gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** @author galitch@google.com (Anton Galitch) */ @RunWith(JUnit4.class) public final class UseCorrectAssertInTestsTest { private static final String ASSERT_THAT_IMPORT = "static com.google.common.truth.Truth.assertThat;"; private static final String ASSERT_WITH_MESSAGE_IMPORT = "static com.google.common.truth.Truth.assertWithMessage;"; private static final String INPUT = "in/FooTest.java"; private static final String OUTPUT = "out/FooTest.java"; private static final String TEST_ONLY = "-XepCompilingTestOnlyCode"; private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance(UseCorrectAssertInTests.class, getClass()); private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(UseCorrectAssertInTests.class, getClass()); @Test public void correctAssertInTest() { refactoringHelper .addInputLines( INPUT, inputWithExpressionAndImport("assertThat(true).isTrue();", ASSERT_THAT_IMPORT)) .expectUnchanged() .doTest(); } @Test public void noAssertInTestsFound() { refactoringHelper .addInputLines(INPUT, inputWithExpression("int a = 1;")) .expectUnchanged() .doTest(); } @Test public void diagnosticIssuedAtFirstAssert() { compilationHelper .addSourceLines( INPUT, "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class FooTest {", " void foo() {", " int x = 1;", " // BUG: Diagnostic contains: UseCorrectAssertInTests", " assert true;", " assert true;", " }", "}") .doTest(); } @Test public void assertInNonTestMethod() { refactoringHelper .addInputLines( INPUT, "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class FooTest {", " void foo() {", " assert true;", " }", "}") .addOutputLines( OUTPUT, "import static com.google.common.truth.Truth.assertThat;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class FooTest {", " void foo() {", " assertThat(true).isTrue();", " }", "}") .doTest(); } @Test public void assertInTestOnlyCode() { refactoringHelper .addInputLines( INPUT, "public class FooTest {", // " void foo() {", " assert true;", " }", "}") .addOutputLines( OUTPUT, "import static com.google.common.truth.Truth.assertThat;", "public class FooTest {", " void foo() {", " assertThat(true).isTrue();", " }", "}") .setArgs(TEST_ONLY) .doTest(); } @Test public void assertInNonTestCode() { refactoringHelper .addInputLines( INPUT, "public class FooTest {", // " void foo() {", " assert true;", " }", "}") .expectUnchanged() .doTest(); } @Test public void wrongAssertInTestWithParentheses() { refactoringHelper .addInputLines(INPUT, inputWithExpression("assert (true);")) .addOutputLines( OUTPUT, inputWithExpressionAndImport("assertThat(true).isTrue();", ASSERT_THAT_IMPORT)) .doTest(); } @Test public void wrongAssertInTestWithoutParentheses() { refactoringHelper .addInputLines(INPUT, inputWithExpression("assert true;")) .addOutputLines( OUTPUT, inputWithExpressionAndImport("assertThat(true).isTrue();", ASSERT_THAT_IMPORT)) .doTest(); } @Test public void wrongAssertInTestWithDetailString() { refactoringHelper .addInputLines(INPUT, inputWithExpression("assert (true) : \"description\";")) .addOutputLines( OUTPUT, inputWithExpressionAndImport( "assertWithMessage(\"description\").that(true).isTrue();", ASSERT_WITH_MESSAGE_IMPORT)) .doTest(); } @Test public void wrongAssertInTestWithDetailStringVariable() { refactoringHelper .addInputLines( INPUT, inputWithExpressions("String desc = \"description\";", "assert (true) : desc;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( "String desc = \"description\";", "assertWithMessage(desc).that(true).isTrue();", ASSERT_WITH_MESSAGE_IMPORT)) .doTest(); } @Test public void wrongAssertInTestWithDetailNonStringVariable() { refactoringHelper .addInputLines(INPUT, inputWithExpressions("Integer desc = 1;", "assert (true) : desc;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( "Integer desc = 1;", "assertWithMessage(desc.toString()).that(true).isTrue();", ASSERT_WITH_MESSAGE_IMPORT)) .doTest(); } @Test public void wrongAssertFalseCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "boolean a = false;", // "assert (!a);")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( "boolean a = false;", "assertThat(a).isFalse();", ASSERT_THAT_IMPORT)) .doTest(); } @Test public void wrongAssertEqualsCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "String a = \"test\";", // "assert a.equals(\"test\");")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( "String a = \"test\";", "assertThat(a).isEqualTo(\"test\");", ASSERT_THAT_IMPORT)) .doTest(); } @Test public void wrongAssertEqualsNullCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer a = null;", // "assert a == null;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( "Integer a = null;", // "assertThat(a).isNull();", ASSERT_THAT_IMPORT)) .doTest(); } @Test public void wrongAssertEqualsNullCaseLeftSide() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer a = null;", // "assert null == a;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( "Integer a = null;", // "assertThat(a).isNull();", ASSERT_THAT_IMPORT)) .doTest(); } @Test public void wrongAssertEqualsNullCaseWithDetail() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer a = null;", // "assert a == null : \"detail\";")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( "Integer a = null;", "assertWithMessage(\"detail\").that(a).isNull();", ASSERT_WITH_MESSAGE_IMPORT)) .doTest(); } @Test public void wrongAssertNotEqualsNullCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer a = 1;", // "assert a != null;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( "Integer a = 1;", // "assertThat(a).isNotNull();", ASSERT_THAT_IMPORT)) .doTest(); } @Test public void wrongAssertReferenceSameCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer a = 1;", // "assert a == 1;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( "Integer a = 1;", // "assertThat(a).isSameInstanceAs(1);", ASSERT_THAT_IMPORT)) .doTest(); } @Test public void wrongAssertReferenceWithParensCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer a = 1;", // "assert (a == 1);")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( "Integer a = 1;", // "assertThat(a).isSameInstanceAs(1);", ASSERT_THAT_IMPORT)) .doTest(); } @Test public void wrongAssertReferenceNotSameCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "Integer a = 1;", // "assert a != 1;")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( "Integer a = 1;", // "assertThat(a).isNotSameInstanceAs(1);", ASSERT_THAT_IMPORT)) .doTest(); } @Test public void wrongAssertReferenceSameCaseWithDetailCase() { refactoringHelper .addInputLines( INPUT, inputWithExpressions( "int a = 1;", // "assert a == 1 : \"detail\";")) .addOutputLines( OUTPUT, inputWithExpressionsAndImport( "int a = 1;", "assertWithMessage(\"detail\").that(a).isSameInstanceAs(1);", ASSERT_WITH_MESSAGE_IMPORT)) .doTest(); } private static String[] inputWithExpressionAndImport(String expr, String importPath) { return inputWithExpressionsAndImport(expr, "", importPath); } private static String[] inputWithExpressionsAndImport( String expr1, String expr2, String importPath) { return new String[] { importPath.isEmpty() ? "" : String.format("import %s", importPath), "import org.junit.Test;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "@RunWith(JUnit4.class)", "public class FooTest {", " @Test", " void foo() {", String.format(" %s", expr1), expr2.isEmpty() ? "" : String.format(" %s", expr2), " }", "}" }; } private static String[] inputWithExpression(String expr) { return inputWithExpressionAndImport(expr, ""); } private static String[] inputWithExpressions(String expr1, String expr2) { return inputWithExpressionsAndImport(expr1, expr2, ""); } }
/* * Copyright 2006-2007 Open Source Applications Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.unitedinternet.cosmo.model.hibernate; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.Vector; import net.fortuna.ical4j.model.Calendar; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.ComponentList; import net.fortuna.ical4j.model.Date; import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.Parameter; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.PropertyList; import net.fortuna.ical4j.model.TimeZone; import net.fortuna.ical4j.model.TimeZoneRegistry; import net.fortuna.ical4j.model.TimeZoneRegistryFactory; import net.fortuna.ical4j.model.component.CalendarComponent; import net.fortuna.ical4j.model.component.VAlarm; import net.fortuna.ical4j.model.component.VEvent; import net.fortuna.ical4j.model.component.VFreeBusy; import net.fortuna.ical4j.model.component.VJournal; import net.fortuna.ical4j.model.component.VTimeZone; import net.fortuna.ical4j.model.component.VToDo; import net.fortuna.ical4j.model.parameter.XParameter; import net.fortuna.ical4j.model.property.Action; import net.fortuna.ical4j.model.property.CalScale; import net.fortuna.ical4j.model.property.Completed; import net.fortuna.ical4j.model.property.DateListProperty; import net.fortuna.ical4j.model.property.DateProperty; import net.fortuna.ical4j.model.property.DtStamp; import net.fortuna.ical4j.model.property.DtStart; import net.fortuna.ical4j.model.property.RecurrenceId; import net.fortuna.ical4j.model.property.Status; import net.fortuna.ical4j.model.property.Trigger; import net.fortuna.ical4j.model.property.Uid; import net.fortuna.ical4j.model.property.Version; import org.apache.commons.lang.StringUtils; import org.unitedinternet.cosmo.calendar.ICalendarUtils; import org.unitedinternet.cosmo.calendar.util.CalendarUtils; import org.unitedinternet.cosmo.dao.ModelValidationException; import org.unitedinternet.cosmo.icalendar.ICalendarConstants; import org.unitedinternet.cosmo.model.AvailabilityItem; import org.unitedinternet.cosmo.model.CalendarCollectionStamp; import org.unitedinternet.cosmo.model.CollectionItem; import org.unitedinternet.cosmo.model.ContentItem; import org.unitedinternet.cosmo.model.EntityFactory; import org.unitedinternet.cosmo.model.EventExceptionStamp; import org.unitedinternet.cosmo.model.EventStamp; import org.unitedinternet.cosmo.model.FreeBusyItem; import org.unitedinternet.cosmo.model.ICalendarItem; import org.unitedinternet.cosmo.model.Item; import org.unitedinternet.cosmo.model.NoteItem; import org.unitedinternet.cosmo.model.NoteOccurrence; import org.unitedinternet.cosmo.model.StampUtils; import org.unitedinternet.cosmo.model.TaskStamp; import org.unitedinternet.cosmo.model.TriageStatus; import org.unitedinternet.cosmo.model.TriageStatusUtil; /** * A component that converts iCalendar objects to entities and vice versa. * Often this is not a straight one-to-one mapping, because recurring * iCalendar events are modeled as multiple events in a single * {@link Calendar}, whereas recurring items are modeled as a master * {@link NoteItem} with zero or more {@link NoteItem} modifications and * potentially also {@link NoteOccurrence}s. */ public class EntityConverter { private static final TimeZoneRegistry TIMEZONE_REGISTRY = TimeZoneRegistryFactory.getInstance().createRegistry(); private EntityFactory entityFactory; public static final String X_OSAF_STARRED = "X-OSAF-STARRED"; /** * Constructor. * @param entityFactory The entity factory. */ public EntityConverter(EntityFactory entityFactory) { this.entityFactory = entityFactory; } /** * Converts a single calendar containing many different * components and component types into a set of * {@link ICalendarItem}. * * @param calendar calendar containing any number and type * of calendar components * @return set of ICalendarItems */ public Set<ICalendarItem> convertCalendar(Calendar calendar) { Set<ICalendarItem> items = new LinkedHashSet<ICalendarItem>(); for(CalendarContext cc: splitCalendar(calendar)) { if(cc.type.equals(Component.VEVENT)) { items.addAll(convertEventCalendar(cc.calendar)); } else if(cc.type.equals(Component.VTODO)) { items.add(convertTaskCalendar(cc.calendar)); } else if(cc.type.equals(Component.VJOURNAL)) { items.add(convertJournalCalendar(cc.calendar)); } else if(cc.type.equals(Component.VFREEBUSY)) { items.add(convertFreeBusyCalendar(cc.calendar)); } } return items; } /** * Expands an event calendar and returns a set of notes representing the * master and exception items. * <p> * The provided note corresponds to the recurrence master or, for * non-recurring items, the single event in the calendar. The result set * includes both the master note as well as a modification note for * exception event in the calendar. * </p> * <p> * If the master note does not already have a UUID or an event stamp, one * is assigned to it. A UUID is assigned because any modification items * that are created require the master's UUID in order to construct * their own. * </p> * <p> * If the given note is already persistent, and the calendar does not * contain an exception event matching an existing modification, that * modification is set inactive. It is still returned in the result set. * </p> * @param note The note item. * @param calendar The calendar. * @return set note item. */ public Set<NoteItem> convertEventCalendar(NoteItem note, Calendar calendar) { EventStamp eventStamp = (EventStamp) note.getStamp(EventStamp.class); if (eventStamp == null) { eventStamp = entityFactory.createEventStamp(note); note.addStamp(eventStamp); } if (note.getUid() == null) { note.setUid(entityFactory.generateUid()); } updateEventInternal(note, calendar); LinkedHashSet<NoteItem> items = new LinkedHashSet<NoteItem>(); items.add(note); // add modifications to set of items for(Iterator<NoteItem> it = note.getModifications().iterator(); it.hasNext();) { NoteItem mod = it.next(); items.add(mod); } return items; } /** * Expands an event calendar and returns a set of notes representing the * master and exception items. * @param calendar The calendar. * @return The convertion. */ public Set<NoteItem> convertEventCalendar(Calendar calendar) { NoteItem note = entityFactory.createNote(); note.setUid(entityFactory.generateUid()); setBaseContentAttributes(note); return convertEventCalendar(note, calendar); } /** * Convert calendar containing single VJOURNAL into NoteItem * @param calendar calendar containing VJOURNAL * @return NoteItem representation of VJOURNAL */ public NoteItem convertJournalCalendar(Calendar calendar) { NoteItem note = entityFactory.createNote(); note.setUid(entityFactory.generateUid()); setBaseContentAttributes(note); return convertJournalCalendar(note, calendar); } /** * Update existing NoteItem with calendar containing single VJOURNAL * @param note note to update * @param calendar calendar containing VJOURNAL * @return NoteItem representation of VJOURNAL */ public NoteItem convertJournalCalendar(NoteItem note, Calendar calendar) { VJournal vj = (VJournal) getMasterComponent(calendar.getComponents(Component.VJOURNAL)); setCalendarAttributes(note, vj); return note; } /** * Convert calendar containing single VTODO into NoteItem * * @param calendar * calendar containing VTODO * @return NoteItem representation of VTODO */ public NoteItem convertTaskCalendar(Calendar calendar) { NoteItem note = entityFactory.createNote(); note.setUid(entityFactory.generateUid()); setBaseContentAttributes(note); return convertTaskCalendar(note, calendar); } /** * Convert calendar containing single VTODO into NoteItem * * @param note * note to update * @param calendar * calendar containing VTODO * @return NoteItem representation of VTODO */ public NoteItem convertTaskCalendar(NoteItem note, Calendar calendar) { note.setTaskCalendar(calendar); VToDo todo = (VToDo) getMasterComponent(calendar.getComponents(Component.VTODO)); setCalendarAttributes(note, todo); return note; } /** * Convert calendar containing single VFREEBUSY into FreeBusyItem * @param calendar calendar containing VFREEBUSY * @return FreeBusyItem representation of VFREEBUSY */ public FreeBusyItem convertFreeBusyCalendar(Calendar calendar) { FreeBusyItem freeBusy = entityFactory.createFreeBusy(); freeBusy.setUid(entityFactory.generateUid()); setBaseContentAttributes(freeBusy); return convertFreeBusyCalendar(freeBusy, calendar); } /** * Convert calendar containing single VFREEBUSY into FreeBusyItem * @param freeBusy freebusy to update * @param calendar calendar containing VFREEBUSY * @return FreeBusyItem representation of VFREEBUSY */ public FreeBusyItem convertFreeBusyCalendar(FreeBusyItem freeBusy, Calendar calendar) { freeBusy.setFreeBusyCalendar(calendar); VFreeBusy vfb = (VFreeBusy) getMasterComponent(calendar.getComponents(Component.VFREEBUSY)); setCalendarAttributes(freeBusy, vfb); return freeBusy; } /** * Returns an icalendar representation of a calendar collection. * @param collection calendar collection * @return icalendar representation of collection */ public Calendar convertCollection(CollectionItem collection) { // verify collection is a calendar CalendarCollectionStamp ccs = StampUtils .getCalendarCollectionStamp(collection); if (ccs == null) { return null; } Calendar calendar = ICalendarUtils.createBaseCalendar(); // extract the supported calendar components for each child item and // add them to the collection calendar object. // index the timezones by tzid so that we only include each tz // once. if for some reason different calendar items have // different tz definitions for a tzid, *shrug* last one wins // for this same reason, we use a single calendar builder/time // zone registry. Map<String, CalendarComponent> tzIdx = new HashMap<>(); for (Item item: collection.getChildren()) { if (!(item instanceof ContentItem)) { continue; } ContentItem contentItem = (ContentItem) item; Calendar childCalendar = convertContent(contentItem); // ignore items that can't be converted if (childCalendar == null) { continue; } // index VTIMEZONE and add all other components for (Object obj: childCalendar.getComponents()) { CalendarComponent comp = (CalendarComponent)obj; if(Component.VTIMEZONE.equals(comp.getName())) { Property tzId = comp.getProperties().getProperty(Property.TZID); if (! tzIdx.containsKey(tzId.getValue())) { tzIdx.put(tzId.getValue(), comp); } } else { calendar.getComponents().add(comp); } } } // add VTIMEZONEs for (CalendarComponent comp: tzIdx.values()) { calendar.getComponents().add(0,comp); } return calendar; } /** * Returns a calendar representing the item. * <p> * If the item is a {@link NoteItem}, delegates to * {@link #convertNote(NoteItem)}. If the item is a {@link ICalendarItem}, * delegates to {@link ICalendarItem#getFullCalendar()}. Otherwise, * returns null. * @param item The content item. * @return The calendar. * </p> */ public Calendar convertContent(ContentItem item) { if(item instanceof NoteItem) { return convertNote((NoteItem) item); } else if(item instanceof FreeBusyItem) { return convertFreeBusyItem((FreeBusyItem) item); } else if(item instanceof AvailabilityItem) { return convertAvailability((AvailabilityItem) item); } return null; } /** * Returns a calendar representing the note. * <p> * If the note is a modification, returns null. If the note has an event * stamp, returns a calendar containing the event and any exceptions. If * the note has a task stamp, returns a calendar containing the task. * Otherwise, returns a calendar containing a journal. * </p> * @param note The note item. * @return calendar The calendar. */ public Calendar convertNote(NoteItem note) { // must be a master note if (note.getModifies()!=null) { return null; } EventStamp event = StampUtils.getEventStamp(note); if (event!=null) { return getCalendarFromEventStamp(event); } return getCalendarFromNote(note); } /** * Converts FreeBusy item. * @param freeBusyItem The freeBusy item. * @return The calendar. */ public Calendar convertFreeBusyItem(FreeBusyItem freeBusyItem) { return freeBusyItem.getFreeBusyCalendar(); } /** * Converts availability. * @param availability The availability item. * @return The calendar. */ public Calendar convertAvailability(AvailabilityItem availability) { return availability.getAvailabilityCalendar(); } /** * Gets calendar from note. * @param note The note item. * @return The calendar. */ protected Calendar getCalendarFromNote(NoteItem note) { // Start with existing calendar if present Calendar calendar = note.getTaskCalendar(); // otherwise, start with new calendar if (calendar == null) { calendar = ICalendarUtils.createBaseCalendar(new VToDo()); } else { // use copy when merging calendar with item properties calendar = CalendarUtils.copyCalendar(calendar); } // merge in displayName,body VToDo task = (VToDo) calendar.getComponent(Component.VTODO); mergeCalendarProperties(task, note); return calendar; } /** * gets calendar from event stamp. * @param stamp The event stamp. * @return The calendar. */ protected Calendar getCalendarFromEventStamp(EventStamp stamp) { Calendar masterCal = CalendarUtils.copyCalendar(stamp.getEventCalendar()); if (masterCal == null) { return null; } // the master calendar might not have any events; for // instance, a client might be trying to save a VTODO if (masterCal.getComponents(Component.VEVENT).isEmpty()) { return masterCal; } VEvent masterEvent = (VEvent) masterCal.getComponents(Component.VEVENT).get(0); VAlarm masterAlarm = getDisplayAlarm(masterEvent); String masterLocation = stamp.getLocation(); // build timezone map that includes all timezones in master calendar ComponentList timezones = masterCal.getComponents(Component.VTIMEZONE); HashMap<String, VTimeZone> tzMap = new HashMap<String, VTimeZone>(); for(Iterator it = timezones.iterator(); it.hasNext();) { VTimeZone vtz = (VTimeZone) it.next(); tzMap.put(vtz.getTimeZoneId().getValue(), vtz); } // check start/end date tz is included, and add if it isn't String tzid = getTzId(stamp.getStartDate()); if(tzid!=null && !tzMap.containsKey(tzid)) { TimeZone tz = TIMEZONE_REGISTRY.getTimeZone(tzid); if(tz!=null) { VTimeZone vtz = tz.getVTimeZone(); masterCal.getComponents().add(0, vtz); tzMap.put(tzid, vtz); } } tzid = getTzId(stamp.getEndDate()); if(tzid!=null && !tzMap.containsKey(tzid)) { TimeZone tz = TIMEZONE_REGISTRY.getTimeZone(tzid); if(tz!=null) { VTimeZone vtz = tz.getVTimeZone(); masterCal.getComponents().add(0, vtz); tzMap.put(tzid, vtz); } } // merge item properties to icalendar props mergeCalendarProperties(masterEvent, (NoteItem) stamp.getItem()); // bug 9606: handle displayAlarm with no trigger by not including // in exported icalendar if(masterAlarm!=null && stamp.getDisplayAlarmTrigger()==null) { masterEvent.getAlarms().remove(masterAlarm); masterAlarm = null; } // If event is not recurring, skip all the event modification // processing if (!stamp.isRecurring()) { return masterCal; } // add all exception events NoteItem note = (NoteItem) stamp.getItem(); TreeMap<String, VEvent> sortedMap = new TreeMap<String, VEvent>(); for(NoteItem exception : note.getModifications()) { EventExceptionStamp exceptionStamp = HibEventExceptionStamp.getStamp(exception); // if modification isn't stamped as an event then ignore if (exceptionStamp==null) { continue; } // Get exception event copy VEvent exceptionEvent = (VEvent) CalendarUtils .copyComponent(exceptionStamp.getExceptionEvent()); // ensure DURATION or DTEND exists on modfication if (ICalendarUtils.getDuration(exceptionEvent) == null) { ICalendarUtils.setDuration(exceptionEvent, ICalendarUtils .getDuration(masterEvent)); } // merge item properties to icalendar props mergeCalendarProperties(exceptionEvent, exception); // check for inherited anyTime if(exceptionStamp.isAnyTime()==null) { DtStart modDtStart = exceptionEvent.getStartDate(); // remove "missing" value modDtStart.getParameters().remove(modDtStart.getParameter(ICalendarConstants.PARAM_X_OSAF_ANYTIME)); // add inherited value if(stamp.isAnyTime()) { modDtStart.getParameters().add(getAnyTimeXParam()); } } // Check for inherited displayAlarm, which is represented // by a valarm with no TRIGGER VAlarm displayAlarm = getDisplayAlarm(exceptionEvent); if(displayAlarm !=null && exceptionStamp.getDisplayAlarmTrigger()==null) { exceptionEvent.getAlarms().remove(displayAlarm); if (masterAlarm != null) { exceptionEvent.getAlarms().add(masterAlarm); } } // Check for inherited LOCATION which is represented as null LOCATION // If inherited, and master event has a LOCATION, then add it to exception if(exceptionStamp.getLocation()==null && masterLocation!=null) { ICalendarUtils.setLocation(masterLocation, exceptionEvent); } sortedMap.put(exceptionStamp.getRecurrenceId().toString(), exceptionEvent); // verify that timezones are present for exceptions, and add if not tzid = getTzId(exceptionStamp.getStartDate()); if(tzid!=null && !tzMap.containsKey(tzid)) { TimeZone tz = TIMEZONE_REGISTRY.getTimeZone(tzid); if(tz!=null) { VTimeZone vtz = tz.getVTimeZone(); masterCal.getComponents().add(0, vtz); tzMap.put(tzid, vtz); } } tzid = getTzId(exceptionStamp.getEndDate()); if(tzid!=null && !tzMap.containsKey(tzid)) { TimeZone tz = TIMEZONE_REGISTRY.getTimeZone(tzid); if(tz!=null) { VTimeZone vtz = tz.getVTimeZone(); masterCal.getComponents().add(0, vtz); tzMap.put(tzid, vtz); } } } masterCal.getComponents().addAll(sortedMap.values()); return masterCal; } /** * Merges calendar properties. * @param event The event. * @param note The note item. */ private void mergeCalendarProperties(VEvent event, NoteItem note) { //summary = displayName //description = body //uid = icalUid //dtstamp = clientModifiedDate/modifiedDate boolean isMod = note.getModifies()!=null; if (isMod) { ICalendarUtils.setUid(note.getModifies().getIcalUid(), event); } else { ICalendarUtils.setUid(note.getIcalUid(), event); } // inherited displayName and body should always be serialized if (event.getSummary() != null) { ICalendarUtils.setSummary(event.getSummary().getValue(), event); } else if (note.getDisplayName()==null && isMod) { ICalendarUtils.setSummary(note.getModifies().getDisplayName(), event); } else { ICalendarUtils.setSummary(note.getDisplayName(), event); } if (event.getDescription() != null) { ICalendarUtils.setDescription(event.getDescription().getValue(), event); } else if (note.getBody()==null && isMod) { ICalendarUtils.setDescription(note.getModifies().getBody(), event); } else { ICalendarUtils.setDescription(note.getBody(), event); } if (note.getClientModifiedDate()!=null) { ICalendarUtils.setDtStamp(note.getClientModifiedDate(), event); } else { ICalendarUtils.setDtStamp(note.getModifiedDate(), event); } if (StampUtils.getTaskStamp(note) != null) { ICalendarUtils.setXProperty(X_OSAF_STARRED, "TRUE", event); } else { ICalendarUtils.setXProperty(X_OSAF_STARRED, null, event); } } /** * Merges calendar properties. * @param task The task. * @param note The note item. */ private void mergeCalendarProperties(VToDo task, NoteItem note) { //uid = icaluid or uid //summary = displayName //description = body //dtstamp = clientModifiedDate/modifiedDate //completed = triageStatus==DONE/triageStatusRank String icalUid = note.getIcalUid(); if (icalUid==null) { icalUid = note.getUid(); } if (note.getClientModifiedDate()!=null) { ICalendarUtils.setDtStamp(note.getClientModifiedDate(), task); } else { ICalendarUtils.setDtStamp(note.getModifiedDate(), task); } ICalendarUtils.setUid(icalUid, task); ICalendarUtils.setSummary(note.getDisplayName(), task); ICalendarUtils.setDescription(note.getBody(), task); // Set COMPLETED/STATUS if triagestatus is DONE TriageStatus ts = note.getTriageStatus(); DateTime completeDate = null; if(ts!=null && ts.getCode()==TriageStatus.CODE_DONE) { ICalendarUtils.setStatus(Status.VTODO_COMPLETED, task); if (ts.getRank() != null) { completeDate = new DateTime(TriageStatusUtil.getDateFromRank(ts.getRank())); } } ICalendarUtils.setCompleted(completeDate, task); if (StampUtils.getTaskStamp(note) != null) { ICalendarUtils.setXProperty(X_OSAF_STARRED, "TRUE", task); } else { ICalendarUtils.setXProperty(X_OSAF_STARRED, null, task); } } /** * Gets display alarm. * @param event The event. * @return The alarm. */ private VAlarm getDisplayAlarm(VEvent event) { for(Iterator it = event.getAlarms().iterator();it.hasNext();) { VAlarm alarm = (VAlarm) it.next(); if (alarm.getProperties().getProperty(Property.ACTION).equals(Action.DISPLAY)) { return alarm; } } return null; } /** * Gets timezone id. * @param date The date. * @return The id. */ private String getTzId(Date date) { if(date instanceof DateTime) { DateTime dt = (DateTime) date; if (dt.getTimeZone()!=null) { return dt.getTimeZone().getID(); } } return null; } /** * Gets any time x param. * @return The parameter. */ private Parameter getAnyTimeXParam() { return new XParameter(ICalendarConstants.PARAM_X_OSAF_ANYTIME, ICalendarConstants.VALUE_TRUE); } /** * Updates event internal. * @param masterNote The master note. * @param calendar The calendar. */ private void updateEventInternal(NoteItem masterNote, Calendar calendar) { HashMap<Date, VEvent> exceptions = new HashMap<Date, VEvent>(); Calendar masterCalendar = calendar; ComponentList vevents = masterCalendar.getComponents().getComponents( Component.VEVENT); EventStamp eventStamp = StampUtils.getEventStamp(masterNote); // get list of exceptions (VEVENT with RECURRENCEID) for (Iterator<VEvent> i = vevents.iterator(); i.hasNext();) { VEvent event = i.next(); // make sure event has DTSTAMP, otherwise validation will fail if (event.getDateStamp()==null) { event.getProperties().add(new DtStamp(new DateTime())); } if (event.getRecurrenceId() != null) { Date recurrenceIdDate = event.getRecurrenceId().getDate(); exceptions.put(recurrenceIdDate, event); } } // Remove all exceptions from master calendar as these // will be stored in each NoteItem modification's EventExceptionStamp for (Entry<Date, VEvent> entry : exceptions.entrySet()) { masterCalendar.getComponents().remove(entry.getValue()); } // Master calendar includes everything in the original calendar minus // any exception events (VEVENT with RECURRENCEID) eventStamp.setEventCalendar(masterCalendar); compactTimezones(masterCalendar); VEvent event = eventStamp.getEvent(); // verify master event exists if (event==null) { throw new ModelValidationException("no master calendar component found"); } setCalendarAttributes(masterNote, event); // synchronize exceptions with master NoteItem modifications syncExceptions(exceptions, masterNote); } /** * Compact timezones. * @param calendar The calendar. */ private void compactTimezones(Calendar calendar) { if (calendar==null) { return; } // Get list of timezones in master calendar and remove all timezone // definitions that are in the registry. The idea is to not store // extra data. Instead, the timezones will be added to the calendar // by the getCalendar() api. ComponentList timezones = calendar.getComponents(Component.VTIMEZONE); ArrayList toRemove = new ArrayList(); for(Iterator it = timezones.iterator();it.hasNext();) { VTimeZone vtz = (VTimeZone) it.next(); String tzid = vtz.getTimeZoneId().getValue(); TimeZone tz = TIMEZONE_REGISTRY.getTimeZone(tzid); // Remove timezone iff it matches the one in the registry if(tz!=null && vtz.equals(tz.getVTimeZone())) { toRemove.add(vtz); } } // remove known timezones from master calendar calendar.getComponents().removeAll(toRemove); } /** * Sync exceptions. * @param exceptions The exceptions. * @param masterNote The master note. */ private void syncExceptions(Map<Date, VEvent> exceptions, NoteItem masterNote) { for (Entry<Date, VEvent> entry : exceptions.entrySet()) { syncException(entry.getValue(), masterNote); } // remove old exceptions for (NoteItem noteItem : masterNote.getModifications()) { EventExceptionStamp eventException = StampUtils.getEventExceptionStamp(noteItem); if (eventException==null || !exceptions.containsKey(eventException.getRecurrenceId())) { noteItem.setIsActive(false); } } } /** * Sync exception. * @param event The event. * @param masterNote The master note. */ private void syncException(VEvent event, NoteItem masterNote) { NoteItem mod = getModification(masterNote, event.getRecurrenceId().getDate()); if (mod == null) { // create if not present createNoteModification(masterNote, event); } else { // update existing mod updateNoteModification(mod, event); } } /** * Gets modification. * @param masterNote The master note. * @param recurrenceId The reccurence id. * @return The note item. */ private NoteItem getModification(NoteItem masterNote, Date recurrenceId) { for (NoteItem mod : masterNote.getModifications()) { EventExceptionStamp exceptionStamp = StampUtils.getEventExceptionStamp(mod); // only interested in mods with event stamp if (exceptionStamp == null) { continue; } if (exceptionStamp.getRecurrenceId().equals(recurrenceId)) { return mod; } } return null; } /** * Creates note modification. * @param masterNote masterNote. * @event The event. */ private void createNoteModification(NoteItem masterNote, VEvent event) { NoteItem noteMod = entityFactory.createNote(); Calendar exceptionCal = null; // a note modification should inherit the calendar product info as its master component. if(masterNote.getStamp(EventStamp.class) != null) { EventStamp masterStamp = (EventStamp) masterNote.getStamp(EventStamp.class); Calendar masterCal = masterStamp.getEventCalendar(); if(masterCal != null && masterCal.getProductId() != null) { exceptionCal = new Calendar(); exceptionCal.getProperties().add(masterCal.getProductId()); exceptionCal.getProperties().add(masterCal.getVersion() != null? masterCal.getVersion(): Version.VERSION_2_0); exceptionCal.getProperties().add(masterCal.getCalendarScale() != null? masterCal.getCalendarScale(): CalScale.GREGORIAN); exceptionCal.getComponents().add(event); } } EventExceptionStamp exceptionStamp = entityFactory.createEventExceptionStamp(noteMod); exceptionStamp.setEventCalendar(exceptionCal); exceptionStamp.setExceptionEvent(event); noteMod.addStamp(exceptionStamp); noteMod.setUid(new ModificationUidImpl(masterNote, event.getRecurrenceId() .getDate()).toString()); noteMod.setOwner(masterNote.getOwner()); noteMod.setName(noteMod.getUid()); // copy VTIMEZONEs to front if present EventStamp es = StampUtils.getEventStamp(masterNote); ComponentList vtimezones = es.getEventCalendar().getComponents(Component.VTIMEZONE); for(Object obj : vtimezones) { VTimeZone vtimezone = (VTimeZone)obj; exceptionStamp.getEventCalendar().getComponents().add(0, vtimezone); } setBaseContentAttributes(noteMod); noteMod.setLastModifiedBy(masterNote.getLastModifiedBy()); noteMod.setModifies(masterNote); masterNote.addModification(noteMod); setCalendarAttributes(noteMod, event); } /** * Updates note modification. * @param noteMod The note item modified. * @param event The event. */ private void updateNoteModification(NoteItem noteMod, VEvent event) { EventExceptionStamp exceptionStamp = StampUtils.getEventExceptionStamp(noteMod); exceptionStamp.setExceptionEvent(event); // copy VTIMEZONEs to front if present ComponentList vtimezones = exceptionStamp.getMasterStamp() .getEventCalendar().getComponents(Component.VTIMEZONE); for(Object obj: vtimezones) { VTimeZone vtimezone = (VTimeZone)obj; exceptionStamp.getEventCalendar().getComponents().add(0, vtimezone); } noteMod.setClientModifiedDate(new Date()); noteMod.setLastModifiedBy(noteMod.getModifies().getLastModifiedBy()); noteMod.setLastModification(ContentItem.Action.EDITED); setCalendarAttributes(noteMod, event); } /** * Sets base content attributes. * @param item The content item. */ private void setBaseContentAttributes(ContentItem item) { TriageStatus ts = entityFactory.createTriageStatus(); TriageStatusUtil.initialize(ts); item.setClientCreationDate(new Date()); item.setClientModifiedDate(item.getClientCreationDate()); item.setTriageStatus(ts); item.setLastModification(ContentItem.Action.CREATED); item.setSent(Boolean.FALSE); item.setNeedsReply(Boolean.FALSE); } /** * Sets calendar attributes. * @param note The note item. * @param event The event. */ private void setCalendarAttributes(NoteItem note, VEvent event) { // UID (only set if master) if(event.getUid()!=null && note.getModifies()==null) { note.setIcalUid(event.getUid().getValue()); } // for now displayName is limited to 1024 chars if (event.getSummary() != null) { note.setDisplayName(StringUtils.substring(event.getSummary() .getValue(), 0, 1024)); } if (event.getDescription() != null) { note.setBody(event.getDescription().getValue()); } // look for DTSTAMP if(event.getDateStamp()!=null) { note.setClientModifiedDate(event.getDateStamp().getDate()); } // look for absolute VALARM VAlarm va = ICalendarUtils.getDisplayAlarm(event); if (va != null && va.getTrigger()!=null) { Trigger trigger = va.getTrigger(); Date reminderTime = trigger.getDateTime(); if (reminderTime != null) { note.setReminderTime(reminderTime); } } // calculate triage status based on start date java.util.Date now =java.util.Calendar.getInstance().getTime(); boolean later = event.getStartDate().getDate().after(now); int code = later ? TriageStatus.CODE_LATER : TriageStatus.CODE_DONE; TriageStatus triageStatus = note.getTriageStatus(); // initialize TriageStatus if not present if (triageStatus == null) { triageStatus = TriageStatusUtil.initialize(entityFactory .createTriageStatus()); note.setTriageStatus(triageStatus); } triageStatus.setCode(code); // check for X-OSAF-STARRED if ("TRUE".equals(ICalendarUtils.getXProperty(X_OSAF_STARRED, event))) { TaskStamp ts = StampUtils.getTaskStamp(note); if (ts == null) { note.addStamp(entityFactory.createTaskStamp()); } } } /** * Sets calendar attributes. * @param note The note item. * @param task The task vToDo. */ private void setCalendarAttributes(NoteItem note, VToDo task) { // UID if(task.getUid()!=null) { note.setIcalUid(task.getUid().getValue()); } // for now displayName is limited to 1024 chars if (task.getSummary() != null) { note.setDisplayName(StringUtils.substring(task.getSummary() .getValue(), 0, 1024)); } if (task.getDescription() != null) { note.setBody(task.getDescription().getValue()); } // look for DTSTAMP if (task.getDateStamp() != null) { note.setClientModifiedDate(task.getDateStamp().getDate()); } // look for absolute VALARM VAlarm va = ICalendarUtils.getDisplayAlarm(task); if (va != null && va.getTrigger()!=null) { Trigger trigger = va.getTrigger(); Date reminderTime = trigger.getDateTime(); if (reminderTime != null) { note.setReminderTime(reminderTime); } } // look for COMPLETED or STATUS:COMPLETED Completed completed = task.getDateCompleted(); Status status = task.getStatus(); TriageStatus ts = note.getTriageStatus(); // Initialize TriageStatus if necessary if(completed!=null || Status.VTODO_COMPLETED.equals(status)) { if (ts == null) { ts = TriageStatusUtil.initialize(entityFactory .createTriageStatus()); note.setTriageStatus(ts); } // TriageStatus.code will be DONE note.getTriageStatus().setCode(TriageStatus.CODE_DONE); // TriageStatus.rank will be the COMPLETED date if present // or currentTime if(completed!=null) { note.getTriageStatus().setRank( TriageStatusUtil.getRank(completed.getDate().getTime())); } else { note.getTriageStatus().setRank( TriageStatusUtil.getRank(System.currentTimeMillis())); } } // check for X-OSAF-STARRED if ("TRUE".equals(ICalendarUtils.getXProperty(X_OSAF_STARRED, task))) { TaskStamp taskStamp = StampUtils.getTaskStamp(note); if (taskStamp == null) { note.addStamp(entityFactory.createTaskStamp()); } } } /** * Sets calendar attributes. * @param note The note item. * @param journal The VJournal. */ private void setCalendarAttributes(NoteItem note, VJournal journal) { // UID if(journal.getUid()!=null) { note.setIcalUid(journal.getUid().getValue()); } // for now displayName is limited to 1024 chars if (journal.getSummary() != null) { note.setDisplayName(StringUtils.substring(journal.getSummary() .getValue(), 0, 1024)); } if (journal.getDescription() != null) { note.setBody(journal.getDescription().getValue()); } // look for DTSTAMP if (journal.getDateStamp() != null) { note.setClientModifiedDate(journal.getDateStamp().getDate()); } } /** * Sets calendar attributes. * @param freeBusy The freeBusy. * @param vfb The VFreeBusy. */ private void setCalendarAttributes(FreeBusyItem freeBusy, VFreeBusy vfb) { // UID if(vfb.getUid()!=null) { freeBusy.setIcalUid(vfb.getUid().getValue()); } // look for DTSTAMP if (vfb.getDateStamp() != null) { freeBusy.setClientModifiedDate(vfb.getDateStamp().getDate()); } } /** * gets master component. * @param components The component list. * @return The component. */ private Component getMasterComponent(ComponentList components) { Iterator<Component> it = components.iterator(); while(it.hasNext()) { Component c = it.next(); if(c.getProperty(Property.RECURRENCE_ID)==null) { return c; } } throw new IllegalArgumentException("no master found"); } /** * Given a Calendar with no VTIMZONE components, go through * all other components and add all relevent VTIMEZONES. * @param calendar The calendar. */ private void addTimezones(Calendar calendar) { ComponentList comps = calendar.getComponents(); Set<VTimeZone> timezones = new HashSet<VTimeZone>(); for(Iterator<Component> it = comps.iterator();it.hasNext();) { Component comp = it.next(); PropertyList props = comp.getProperties(); for(Iterator<Property> it2 = props.iterator();it2.hasNext();) { Property prop = it2.next(); if(prop instanceof DateProperty) { DateProperty dateProp = (DateProperty) prop; Date d = dateProp.getDate(); if(d instanceof DateTime) { DateTime dt = (DateTime)d; if(dt.getTimeZone()!=null) { timezones.add(dt.getTimeZone().getVTimeZone()); } } } else if(prop instanceof DateListProperty) { DateListProperty dateProp = (DateListProperty) prop; if(dateProp.getDates().getTimeZone()!=null) { timezones.add(dateProp.getDates().getTimeZone().getVTimeZone()); } } } } for(VTimeZone vtz: timezones) { calendar.getComponents().add(0, vtz); } } /** * Given a calendar with many different components, split into * separate calendars that contain only a single component type * and a single UID. * @param calendar The calendar. * @return The split calendar. */ private CalendarContext[] splitCalendar(Calendar calendar) { Vector<CalendarContext> contexts = new Vector<CalendarContext>(); Set<String> allComponents = new HashSet<String>(); Map<String, ComponentList> componentMap = new HashMap<String, ComponentList>(); ComponentList comps = calendar.getComponents(); for(Iterator<Component> it = comps.iterator(); it.hasNext();) { Component comp = it.next(); // ignore vtimezones for now if(comp instanceof VTimeZone) { continue; } Uid uid = (Uid) comp.getProperty(Property.UID); RecurrenceId rid = (RecurrenceId) comp.getProperty(Property.RECURRENCE_ID); String key = uid.getValue(); if(rid!=null) { key+=rid.toString(); } // ignore duplicates if(allComponents.contains(key)) { continue; } allComponents.add(key); ComponentList cl = componentMap.get(uid.getValue()); if(cl==null) { cl = new ComponentList(); componentMap.put(uid.getValue(), cl); } cl.add(comp); } for(Entry<String, ComponentList> entry : componentMap.entrySet()) { Component firstComp = (Component) entry.getValue().get(0); Calendar cal = ICalendarUtils.createBaseCalendar(); cal.getComponents().addAll(entry.getValue()); addTimezones(cal); CalendarContext cc = new CalendarContext(); cc.calendar = cal; cc.type = firstComp.getName(); contexts.add(cc); } return contexts.toArray(new CalendarContext[contexts.size()]); } /** * Gets entity factory. * @return The entity factory. */ public EntityFactory getEntityFactory() { return entityFactory; } /** * Container for a calendar containing single component type (can * be multiple components if the component is recurring and has * modifications), and the component type. */ static class CalendarContext { String type; Calendar calendar; } }
package edu.jhu.prim.vector; import java.util.Arrays; import edu.jhu.prim.Primitives; import edu.jhu.prim.arrays.IntArrays; import edu.jhu.prim.util.Lambda; import edu.jhu.prim.util.Lambda.FnLongIntToInt; import edu.jhu.prim.util.Lambda.FnLongIntToVoid; import edu.jhu.prim.util.SafeCast; import edu.jhu.prim.vector.LongIntHashVector.SparseBinaryOpApplier; //TODO: Implement Iterable<LongIntEntry>. public class LongIntDenseVector extends AbstractLongIntVector implements LongIntVector { private static final long serialVersionUID = 1L; /** The value given to non-explicit entries in the vector. */ private static final int missingEntries = 0; /** The internal array representing this vector. */ private int[] elements; /** The index after the last explicit entry in the vector. */ private int idxAfterLast; public LongIntDenseVector() { this(8); } public LongIntDenseVector(int initialCapacity) { elements = new int[initialCapacity]; idxAfterLast = 0; } public LongIntDenseVector(int[] elements) { this.elements = elements; idxAfterLast = elements.length; } /** Gets a deep copy of this vector. */ public LongIntDenseVector(LongIntDenseVector other) { this.elements = IntArrays.copyOf(other.elements); this.idxAfterLast = other.idxAfterLast; } /** Copy constructor. */ public LongIntDenseVector(LongIntVector other) { // TODO: Exploit the number of non-zero entries in other. this(); final LongIntDenseVector thisVec = this; other.iterate(new FnLongIntToVoid() { @Override public void call(long idx, int val) { thisVec.set(idx, val); } }); } /** Copy factory method. */ @Override public LongIntVector copy() { return new LongIntDenseVector(this); } /** * Gets the i'th entry in the vector. * @param i The index of the element to get. * @return The value of the element to get. */ public int get(long i) { if (i < 0 || i >= idxAfterLast) { return missingEntries; } return elements[SafeCast.safeLongToInt(i)]; } /** * Sets the i'th entry of the vector to the given value. * @param i The index to set. * @param value The value to set. */ public int set(long idx, int value) { int i = SafeCast.safeLongToInt(idx); idxAfterLast = Math.max(idxAfterLast, i + 1); ensureCapacity(idxAfterLast); int old = elements[i]; elements[i] = value; return old; } public void add(long idx, int value) { int i = SafeCast.safeLongToInt(idx); idxAfterLast = Math.max(idxAfterLast, i + 1); ensureCapacity(idxAfterLast); elements[i] += value; } public void scale(int multiplier) { for (int i=0; i<idxAfterLast; i++) { elements[i] *= multiplier; } } @Override public int dot(int[] other) { int max = Math.min(idxAfterLast, other.length); int dot = 0; for (int i=0; i<max; i++) { dot += elements[i] * other[i]; } return dot; } @Override public int dot(LongIntVector y) { if (y instanceof LongIntDenseVector){ LongIntDenseVector other = (LongIntDenseVector) y; int max = Math.min(idxAfterLast, other.idxAfterLast); int dot = 0; for (int i=0; i<max; i++) { dot += elements[i] * y.get(i); } return dot; } else { return y.dot(this); } } @Override public void apply(FnLongIntToInt function) { for (int i=0; i<idxAfterLast; i++) { elements[i] = function.call(i, elements[i]); } } @Override public void iterate(FnLongIntToVoid function) { for (int i=0; i<idxAfterLast; i++) { function.call(i, elements[i]); } } /** Updates this vector to be the entrywise sum of this vector with the other. */ public void add(LongIntVector other) { if (other instanceof LongIntUnsortedVector) { LongIntUnsortedVector vec = (LongIntUnsortedVector) other; for (int i=0; i<vec.top; i++) { this.add(vec.idx[i], vec.vals[i]); } } else { // TODO: Add special case for LongIntDenseVector. other.iterate(new SparseBinaryOpApplier(this, new Lambda.IntAdd())); } } /** Updates this vector to be the entrywise difference of this vector with the other. */ public void subtract(LongIntVector other) { if (other instanceof LongIntUnsortedVector) { LongIntUnsortedVector vec = (LongIntUnsortedVector) other; for (int i=0; i<vec.top; i++) { this.add(vec.idx[i], -vec.vals[i]); } } else { // TODO: Add special case for LongIntDenseVector. other.iterate(new SparseBinaryOpApplier(this, new Lambda.IntSubtract())); } } /** Updates this vector to be the entrywise product (i.e. Hadamard product) of this vector with the other. */ public void product(LongIntVector other) { // TODO: Add special case for LongIntDenseVector. for (int i=0; i<idxAfterLast; i++) { elements[i] *= other.get(i); } } /** * Gets the index of the first element in this vector with the specified * value, or -1 if it is not present. * * @param value The value to search for. * @param delta The delta with which to evaluate equality. * @return The index or -1 if not present. */ public int lookupIndex(int value) { for (int i=0; i<elements.length; i++) { if (Primitives.equals(elements[i], value)) { return i; } } return -1; } /** Gets a NEW array containing all the elements in this vector. */ public int[] toNativeArray() { return Arrays.copyOf(elements, idxAfterLast); } /** Gets the INTERNAL representation of this vector. */ public int[] getInternalElements() { return elements; } /** * Gets the number of explicit entries in this vector. * * For a dense vector, this is just the size of the vector. * * For a sparse vector, this is the number of entries which are explicitly * represented in the vector. * * The contract of this method is that a call to this.apply(fn) will visit n * entries where n = this.getNumExplicitEntries(). * * @return The number of explicit entries. */ public int getNumExplicitEntries() { return idxAfterLast; } /** * Gets the number of implicit entries. * * For a dense vector, this is just the size of the vector. * * For a sparse vector, this is index after the last explicit entry in the * vector. This corresponds to (1 + i) where i is the highest index * explicitly represented. * * The contract of this method is that for any j >= * this.getNumImplicitEntries(), this.get(j) will return 0. * * @return The number of implicit entries. */ public long getNumImplicitEntries() { return idxAfterLast; } /** * Trims the internal array to exactly the size of the list. */ public void trimToSize() { if (idxAfterLast != elements.length) { elements = Arrays.copyOf(elements, idxAfterLast); } } /** * Ensure that the internal array has space to contain the specified number of elements. * @param size The number of elements. */ private void ensureCapacity(int size) { elements = ensureCapacity(elements, size); } /** * Ensure that the array has space to contain the specified number of elements. * @param elements The array. * @param size The number of elements. */ public static int[] ensureCapacity(int[] elements, int size) { if (size > elements.length) { int[] tmp = new int[size*2]; System.arraycopy(elements, 0, tmp, 0, elements.length); elements = tmp; } return elements; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("LongIntDenseVector ["); for (int i=0; i<idxAfterLast; i++) { sb.append(elements[i]); if (i < idxAfterLast - 1) { sb.append(", "); } } sb.append("]"); return sb.toString(); } public int infinityNorm() { int maxAbs = 0; for (int i=0; i<idxAfterLast; i++) { int abs = Math.abs(elements[i]); if (abs > maxAbs) { maxAbs = abs; } } return maxAbs; } }
/* * Copyright Terracotta, 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 org.ehcache.clustered.client.internal.store; import org.ehcache.clustered.client.config.ClusteredResourceType; import org.ehcache.clustered.client.config.DedicatedClusteredResourcePool; import org.ehcache.clustered.client.internal.config.DedicatedClusteredResourcePoolImpl; import org.ehcache.clustered.client.service.ClusteringService; import org.ehcache.config.Eviction; import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePool; import org.ehcache.config.ResourcePools; import org.ehcache.config.ResourceType; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.config.ResourcePoolsImpl; import org.ehcache.core.internal.service.ServiceLocator; import org.ehcache.core.spi.service.DiskResourceService; import org.ehcache.core.spi.store.Store; import org.ehcache.expiry.Expirations; import org.ehcache.expiry.Expiry; import org.ehcache.impl.internal.store.disk.OffHeapDiskStore; import org.ehcache.impl.internal.store.heap.OnHeapStore; import org.ehcache.impl.internal.store.offheap.OffHeapStore; import org.ehcache.impl.internal.store.tiering.TieredStore; import org.ehcache.impl.serialization.LongSerializer; import org.ehcache.impl.serialization.StringSerializer; import org.ehcache.spi.serialization.Serializer; import org.ehcache.spi.service.ServiceConfiguration; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import static org.ehcache.core.internal.service.ServiceLocator.dependencySet; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; /** * Provides basic tests for {@link org.ehcache.clustered.client.internal.store.ClusteredStore.Provider ClusteredStore.Provider}. */ public class ClusteredStoreProviderTest { @Test public void testRank() throws Exception { ClusteredStore.Provider provider = new ClusteredStore.Provider(); ServiceLocator serviceLocator = dependencySet() .with(new TieredStore.Provider()) .with(new OnHeapStore.Provider()) .with(new OffHeapStore.Provider()) .with(mock(DiskResourceService.class)) .with(new OffHeapDiskStore.Provider()) .with(mock(ClusteringService.class)).build(); provider.start(serviceLocator); assertRank(provider, 1, ClusteredResourceType.Types.DEDICATED); assertRank(provider, 1, ClusteredResourceType.Types.SHARED); assertRank(provider, 0, new UnmatchedResourceType()); } @Test public void testRankTiered() throws Exception { TieredStore.Provider provider = new TieredStore.Provider(); ServiceLocator serviceLocator = dependencySet() .with(provider) .with(new ClusteredStore.Provider()) .with(new OnHeapStore.Provider()) .with(new OffHeapStore.Provider()) .with(new OffHeapDiskStore.Provider()) .with(mock(DiskResourceService.class)) .with(mock(ClusteringService.class)).build(); serviceLocator.startAllServices(); assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.DISK); assertRank(provider, 2, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.HEAP); assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.OFFHEAP); assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP); assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.DISK, ResourceType.Core.HEAP); assertRank(provider, 3, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP); assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP); assertRank(provider, 0, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK); assertRank(provider, 2, ClusteredResourceType.Types.SHARED, ResourceType.Core.HEAP); assertRank(provider, 0, ClusteredResourceType.Types.SHARED, ResourceType.Core.OFFHEAP); assertRank(provider, 0, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP); assertRank(provider, 0, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.HEAP); assertRank(provider, 3, ClusteredResourceType.Types.SHARED, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP); assertRank(provider, 0, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP); // Multiple clustered resources not currently supported assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK); assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.HEAP); assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.OFFHEAP); assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP); assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.HEAP); assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP); assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP); } @Test public void testAuthoritativeRank() throws Exception { ClusteredStore.Provider provider = new ClusteredStore.Provider(); ServiceLocator serviceLocator = dependencySet().with(mock(ClusteringService.class)).build(); provider.start(serviceLocator); assertThat(provider.rankAuthority(ClusteredResourceType.Types.DEDICATED, Collections.<ServiceConfiguration<?>>emptyList()), is(1)); assertThat(provider.rankAuthority(ClusteredResourceType.Types.SHARED, Collections.<ServiceConfiguration<?>>emptyList()), is(1)); assertThat(provider.rankAuthority(new UnmatchedResourceType(), Collections.<ServiceConfiguration<?>>emptyList()), is(0)); } private void assertRank(final Store.Provider provider, final int expectedRank, final ResourceType<?>... resources) { final List<ServiceConfiguration<?>> serviceConfigs = Collections.emptyList(); if (expectedRank == -1) { try { provider.rank(new HashSet<ResourceType<?>>(Arrays.asList(resources)), serviceConfigs); fail(); } catch (IllegalStateException e) { // Expected assertThat(e.getMessage(), startsWith("No Store.Provider ")); } } else { assertThat(provider.rank(new HashSet<ResourceType<?>>(Arrays.asList(resources)), serviceConfigs), is(expectedRank)); } } private Store.Configuration<Long, String> getStoreConfig() { return new Store.Configuration<Long, String>() { @Override public Class<Long> getKeyType() { return Long.class; } @Override public Class<String> getValueType() { return String.class; } @Override public EvictionAdvisor<? super Long, ? super String> getEvictionAdvisor() { return Eviction.noAdvice(); } @Override public ClassLoader getClassLoader() { return getClass().getClassLoader(); } @Override public Expiry<? super Long, ? super String> getExpiry() { return Expirations.noExpiration(); } @Override @SuppressWarnings("unchecked") public ResourcePools getResourcePools() { Map<ClusteredResourceType<DedicatedClusteredResourcePool>, DedicatedClusteredResourcePoolImpl> poolMap = Collections .singletonMap(ClusteredResourceType.Types.DEDICATED, new DedicatedClusteredResourcePoolImpl("test", 10, MemoryUnit.MB)); return new ResourcePoolsImpl((Map) poolMap); } @Override public Serializer<Long> getKeySerializer() { return new LongSerializer(); } @Override public Serializer<String> getValueSerializer() { return new StringSerializer(); } @Override public int getDispatcherConcurrency() { return 1; } }; } private static class UnmatchedResourceType implements ResourceType<ResourcePool> { @Override public Class<ResourcePool> getResourcePoolClass() { return ResourcePool.class; } @Override public boolean isPersistable() { return true; } @Override public boolean requiresSerialization() { return true; } @Override public int getTierHeight() { return 10; } } }
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.application.options; import com.intellij.application.options.codeStyle.CodeStyleBlankLinesPanel; import com.intellij.application.options.codeStyle.CodeStyleSchemesModel; import com.intellij.application.options.codeStyle.CodeStyleSpacesPanel; import com.intellij.application.options.codeStyle.WrappingAndBracesPanel; import com.intellij.lang.Language; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationBundle; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.highlighter.EditorHighlighter; import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectUtil; import com.intellij.openapi.ui.JBMenuItem; import com.intellij.openapi.ui.JBPopupMenu; import com.intellij.openapi.util.Disposer; import com.intellij.psi.codeStyle.*; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.TabbedPaneWrapper; import com.intellij.util.containers.hash.HashSet; import com.intellij.util.ui.GraphicsUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.*; import java.util.List; /** * @author Rustam Vishnyakov */ public abstract class TabbedLanguageCodeStylePanel extends CodeStyleAbstractPanel { private static final Logger LOG = Logger.getInstance(TabbedLanguageCodeStylePanel.class); private CodeStyleAbstractPanel myActiveTab; private List<CodeStyleAbstractPanel> myTabs; private JPanel myPanel; private TabbedPaneWrapper myTabbedPane; private final PredefinedCodeStyle[] myPredefinedCodeStyles; private JPopupMenu myCopyFromMenu; private @Nullable TabChangeListener myListener; protected TabbedLanguageCodeStylePanel(@Nullable Language language, CodeStyleSettings currentSettings, CodeStyleSettings settings) { super(language, currentSettings, settings); myPredefinedCodeStyles = getPredefinedStyles(); } /** * Initializes all standard tabs: "Tabs and Indents", "Spaces", "Blank Lines" and "Wrapping and Braces" if relevant. * For "Tabs and Indents" LanguageCodeStyleSettingsProvider must instantiate its own indent options, for other standard tabs it * must return false in usesSharedPreview() method. You can override this method to add your own tabs by calling super.initTabs() and * then addTab() methods or selectively add needed tabs with your own implementation. * @param settings Code style settings to be used with initialized panels. * @see LanguageCodeStyleSettingsProvider * @see #addIndentOptionsTab(CodeStyleSettings) * @see #addSpacesTab(CodeStyleSettings) * @see #addBlankLinesTab(CodeStyleSettings) * @see #addWrappingAndBracesTab(CodeStyleSettings) */ protected void initTabs(CodeStyleSettings settings) { LanguageCodeStyleSettingsProvider provider = LanguageCodeStyleSettingsProvider.forLanguage(getDefaultLanguage()); addIndentOptionsTab(settings); if (provider != null) { addSpacesTab(settings); addWrappingAndBracesTab(settings); addBlankLinesTab(settings); } } /** * Adds "Tabs and Indents" tab if the language has its own LanguageCodeStyleSettings provider and instantiates indent options in * getDefaultSettings() method. * @param settings CodeStyleSettings to be used with "Tabs and Indents" panel. */ protected void addIndentOptionsTab(CodeStyleSettings settings) { LanguageCodeStyleSettingsProvider provider = LanguageCodeStyleSettingsProvider.forLanguage(getDefaultLanguage()); if (provider != null) { IndentOptionsEditor indentOptionsEditor = provider.getIndentOptionsEditor(); if (indentOptionsEditor != null) { MyIndentOptionsWrapper indentOptionsWrapper = new MyIndentOptionsWrapper(settings, provider, indentOptionsEditor); addTab(indentOptionsWrapper); } } } protected void addSpacesTab(CodeStyleSettings settings) { addTab(new MySpacesPanel(settings)); } protected void addBlankLinesTab(CodeStyleSettings settings) { addTab(new MyBlankLinesPanel(settings)); } protected void addWrappingAndBracesTab(CodeStyleSettings settings) { addTab(new MyWrappingAndBracesPanel(settings)); } protected void ensureTabs() { if (myTabs == null) { myPanel = new JPanel(); myPanel.setLayout(new BorderLayout()); myTabbedPane = new TabbedPaneWrapper(this); myTabbedPane.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (myListener != null) { String title = myTabbedPane.getSelectedTitle(); if (title != null) { myListener.tabChanged(TabbedLanguageCodeStylePanel.this, title); } } } }); myTabs = new ArrayList<>(); myPanel.add(myTabbedPane.getComponent()); initTabs(getSettings()); } assert !myTabs.isEmpty(); } public void showSetFrom(Component component) { initCopyFromMenu(); myCopyFromMenu.show(component, 0, component.getHeight()); } private void initCopyFromMenu() { if (myCopyFromMenu == null) { myCopyFromMenu = new JBPopupMenu(); setupCopyFromMenu(myCopyFromMenu); } } /** * Adds a tab with the given CodeStyleAbstractPanel. Tab title is taken from getTabTitle() method. * @param tab The panel to use in a tab. */ protected final void addTab(CodeStyleAbstractPanel tab) { myTabs.add(tab); tab.setShouldUpdatePreview(true); addPanelToWatch(tab.getPanel()); myTabbedPane.addTab(tab.getTabTitle(), tab.getPanel()); if (myActiveTab == null) { myActiveTab = tab; } } private void addTab(Configurable configurable) { ConfigurableWrapper wrapper = new ConfigurableWrapper(configurable, getSettings()); addTab(wrapper); } /** * Creates and adds a tab from CodeStyleSettingsProvider. The provider may return false in hasSettingsPage() method in order not to be * shown at top level of code style settings. * @param provider The provider used to create a settings page. */ protected final void createTab(CodeStyleSettingsProvider provider) { if (provider.hasSettingsPage()) return; Configurable configurable = provider.createSettingsPage(getCurrentSettings(), getSettings()); addTab(configurable); } @Override public final void setModel(CodeStyleSchemesModel model) { super.setModel(model); ensureTabs(); for (CodeStyleAbstractPanel tab : myTabs) { tab.setModel(model); } } @Override protected int getRightMargin() { ensureTabs(); return myActiveTab.getRightMargin(); } @Override protected EditorHighlighter createHighlighter(EditorColorsScheme scheme) { ensureTabs(); return myActiveTab.createHighlighter(scheme); } @NotNull @Override protected FileType getFileType() { ensureTabs(); return myActiveTab.getFileType(); } @Override protected String getPreviewText() { ensureTabs(); return myActiveTab.getPreviewText(); } @Override protected void updatePreview(boolean useDefaultSample) { ensureTabs(); for (CodeStyleAbstractPanel tab : myTabs) { tab.updatePreview(useDefaultSample); } } @Override public void onSomethingChanged() { ensureTabs(); for (CodeStyleAbstractPanel tab : myTabs) { tab.setShouldUpdatePreview(true); tab.onSomethingChanged(); } } @Override protected void somethingChanged() { super.somethingChanged(); } @Override public void apply(CodeStyleSettings settings) throws ConfigurationException { ensureTabs(); for (CodeStyleAbstractPanel tab : myTabs) { tab.apply(settings); } } @Override public void dispose() { for (CodeStyleAbstractPanel tab : myTabs) { Disposer.dispose(tab); } super.dispose(); } @Override public boolean isModified(CodeStyleSettings settings) { ensureTabs(); for (CodeStyleAbstractPanel tab : myTabs) { if (tab.isModified(settings)) { return true; } } return false; } @Override public JComponent getPanel() { return myPanel; } @Override protected void resetImpl(CodeStyleSettings settings) { ensureTabs(); for (CodeStyleAbstractPanel tab : myTabs) { tab.resetImpl(settings); } } @Override public void setupCopyFromMenu(JPopupMenu copyMenu) { super.setupCopyFromMenu(copyMenu); if (myPredefinedCodeStyles.length > 0) { JMenu langs = new JMenu("Language") { @Override public void paint(Graphics g) { GraphicsUtil.setupAntialiasing(g); super.paint(g); } }; //TODO<rv>: Move to resource bundle copyMenu.add(langs); fillLanguages(langs); JMenu predefined = new JMenu("Predefined Style") { @Override public void paint(Graphics g) { GraphicsUtil.setupAntialiasing(g); super.paint(g); } }; //TODO<rv>: Move to resource bundle copyMenu.add(predefined); fillPredefined(predefined); } else { fillLanguages(copyMenu); } } private void fillLanguages(JComponent parentMenu) { Language[] languages = LanguageCodeStyleSettingsProvider.getLanguagesWithCodeStyleSettings(); @SuppressWarnings("UnnecessaryFullyQualifiedName") java.util.List<JMenuItem> langItems = new ArrayList<>(); for (final Language lang : languages) { if (!lang.equals(getDefaultLanguage())) { final String langName = LanguageCodeStyleSettingsProvider.getLanguageName(lang); JMenuItem langItem = new JBMenuItem(langName); langItem.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { applyLanguageSettings(lang); } }); langItems.add(langItem); } } Collections.sort(langItems, (item1, item2) -> item1.getText().compareToIgnoreCase(item2.getText())); for (JMenuItem langItem : langItems) { parentMenu.add(langItem); } } private void fillPredefined(JMenuItem parentMenu) { for (final PredefinedCodeStyle predefinedCodeStyle : myPredefinedCodeStyles) { JMenuItem predefinedItem = new JBMenuItem(predefinedCodeStyle.getName()); parentMenu.add(predefinedItem); predefinedItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { applyPredefinedStyle(predefinedCodeStyle.getName()); } }); } } private PredefinedCodeStyle[] getPredefinedStyles() { final Language language = getDefaultLanguage(); final List<PredefinedCodeStyle> result = new ArrayList<>(); for (PredefinedCodeStyle codeStyle : PredefinedCodeStyle.EP_NAME.getExtensions()) { if (codeStyle.getLanguage().equals(language)) { result.add(codeStyle); } } return result.toArray(new PredefinedCodeStyle[result.size()]); } private void applyLanguageSettings(Language lang) { final Project currProject = ProjectUtil.guessCurrentProject(getPanel()); CodeStyleSettings rootSettings = CodeStyleSettingsManager.getSettings(currProject); CodeStyleSettings targetSettings = getSettings(); if (rootSettings.getCommonSettings(lang) == null || targetSettings.getCommonSettings(getDefaultLanguage()) == null) return; applyLanguageSettings(lang, rootSettings, targetSettings); reset(targetSettings); onSomethingChanged(); } protected void applyLanguageSettings(Language lang, CodeStyleSettings rootSettings, CodeStyleSettings targetSettings) { CommonCodeStyleSettings sourceCommonSettings = rootSettings.getCommonSettings(lang); CommonCodeStyleSettings targetCommonSettings = targetSettings.getCommonSettings(getDefaultLanguage()); if (!(targetCommonSettings instanceof CodeStyleSettings)) { CommonCodeStyleSettingsManager.copy(sourceCommonSettings, targetCommonSettings); } else { Language targetLang = getDefaultLanguage(); LOG.error((targetLang != null ? targetLang.getDisplayName() : "Unknown") + " language plug-in either uses an outdated API or does not initialize" + " its own code style settings in LanguageCodeStyleSettingsProvider.getDefaultSettings()." + " The operation can not be applied in this case."); } } private void applyPredefinedStyle(String styleName) { for (PredefinedCodeStyle style : myPredefinedCodeStyles) { if (style.getName().equals(styleName)) { applyPredefinedSettings(style); } } } //======================================================================================================================================== protected class MySpacesPanel extends CodeStyleSpacesPanel { public MySpacesPanel(CodeStyleSettings settings) { super(settings); } @Override protected boolean shouldHideOptions() { return true; } @Override public Language getDefaultLanguage() { return TabbedLanguageCodeStylePanel.this.getDefaultLanguage(); } } protected class MyBlankLinesPanel extends CodeStyleBlankLinesPanel { public MyBlankLinesPanel(CodeStyleSettings settings) { super(settings); } @Override public Language getDefaultLanguage() { return TabbedLanguageCodeStylePanel.this.getDefaultLanguage(); } } protected class MyWrappingAndBracesPanel extends WrappingAndBracesPanel { public MyWrappingAndBracesPanel(CodeStyleSettings settings) { super(settings); } @Override public Language getDefaultLanguage() { return TabbedLanguageCodeStylePanel.this.getDefaultLanguage(); } } //======================================================================================================================================== private class ConfigurableWrapper extends CodeStyleAbstractPanel { private final Configurable myConfigurable; private JComponent myComponent; public ConfigurableWrapper(@NotNull Configurable configurable, CodeStyleSettings settings) { super(settings); myConfigurable = configurable; Disposer.register(this, new Disposable() { @Override public void dispose() { myConfigurable.disposeUIResources(); } }); } @Override protected int getRightMargin() { return 0; } @Nullable @Override protected EditorHighlighter createHighlighter(EditorColorsScheme scheme) { return null; } @SuppressWarnings("ConstantConditions") @NotNull @Override protected FileType getFileType() { Language language = getDefaultLanguage(); return language != null ? language.getAssociatedFileType() : FileTypes.PLAIN_TEXT; } @Override public Language getDefaultLanguage() { return TabbedLanguageCodeStylePanel.this.getDefaultLanguage(); } @Override protected String getTabTitle() { return myConfigurable.getDisplayName(); } @Override protected String getPreviewText() { return null; } @Override public void apply(CodeStyleSettings settings) throws ConfigurationException { if (myConfigurable instanceof CodeStyleConfigurable) { ((CodeStyleConfigurable)myConfigurable).apply(settings); } else { myConfigurable.apply(); } } @Override public boolean isModified(CodeStyleSettings settings) { return myConfigurable.isModified(); } @Nullable @Override public JComponent getPanel() { if (myComponent == null) { myComponent = myConfigurable.createComponent(); } return myComponent; } @Override protected void resetImpl(CodeStyleSettings settings) { if (myConfigurable instanceof CodeStyleConfigurable) { ((CodeStyleConfigurable)myConfigurable).reset(settings); } else { myConfigurable.reset(); } } } @Override public Set<String> processListOptions() { final Set<String> result = new HashSet<>(); for (CodeStyleAbstractPanel tab : myTabs) { result.addAll(tab.processListOptions()); } return result; } //======================================================================================================================================== protected class MyIndentOptionsWrapper extends CodeStyleAbstractPanel { private final IndentOptionsEditor myEditor; private final LanguageCodeStyleSettingsProvider myProvider; private final JPanel myTopPanel = new JPanel(new BorderLayout()); private final JPanel myLeftPanel = new JPanel(new BorderLayout()); private final JPanel myRightPanel; protected MyIndentOptionsWrapper(CodeStyleSettings settings, LanguageCodeStyleSettingsProvider provider, IndentOptionsEditor editor) { super(settings); myProvider = provider; myTopPanel.add(myLeftPanel, BorderLayout.WEST); myRightPanel = new JPanel(); installPreviewPanel(myRightPanel); myEditor = editor; if (myEditor != null) { JPanel panel = myEditor.createPanel(); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); JScrollPane scroll = ScrollPaneFactory.createScrollPane(panel, true); scroll.setPreferredSize(new Dimension(panel.getPreferredSize().width + scroll.getVerticalScrollBar().getPreferredSize().width + 5, -1)); myLeftPanel.add(scroll, BorderLayout.CENTER); } myTopPanel.add(myRightPanel, BorderLayout.CENTER); } @Override protected int getRightMargin() { return myProvider.getRightMargin(LanguageCodeStyleSettingsProvider.SettingsType.INDENT_SETTINGS); } @Override protected EditorHighlighter createHighlighter(EditorColorsScheme scheme) { //noinspection NullableProblems return EditorHighlighterFactory.getInstance().createEditorHighlighter(getFileType(), scheme, null); } @SuppressWarnings("ConstantConditions") @NotNull @Override protected FileType getFileType() { Language language = TabbedLanguageCodeStylePanel.this.getDefaultLanguage(); return language != null ? language.getAssociatedFileType() : FileTypes.PLAIN_TEXT; } @Override protected String getPreviewText() { return myProvider != null ? myProvider.getCodeSample(LanguageCodeStyleSettingsProvider.SettingsType.INDENT_SETTINGS) : "Loading..."; } @Override protected String getFileExt() { if (myProvider != null) { String ext = myProvider.getFileExt(); if (ext != null) return ext; } return super.getFileExt(); } @Override public void apply(CodeStyleSettings settings) { CommonCodeStyleSettings.IndentOptions indentOptions = getIndentOptions(settings); if (indentOptions == null) return; myEditor.apply(settings, indentOptions); } @Override public boolean isModified(CodeStyleSettings settings) { CommonCodeStyleSettings.IndentOptions indentOptions = getIndentOptions(settings); if (indentOptions == null) return false; return myEditor.isModified(settings, indentOptions); } @Override public JComponent getPanel() { return myTopPanel; } @Override protected void resetImpl(CodeStyleSettings settings) { CommonCodeStyleSettings.IndentOptions indentOptions = getIndentOptions(settings); if (indentOptions == null) { myEditor.setEnabled(false); indentOptions = settings.getIndentOptions(myProvider.getLanguage().getAssociatedFileType()); } myEditor.reset(settings, indentOptions); } @Nullable private CommonCodeStyleSettings.IndentOptions getIndentOptions(CodeStyleSettings settings) { return settings.getCommonSettings(getDefaultLanguage()).getIndentOptions(); } @Override public Language getDefaultLanguage() { return TabbedLanguageCodeStylePanel.this.getDefaultLanguage(); } @Override protected String getTabTitle() { return ApplicationBundle.message("title.tabs.and.indents"); } @Override public void onSomethingChanged() { super.onSomethingChanged(); myEditor.setEnabled(true); } } public interface TabChangeListener { void tabChanged(@NotNull TabbedLanguageCodeStylePanel source, @NotNull String tabTitle); } public void setListener(@Nullable TabChangeListener listener) { myListener = listener; } public void changeTab(@NotNull String tabTitle) { myTabbedPane.setSelectedTitle(tabTitle); } }
package com.emop.client.fragment; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.TypedArray; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.SyncStateContract.Columns; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.ListView; import android.widget.TextView; import com.emop.client.Constants; import com.emop.client.MutilFragmentActivity; import com.emop.client.R; import com.emop.client.fragment.adapter.CreditAdapter; import com.emop.client.io.FmeiClient; import com.emop.client.provider.JSONCursor; import com.emop.client.provider.Schema; import com.emop.client.provider.model.Shop; import com.emop.client.wxapi.DensityUtil; public class ShopListFragment extends ListFragment{ public int cateId = 0; private CursorAdapter adapter = null; protected Handler handler = new Handler(); private String dataSource = ""; private String dataFrom = ""; private boolean isRunning = false; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedState){ View v = inflater.inflate(R.layout.shop_list_view, container, false); if(cateId > 0){ v.setTag(cateId); } ListView listView = (ListView)v.findViewById(android.R.id.list); listView.setCacheColorHint(0); return v; } @Override public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) { super.onInflate(activity, attrs, savedInstanceState); TypedArray a = activity.obtainStyledAttributes(attrs, R.styleable.FragmentArguments); dataFrom = a.getString(R.styleable.FragmentArguments_data_source); a.recycle(); } public void reload(){ initParam(); Log.d("xx", "reload shop list...." + dataSource); getLoaderManager().restartLoader(0, null, callbacks); } public void onResume(){ super.onResume(); isRunning = true; } public void onPause(){ super.onPause(); isRunning = false; } private void initParam(){ final FmeiClient client = FmeiClient.getInstance(null); Bundle args = this.getArguments(); if(args != null){ dataSource = args.getString("uri"); } Log.d("xx", "shop list froms:" + dataFrom); if(dataFrom != null && dataFrom.equals("fav")){ String myFavId = client.getFavoriteId(); if(myFavId == null || myFavId.trim().length() == 0){ Log.d("xx", "not found myfav id...."); return; } dataSource = Schema.SHOP_LIST.toString(); } } public void onActivityCreated(Bundle savedState){ super.onActivityCreated(savedState); final FmeiClient client = FmeiClient.getInstance(null); initParam(); final int picWidth = DensityUtil.dip2px(getActivity(), 80); adapter = new CursorAdapter(getActivity(), JSONCursor.EMPTY, true){ private int titleIndex = -1, nickIndex, logoIndex, descIndex, shopTypeIndex, shopIdIndex, creditIndex; @Override public void bindView(View v, Context ctx, Cursor c) { if(titleIndex < 0){ initCursorIndex(c); } if(shopIdIndex >= 0){ v.setId(c.getInt(shopIdIndex)); } Items items = (Items)v.getTag(); if(items == null){ items = new Items(v); v.setTag(items); } if(items.shopTitle != null && titleIndex >= 0){ items.shopTitle.setText(c.getString(titleIndex)); } if(items.userNick != null && nickIndex >= 0){ items.userNick.setText(c.getString(nickIndex)); } if(items.shopDesc != null && descIndex >= 0){ items.shopDesc.setText(c.getString(descIndex)); } String shopType = ""; if(items.shopTypeLogo != null && shopTypeIndex >= 0){ shopType = c.getString(shopTypeIndex); if(shopType.equals("B")){ items.shopTypeLogo.setVisibility(View.VISIBLE); if(items.credit != null){ items.credit.setVisibility(View.GONE); } }else { items.shopTypeLogo.setVisibility(View.GONE); } } if(items.credit != null && creditIndex >= 0 && shopType.equals("C")){ int creditLevel = c.getInt(creditIndex); items.credit.setAdapter(new CreditAdapter(getActivity(), creditLevel)); items.credit.setVisibility(View.VISIBLE); items.credit.setVerticalScrollBarEnabled(false); items.credit.setHorizontalScrollBarEnabled(false); } if(items.shopLogo != null && logoIndex >= 0){ final String des = c.getString(logoIndex); items.shopLogo.setTag(des); Bitmap bm = client.tmpImgLoader.cache.get(des, picWidth, false, false); ImageView img = (ImageView)items.shopLogo; if(bm != null){ img.setScaleType(ScaleType.CENTER_CROP); img.setImageBitmap(bm); }else { img.setScaleType(ScaleType.CENTER_INSIDE); img.setImageResource(R.drawable.loading); client.tmpImgLoader.runTask(new Runnable(){ @Override public void run() { //Log.d("xxx", "load xxx2:" + des); final Bitmap newBm = client.tmpImgLoader.cache.get(des, 80, false, true); if(newBm != null){ handler.post(new Runnable(){ @Override public void run() { if(isRunning){ View v = getListView().findViewWithTag(des); if(v != null){ ImageView v2 = (ImageView)v; v2.setScaleType(ScaleType.CENTER_CROP); v2.setImageBitmap(newBm); } } } }); } } }); } } if(items.addToFav != null){ items.addToFav.setOnClickListener(addToFavorite); } } @Override public View newView(Context ctx, Cursor c, ViewGroup root) { Log.d("xx", "newView finishied, index:" + c.getPosition()); View v = getLayoutInflater(null).inflate(R.layout.shop_list_item, null); v.setTag(new Items(v)); return v; } private void initCursorIndex(Cursor c){ titleIndex = c.getColumnIndex(Shop.SHOP_TITLE); nickIndex = c.getColumnIndex(Shop.USER_NICK); logoIndex = c.getColumnIndex(Shop.SHOP_LOGO); descIndex = c.getColumnIndex(Shop.SHOP_DESC); shopTypeIndex = c.getColumnIndex(Shop.SHOP_TYPE); shopIdIndex = c.getColumnIndex(Shop.SHOP_ID); creditIndex = c.getColumnIndex(Shop.SHOP_CREDIT); } }; setListAdapter(adapter); if(dataSource != null && dataSource.length() > 0){ getLoaderManager().initLoader(0, null, callbacks); if(Uri.parse(dataSource) != null){ Log.d(Constants.TAG_EMOP, "registerContent:" + dataSource); getActivity().getContentResolver().registerContentObserver(Uri.parse(dataSource), false, new ContentObserver(new Handler()){ public void onChange(boolean selfChange) { if(isRunning){ Log.d(Constants.TAG_EMOP, "shop list is changed:" + dataSource); getLoaderManager().getLoader(0).forceLoad(); } } }); } } } protected LoaderCallbacks<Cursor> callbacks = new LoaderCallbacks<Cursor>() { @Override public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) { return new CursorLoader(getActivity(), Uri.parse(dataSource), new String[] {Columns._ID, Shop.SHOP_ID, Shop.SHOP_TITLE, Shop.USER_NICK, Shop.SHOP_TYPE, Shop.SHOP_DESC, Shop.SHOP_LOGO, Shop.SHOP_CREDIT }, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if(cursor != null){ Log.d("xx", "onLoad finishied, count:" + cursor.getCount()); if(cursor.getCount() == 0){ showNoItems(); } adapter.swapCursor(cursor); } } @Override public void onLoaderReset(Loader<Cursor> arg0) { adapter.swapCursor(null); } }; public void onListItemClick(ListView l, View v, int position, long id){ //Log.d("emop", "onListItemClick....."); Log.d("emop", "onItemClick, id:" + id); Intent intent = new Intent(); intent.setClass(getActivity(), MutilFragmentActivity.class); //intent.set intent.putExtra("view_id", new int[]{R.layout.shop_detail}); intent.putExtra("shop_id", id + ""); startActivity(intent); } private void showNoItems(){ View v = getView().findViewById(R.id.progressbar_loading); if(v != null){ v.setVisibility(View.GONE); } v = getView().findViewById(R.id.no_items); if(v != null){ v.setVisibility(View.VISIBLE); } } private OnClickListener addToFavorite = new OnClickListener(){ @Override public void onClick(View v) { Log.d("emop", "click view:" + v); } }; class Items{ TextView shopTitle = null; TextView userNick = null; ImageView shopLogo = null; TextView shopDesc = null; ImageView shopTypeLogo = null; Button addToFav = null; GridView credit = null; public Items(View root){ shopTitle = (TextView)root.findViewById(R.id.shop_title); userNick = (TextView)root.findViewById(R.id.user_nick); shopLogo = (ImageView)root.findViewById(R.id.shop_logo); shopDesc = (TextView)root.findViewById(R.id.shop_desc); shopTypeLogo = (ImageView)root.findViewById(R.id.shop_type_logo); addToFav = (Button)root.findViewById(R.id.add_to_favorite); credit = (GridView)root.findViewById(R.id.taobao_credit); } } }
package com.bandofyetis.robotframeworkdebugger; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Stack; import org.apache.log4j.Logger; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.MenuAdapter; import org.eclipse.swt.events.MenuEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowData; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import com.bandofyetis.robotframeworkdebugger.RobotFrameworkDebugContext.ContextType; public class RobotFrameworkDebuggerUIThread implements Runnable{ protected Shell shell; private Display display; private Object stepLock; private TabFolder tabFolder; private Label lblTestSuiteValue; private Label lblTestCaseValue; private Label lblKeywordValue; private Label lblArgumentsValue; private Table tblCallStackItem; private Table tblVariables; private StyledText textDocumentation; private RobotFrameworkDebugger controller; private Table tblBreakpoints; private Text textBreakpoint; private Table tblTestResults; private ToolItem tltmStepOver; private ToolItem tltmStepInto; private ToolItem tltmResume; private MenuItem mntmRemoveBreakpoint; private PreferencesDialog prefsDialog; private Image imgCurrentBreakpoint; /** * Logger */ static final Logger log = Logger.getLogger(RobotFrameworkDebuggerUIThread.class); /** * Open the window. * @wbp.parser.entryPoint */ public void run() { display = Display.getDefault(); createContents(); shell.open(); shell.layout(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } /** * Constructor * @param controller The Robot Framework Debugger instance that controls the window in the MVC model * @param stepLock The object that the debugger locks on when pausing execution of keywords */ public RobotFrameworkDebuggerUIThread(RobotFrameworkDebugger controller, Object stepLock){ this.controller = controller; this.stepLock = stepLock; } /** * Create contents of the window. */ protected void createContents() { shell = new Shell(SWT.SHELL_TRIM & (~SWT.RESIZE)); shell.setSize(530, 505); shell.setText("Robot Framework Debugger"); shell.setLayout(new GridLayout(1, false)); // On close window kill RobotFramework Test shell.addShellListener(new ShellAdapter() { public void shellClosed(ShellEvent e) { System.exit(0); } }); createToolbar(); createLabelPanel(); prefsDialog = new PreferencesDialog(shell, SWT.NONE); createTabFolder(); createCallStackTab(); createVariablesTab(); createDocumentationTab(); createBreakpointsTab(); createTestResultsTab(); } /** * Create the toolbar */ protected void createToolbar(){ ToolBar toolBar = new ToolBar(shell, SWT.FLAT | SWT.RIGHT); toolBar.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1)); tltmStepOver = new ToolItem(toolBar, SWT.NONE); tltmStepOver.setEnabled(false); InputStream in = getClass().getClassLoader().getResourceAsStream("arrow_turn_right.png"); if(in != null){ tltmStepOver.setImage(new Image(display, in)); } tltmStepOver.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { controller.setStepOver(); synchronized (stepLock) { stepLock.notify(); } } }); tltmStepOver.setText("Step Over"); tltmStepInto = new ToolItem(toolBar, SWT.NONE); tltmStepInto.setEnabled(false); in = getClass().getClassLoader().getResourceAsStream("arrow_down.png"); if(in != null){ tltmStepInto.setImage(new Image(display, in)); } tltmStepInto.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { controller.setStepInto(); synchronized (stepLock) { stepLock.notify(); } } }); tltmStepInto.setText("Step Into"); tltmResume = new ToolItem(toolBar, SWT.NONE); tltmResume.setEnabled(false); in = getClass().getClassLoader().getResourceAsStream("control_play_blue.png"); if(in != null){ tltmResume.setImage(new Image(display, in)); } tltmResume.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { controller.setRunToBreakpoint(); synchronized (stepLock) { stepLock.notify(); } } }); tltmResume.setText("Resume"); ToolItem tltmStop = new ToolItem(toolBar, SWT.NONE); in = getClass().getClassLoader().getResourceAsStream("control_stop_blue.png"); if(in != null){ tltmStop.setImage(new Image(display, in)); } tltmStop.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { // wake anything up that may be waiting synchronized (stepLock) { stepLock.notify(); } System.exit(0); } }); tltmStop.setText("Stop"); ToolItem tltmPreferences = new ToolItem(toolBar, SWT.NONE); tltmPreferences.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { prefsDialog.open(); } }); in = getClass().getClassLoader().getResourceAsStream("application_form_edit.png"); if(in != null){ tltmPreferences.setImage(new Image(display, in)); } tltmPreferences.setText("Preferences"); } /** * Create the label panel above the tabs that indicates which test, suite and keyword are running */ protected void createLabelPanel(){ Composite compositeTestSuiteRow = new Composite(shell, SWT.NONE); compositeTestSuiteRow.setLayout(new RowLayout(SWT.HORIZONTAL)); GridData gd_compositeTestSuiteRow = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_compositeTestSuiteRow.widthHint = 495; compositeTestSuiteRow.setLayoutData(gd_compositeTestSuiteRow); Label lblTestSuiteName = new Label(compositeTestSuiteRow, SWT.NONE); lblTestSuiteName.setLayoutData(new RowData(73, 15)); lblTestSuiteName.setText("Test Suite:"); lblTestSuiteValue = new Label(compositeTestSuiteRow, SWT.NONE); lblTestSuiteValue.setLayoutData(new RowData(350, SWT.DEFAULT)); Composite compositeTestCaseRow = new Composite(shell, SWT.NONE); compositeTestCaseRow.setLayout(new RowLayout(SWT.HORIZONTAL)); Label lblTestCase = new Label(compositeTestCaseRow, SWT.NONE); lblTestCase.setLayoutData(new RowData(73, 15)); lblTestCase.setText("Test Case:"); lblTestCaseValue = new Label(compositeTestCaseRow, SWT.NONE); lblTestCaseValue.setLayoutData(new RowData(367, SWT.DEFAULT)); Composite compositeKeywordRow = new Composite(shell, SWT.NONE); compositeKeywordRow.setLayout(new RowLayout(SWT.HORIZONTAL)); Label lblKeywordName = new Label(compositeKeywordRow, SWT.NONE); lblKeywordName.setLayoutData(new RowData(73, 15)); lblKeywordName.setText("Keyword:"); lblKeywordValue = new Label(compositeKeywordRow, SWT.NONE); lblKeywordValue.setLayoutData(new RowData(367, -1)); Composite compositeArgumentsRow = new Composite(shell, SWT.NONE); compositeArgumentsRow.setLayout(new RowLayout(SWT.HORIZONTAL)); Label lblArgumentsName = new Label(compositeArgumentsRow, SWT.NONE); lblArgumentsName.setLayoutData(new RowData(73, 15)); lblArgumentsName.setText("Arguments:"); lblArgumentsValue = new Label(compositeArgumentsRow, SWT.NONE); lblArgumentsValue.setLayoutData(new RowData(367, -1)); } /** * Create tab folder - the container that holds all of the tabs */ private void createTabFolder(){ tabFolder = new TabFolder(shell, SWT.NONE); GridData gd_tabFolder = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_tabFolder.widthHint = 495; gd_tabFolder.heightHint = 289; tabFolder.setLayoutData(gd_tabFolder); } /** * Create the callstack tab */ private void createCallStackTab(){ TabItem tbtmCallStack = new TabItem(tabFolder, SWT.NONE); tbtmCallStack.setText("Call Stack"); tblCallStackItem = new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION); tblCallStackItem.setHeaderVisible(true); tbtmCallStack.setControl(tblCallStackItem); tblCallStackItem.setLinesVisible(true); TableColumn tblclmnCallstackType = new TableColumn(tblCallStackItem, SWT.NONE); tblclmnCallstackType.setText("Type"); tblclmnCallstackType.setWidth(100); TableColumn tblclmnCallStack = new TableColumn(tblCallStackItem, SWT.NONE); tblclmnCallStack.setText("Name"); tblclmnCallStack.setWidth(300); TableColumn tblclmnLineNumber = new TableColumn(tblCallStackItem, SWT.LEFT); tblclmnLineNumber.setWidth(90); tblclmnLineNumber.setText("Line Number"); } /** * Create the variables tab */ private void createVariablesTab(){ TabItem tbtmVariables = new TabItem(tabFolder, SWT.NONE); tbtmVariables.setText("Variables"); tblVariables = new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION); tblVariables.setHeaderVisible(true); tbtmVariables.setControl(tblVariables); tblVariables.setLinesVisible(true); TableColumn tblclmnVariableName = new TableColumn(tblVariables, SWT.NONE); tblclmnVariableName.setWidth(100); tblclmnVariableName.setText("Variable Name"); TableColumn tblclmnValue = new TableColumn(tblVariables, SWT.NONE); tblclmnValue.setWidth(389); tblclmnValue.setText("Value"); } /** * Create the documentation tab */ private void createDocumentationTab(){ TabItem tbtmDocumentation = new TabItem(tabFolder, SWT.NONE); tbtmDocumentation.setText("Documentation"); textDocumentation = new StyledText(tabFolder, SWT.BORDER); textDocumentation.setDoubleClickEnabled(false); textDocumentation.setEditable(false); tbtmDocumentation.setControl(textDocumentation); } /** * Create the breakpoints tab */ private void createBreakpointsTab(){ InputStream in = getClass().getClassLoader().getResourceAsStream("arrow_right.png"); if(in != null){ imgCurrentBreakpoint = new Image(display, in); } else{ imgCurrentBreakpoint = null; } TabItem tbtmBreakpoints = new TabItem(tabFolder, SWT.NONE); tbtmBreakpoints.setText("Breakpoints"); Composite breakpointComposite = new Composite(tabFolder, SWT.NONE); tbtmBreakpoints.setControl(breakpointComposite); breakpointComposite.setLayout(new GridLayout(1, false)); tblBreakpoints = new Table(breakpointComposite, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); tblBreakpoints.setLinesVisible(true); tblBreakpoints.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); TableColumn tblclmnImage = new TableColumn(tblBreakpoints, SWT.CENTER); tblclmnImage.setResizable(false); tblclmnImage.setWidth(20); tblclmnImage.setText("image"); TableColumn tblclmnBreakpoints = new TableColumn(tblBreakpoints, SWT.NONE); tblclmnBreakpoints.setResizable(false); tblclmnBreakpoints.setWidth(461); tblclmnBreakpoints.setText("Breakpoint"); Menu menu = new Menu(shell, SWT.POP_UP); mntmRemoveBreakpoint = new MenuItem(menu, SWT.PUSH); mntmRemoveBreakpoint.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { int[] indices = tblBreakpoints.getSelectionIndices(); controller.removeBreakpoints(indices); // do an inline update until the next full table redraw tblBreakpoints.remove(tblBreakpoints.getSelectionIndices()); } }); in = getClass().getClassLoader().getResourceAsStream("delete.png"); if(in != null){ mntmRemoveBreakpoint.setImage(new Image(display, in)); } mntmRemoveBreakpoint.setText("Delete Breakpoints"); menu.addMenuListener(new MenuAdapter() { @Override public void menuShown(MenuEvent e) { int numSelected = tblBreakpoints.getSelectionCount(); if (numSelected == 0){ mntmRemoveBreakpoint.setText("Delete Breakpoint"); mntmRemoveBreakpoint.setEnabled(false); return; } else{ mntmRemoveBreakpoint.setEnabled(true); } // Handle grammar if (numSelected == 1){ mntmRemoveBreakpoint.setText("Delete Breakpoint"); } else{ mntmRemoveBreakpoint.setText("Delete Breakpoints"); } } }); tblBreakpoints.setMenu(menu); // Create new breakpoint dialog and button Composite breakpointEntryComposite = new Composite(breakpointComposite, SWT.NONE); breakpointEntryComposite.setLayout(new GridLayout(2, false)); GridData gd_breakpointEntryComposite = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_breakpointEntryComposite.widthHint = 482; breakpointEntryComposite.setLayoutData(gd_breakpointEntryComposite); textBreakpoint = new Text(breakpointEntryComposite, SWT.BORDER); textBreakpoint.setToolTipText("Enter part of the keyword name to break on"); GridData gd_textBreakpoint = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd_textBreakpoint.widthHint = 296; textBreakpoint.setLayoutData(gd_textBreakpoint); textBreakpoint.addListener(SWT.DefaultSelection, new Listener() { public void handleEvent(Event e) { String breakpointText = textBreakpoint.getText(); if (breakpointText != null && breakpointText.length() > 0){ controller.addBreakpoint(breakpointText); textBreakpoint.setText(""); } } }); Button btnAddBreakpoint = new Button(breakpointEntryComposite, SWT.NONE); btnAddBreakpoint.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String breakpointText = textBreakpoint.getText(); if (breakpointText != null && breakpointText.length() > 0){ controller.addBreakpoint(breakpointText); textBreakpoint.setText(""); } } }); btnAddBreakpoint.setText("Add Breakpoint"); } /** * Create the test results tab */ private void createTestResultsTab(){ TabItem tbtmTestresults = new TabItem(tabFolder, SWT.NONE); tbtmTestresults.setText("TestResults"); tblTestResults = new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION); tbtmTestresults.setControl(tblTestResults); tblTestResults.setHeaderVisible(true); tblTestResults.setLinesVisible(true); TableColumn tblclmTestName = new TableColumn(tblTestResults, SWT.NONE); tblclmTestName.setWidth(395); tblclmTestName.setText("Test Name"); TableColumn tblclmnResult = new TableColumn(tblTestResults, SWT.NONE); tblclmnResult.setWidth(100); tblclmnResult.setText("Result"); } /** * Clear all tabs and labels (Don't clear breakpoints or test results -- they persist) */ private void clearAll(){ lblTestSuiteValue.setText(""); lblTestCaseValue.setText(""); lblKeywordValue.setText(""); lblArgumentsValue.setText(""); textDocumentation.setText(""); tblVariables.removeAll(); tblCallStackItem.removeAll(); } /** * A hook to clear the data with the thread running in the context of the GUI */ public synchronized void clearTestData() { if (display == null || display.isDisposed()) return; display.asyncExec(new Runnable() { public void run() { clearAll(); } }); } /** * Update the GUI based on the model (ie the stack of debug contexts) * @param contextStack - A stack of debug contexts used to update the gui. Represents the state of the running test suite */ public synchronized void update(final Stack<RobotFrameworkDebugContext> contextStack) { if (display == null || display.isDisposed()) return; display.asyncExec(new Runnable() { public void run() { clearAll(); // A map for variables that handles scoping of variables Map<String, String> variables = new HashMap<String, String>(); // Traverse stack from bottom to top for (Iterator<RobotFrameworkDebugContext> it = contextStack.iterator(); it.hasNext(); ) { RobotFrameworkDebugContext context = it.next(); // set labels based on stack if (context.getContextType() == ContextType.TEST_SUITE){ lblTestSuiteValue.setText(context.getItemName()); } else if (context.getContextType() == ContextType.TEST_CASE){ lblTestCaseValue.setText(context.getItemName()); } // if it is the last keyword, take the data from it else if (!it.hasNext()){ // must be a keyword lblKeywordValue.setText(context.getItemName()); Map<String, Object> keywordAttrs = context.getItemAttribs(); String strArgs = ""; String strDocs = ""; if (keywordAttrs != null){ List args = (List)keywordAttrs.get("args"); for (int i=0; i < args.size(); i++) { strArgs += (i>0?", ":"")+args.get(i); } lblArgumentsValue.setText(strArgs); strDocs = (String)keywordAttrs.get("doc"); if (strDocs != null){ textDocumentation.setText(strDocs); } else{ textDocumentation.setText(""); } } } // Now add the context variables to our variables map - since we are traversing from // bottom to top, if 2 variables have the same name, the scope closest to the top of the stack is // displayed variables.putAll(context.getVariables()); } // Update callstack table - items are added to table in order listed! So we can't roll it into the loop // create table items for the callstack table int stackSize = contextStack.size(); final TableItem[] callstackItems = new TableItem[stackSize]; for (int pos = stackSize -1; pos >= 0; pos--){ RobotFrameworkDebugContext context = contextStack.elementAt(pos); // add to the call stack items int lineNumber = context.getLineNumber(); callstackItems[pos] = new TableItem(tblCallStackItem,SWT.NONE); callstackItems[pos].setText( new String[] { (String) context.getContextTypeString(), (String) context.getItemName(), (lineNumber > 0) ? Integer.toString(lineNumber):""}); } // Update test Variable table List<Set<Entry<String,Object>>> testVarList = CollectionHelpers.sortMapByKey(variables); final TableItem[] items = new TableItem[testVarList.size()]; int i=0; for (Iterator it = testVarList.iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next(); items[i] = new TableItem(tblVariables,SWT.NONE); items[i].setText( new String[] { (String) entry.getKey(), (String) entry.getValue()}); i++; } //Update the breakpoints table updateAllBreakpoints(controller.getBreakpoints()); } }); } /** * Set the state of the "stepping and running" buttons * @param bEnabled true if enabled, false if disabled */ public synchronized void setControlButtonsEnabled(final boolean bEnabled) { if (display == null || display.isDisposed()) return; display.asyncExec(new Runnable() { public void run() { tltmStepOver.setEnabled(bEnabled); tltmStepInto.setEnabled(bEnabled); tltmResume.setEnabled(bEnabled); } }); } /** * Set a new test result in the results tab * * @param testName name of the test * @param result a String "PASS" or "FAIL" */ public synchronized void setTestResult(final String testName, final String result) { if (display == null || display.isDisposed()) return; display.asyncExec(new Runnable() { public void run() { final Color red = display.getSystemColor(SWT.COLOR_RED); final Color green = display.getSystemColor(SWT.COLOR_DARK_GREEN); final TableItem testResult = new TableItem(tblTestResults, SWT.NONE); testResult.setText(new String[] {testName, result}); if (result.equalsIgnoreCase("PASS")){ testResult.setForeground(green); } else{ testResult.setForeground(red); } } }); } /** * Replace the data in the breakpoints tab with list of breakpoints passed in * @param breakpoints the breakpoints to update the tab with */ public void updateBreakpoints(final List<String> breakpoints) { if (display == null || display.isDisposed()) return; display.asyncExec(new Runnable() { public void run() { updateAllBreakpoints(breakpoints); } }); } /** * Private function to handle breakpoint update. Can be called from update or updateBreakpoints * @param breakpoints the breakpoints to update the tab with */ private void updateAllBreakpoints(List<String> breakpoints){ int currentBreakpointIndex = controller.getCurrentBreakpointIndex(); tblBreakpoints.removeAll(); final TableItem[] items = new TableItem[breakpoints.size()]; int i=0; for (Iterator<String> it = breakpoints.iterator(); it.hasNext(); ) { String breakpoint = it.next(); items[i] = new TableItem(tblBreakpoints,SWT.NONE); items[i].setText( new String[] { "", (String) breakpoint }); if (i == currentBreakpointIndex){ if(imgCurrentBreakpoint != null){ items[i].setImage(imgCurrentBreakpoint); } } i++; } } }
/* * Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* Type-specific source code for unit test * * Regenerate the BasicX classes via genBasic.sh whenever this file changes. * We check in the generated source files so that the test tree can be used * independently of the rest of the source tree. */ // -- This file was mechanically generated: Do not edit! -- // import java.nio.*; import java.lang.reflect.Method; public class BasicByte extends Basic { private static final byte[] VALUES = { Byte.MIN_VALUE, (byte) -1, (byte) 0, (byte) 1, Byte.MAX_VALUE, }; private static void relGet(ByteBuffer b) { int n = b.capacity(); byte v; for (int i = 0; i < n; i++) ck(b, (long)b.get(), (long)((byte)ic(i))); b.rewind(); } private static void relGet(ByteBuffer b, int start) { int n = b.remaining(); byte v; for (int i = start; i < n; i++) ck(b, (long)b.get(), (long)((byte)ic(i))); b.rewind(); } private static void absGet(ByteBuffer b) { int n = b.capacity(); byte v; for (int i = 0; i < n; i++) ck(b, (long)b.get(), (long)((byte)ic(i))); b.rewind(); } private static void bulkGet(ByteBuffer b) { int n = b.capacity(); byte[] a = new byte[n + 7]; b.get(a, 7, n); for (int i = 0; i < n; i++) ck(b, (long)a[i + 7], (long)((byte)ic(i))); } private static void relPut(ByteBuffer b) { int n = b.capacity(); b.clear(); for (int i = 0; i < n; i++) b.put((byte)ic(i)); b.flip(); } private static void absPut(ByteBuffer b) { int n = b.capacity(); b.clear(); for (int i = 0; i < n; i++) b.put(i, (byte)ic(i)); b.limit(n); b.position(0); } private static void bulkPutArray(ByteBuffer b) { int n = b.capacity(); b.clear(); byte[] a = new byte[n + 7]; for (int i = 0; i < n; i++) a[i + 7] = (byte)ic(i); b.put(a, 7, n); b.flip(); } private static void bulkPutBuffer(ByteBuffer b) { int n = b.capacity(); b.clear(); ByteBuffer c = ByteBuffer.allocate(n + 7); c.position(7); for (int i = 0; i < n; i++) c.put((byte)ic(i)); c.flip(); c.position(7); b.put(c); b.flip(); } //6231529 private static void callReset(ByteBuffer b) { b.position(0); b.mark(); b.duplicate().reset(); b.asReadOnlyBuffer().reset(); } private static void checkSlice(ByteBuffer b, ByteBuffer slice) { ck(slice, 0, slice.position()); ck(slice, b.remaining(), slice.limit()); ck(slice, b.remaining(), slice.capacity()); if (b.isDirect() != slice.isDirect()) fail("Lost direction", slice); if (b.isReadOnly() != slice.isReadOnly()) fail("Lost read-only", slice); } private static void checkBytes(ByteBuffer b, byte[] bs) { int n = bs.length; int p = b.position(); byte v; if (b.order() == ByteOrder.BIG_ENDIAN) { for (int i = 0; i < n; i++) ck(b, b.get(), bs[i]); } else { for (int i = n - 1; i >= 0; i--) ck(b, b.get(), bs[i]); } b.position(p); } private static void compact(Buffer b) { try { Class<?> cl = b.getClass(); Method m = cl.getDeclaredMethod("compact"); m.setAccessible(true); m.invoke(b); } catch (Exception e) { fail(e.getMessage(), b); } } private static void checkInvalidMarkException(final Buffer b) { tryCatch(b, InvalidMarkException.class, new Runnable() { public void run() { b.mark(); compact(b); b.reset(); }}); } private static void testViews(int level, ByteBuffer b, boolean direct) { ShortBuffer sb = b.asShortBuffer(); BasicShort.test(level, sb, direct); checkBytes(b, new byte[] { 0, (byte)ic(0) }); checkInvalidMarkException(sb); CharBuffer cb = b.asCharBuffer(); BasicChar.test(level, cb, direct); checkBytes(b, new byte[] { 0, (byte)ic(0) }); checkInvalidMarkException(cb); IntBuffer ib = b.asIntBuffer(); BasicInt.test(level, ib, direct); checkBytes(b, new byte[] { 0, 0, 0, (byte)ic(0) }); checkInvalidMarkException(ib); LongBuffer lb = b.asLongBuffer(); BasicLong.test(level, lb, direct); checkBytes(b, new byte[] { 0, 0, 0, 0, 0, 0, 0, (byte)ic(0) }); checkInvalidMarkException(lb); FloatBuffer fb = b.asFloatBuffer(); BasicFloat.test(level, fb, direct); checkBytes(b, new byte[] { 0x42, (byte)0xc2, 0, 0 }); checkInvalidMarkException(fb); DoubleBuffer db = b.asDoubleBuffer(); BasicDouble.test(level, db, direct); checkBytes(b, new byte[] { 0x40, 0x58, 0x40, 0, 0, 0, 0, 0 }); checkInvalidMarkException(db); } private static void testHet(int level, ByteBuffer b) { int p = b.position(); b.limit(b.capacity()); show(level, b); out.print(" put:"); b.putChar((char)1); b.putChar((char)Character.MAX_VALUE); out.print(" char"); b.putShort((short)1); b.putShort((short)Short.MAX_VALUE); out.print(" short"); b.putInt(1); b.putInt(Integer.MAX_VALUE); out.print(" int"); b.putLong((long)1); b.putLong((long)Long.MAX_VALUE); out.print(" long"); b.putFloat((float)1); b.putFloat((float)Float.MIN_VALUE); b.putFloat((float)Float.MAX_VALUE); out.print(" float"); b.putDouble((double)1); b.putDouble((double)Double.MIN_VALUE); b.putDouble((double)Double.MAX_VALUE); out.print(" double"); out.println(); b.limit(b.position()); b.position(p); show(level, b); out.print(" get:"); ck(b, b.getChar(), 1); ck(b, b.getChar(), Character.MAX_VALUE); out.print(" char"); ck(b, b.getShort(), 1); ck(b, b.getShort(), Short.MAX_VALUE); out.print(" short"); ck(b, b.getInt(), 1); ck(b, b.getInt(), Integer.MAX_VALUE); out.print(" int"); ck(b, b.getLong(), 1); ck(b, b.getLong(), Long.MAX_VALUE); out.print(" long"); ck(b, (long)b.getFloat(), 1); ck(b, (long)b.getFloat(), (long)Float.MIN_VALUE); ck(b, (long)b.getFloat(), (long)Float.MAX_VALUE); out.print(" float"); ck(b, (long)b.getDouble(), 1); ck(b, (long)b.getDouble(), (long)Double.MIN_VALUE); ck(b, (long)b.getDouble(), (long)Double.MAX_VALUE); out.print(" double"); out.println(); } private static void fail(String problem, ByteBuffer xb, ByteBuffer yb, byte x, byte y) { fail(problem + String.format(": x=%s y=%s", x, y), xb, yb); } private static void tryCatch(Buffer b, Class ex, Runnable thunk) { boolean caught = false; try { thunk.run(); } catch (Throwable x) { if (ex.isAssignableFrom(x.getClass())) { caught = true; } else { fail(x.getMessage() + " not expected"); } } if (!caught) fail(ex.getName() + " not thrown", b); } private static void tryCatch(byte [] t, Class ex, Runnable thunk) { tryCatch(ByteBuffer.wrap(t), ex, thunk); } public static void test(int level, final ByteBuffer b, boolean direct) { show(level, b); if (direct != b.isDirect()) fail("Wrong direction", b); // Gets and puts relPut(b); relGet(b); absGet(b); bulkGet(b); absPut(b); relGet(b); absGet(b); bulkGet(b); bulkPutArray(b); relGet(b); bulkPutBuffer(b); relGet(b); // Compact relPut(b); b.position(13); b.compact(); b.flip(); relGet(b, 13); // Exceptions relPut(b); b.limit(b.capacity() / 2); b.position(b.limit()); tryCatch(b, BufferUnderflowException.class, new Runnable() { public void run() { b.get(); }}); tryCatch(b, BufferOverflowException.class, new Runnable() { public void run() { b.put((byte)42); }}); // The index must be non-negative and lesss than the buffer's limit. tryCatch(b, IndexOutOfBoundsException.class, new Runnable() { public void run() { b.get(b.limit()); }}); tryCatch(b, IndexOutOfBoundsException.class, new Runnable() { public void run() { b.get(-1); }}); tryCatch(b, IndexOutOfBoundsException.class, new Runnable() { public void run() { b.put(b.limit(), (byte)42); }}); tryCatch(b, InvalidMarkException.class, new Runnable() { public void run() { b.position(0); b.mark(); b.compact(); b.reset(); }}); // Values b.clear(); b.put((byte)0); b.put((byte)-1); b.put((byte)1); b.put(Byte.MAX_VALUE); b.put(Byte.MIN_VALUE); byte v; b.flip(); ck(b, b.get(), 0); ck(b, b.get(), (byte)-1); ck(b, b.get(), 1); ck(b, b.get(), Byte.MAX_VALUE); ck(b, b.get(), Byte.MIN_VALUE); // Comparison b.rewind(); ByteBuffer b2 = ByteBuffer.allocate(b.capacity()); b2.put(b); b2.flip(); b.position(2); b2.position(2); if (!b.equals(b2)) { for (int i = 2; i < b.limit(); i++) { byte x = b.get(i); byte y = b2.get(i); if (x != y ) out.println("[" + i + "] " + x + " != " + y); } fail("Identical buffers not equal", b, b2); } if (b.compareTo(b2) != 0) fail("Comparison to identical buffer != 0", b, b2); b.limit(b.limit() + 1); b.position(b.limit() - 1); b.put((byte)99); b.rewind(); b2.rewind(); if (b.equals(b2)) fail("Non-identical buffers equal", b, b2); if (b.compareTo(b2) <= 0) fail("Comparison to shorter buffer <= 0", b, b2); b.limit(b.limit() - 1); b.put(2, (byte)42); if (b.equals(b2)) fail("Non-identical buffers equal", b, b2); if (b.compareTo(b2) <= 0) fail("Comparison to lesser buffer <= 0", b, b2); // Check equals and compareTo with interesting values for (byte x : VALUES) { ByteBuffer xb = ByteBuffer.wrap(new byte[] { x }); if (xb.compareTo(xb) != 0) { fail("compareTo not reflexive", xb, xb, x, x); } if (! xb.equals(xb)) { fail("equals not reflexive", xb, xb, x, x); } for (byte y : VALUES) { ByteBuffer yb = ByteBuffer.wrap(new byte[] { y }); if (xb.compareTo(yb) != - yb.compareTo(xb)) { fail("compareTo not anti-symmetric", xb, yb, x, y); } if ((xb.compareTo(yb) == 0) != xb.equals(yb)) { fail("compareTo inconsistent with equals", xb, yb, x, y); } if (xb.compareTo(yb) != Byte.compare(x, y)) { fail("Incorrect results for ByteBuffer.compareTo", xb, yb, x, y); } if (xb.equals(yb) != ((x == y) || ((x != x) && (y != y)))) { fail("Incorrect results for ByteBuffer.equals", xb, yb, x, y); } } } // Sub, dup relPut(b); relGet(b.duplicate()); b.position(13); relGet(b.duplicate(), 13); relGet(b.duplicate().slice(), 13); relGet(b.slice(), 13); relGet(b.slice().duplicate(), 13); // Slice b.position(5); ByteBuffer sb = b.slice(); checkSlice(b, sb); b.position(0); ByteBuffer sb2 = sb.slice(); checkSlice(sb, sb2); if (!sb.equals(sb2)) fail("Sliced slices do not match", sb, sb2); if ((sb.hasArray()) && (sb.arrayOffset() != sb2.arrayOffset())) fail("Array offsets do not match: " + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2); // Views b.clear(); b.order(ByteOrder.BIG_ENDIAN); testViews(level + 1, b, direct); for (int i = 1; i <= 9; i++) { b.position(i); show(level + 1, b); testViews(level + 2, b, direct); } b.position(0); b.order(ByteOrder.LITTLE_ENDIAN); testViews(level + 1, b, direct); // Heterogeneous accessors b.order(ByteOrder.BIG_ENDIAN); for (int i = 0; i <= 9; i++) { b.position(i); testHet(level + 1, b); } b.order(ByteOrder.LITTLE_ENDIAN); b.position(3); testHet(level + 1, b); // Read-only views b.rewind(); final ByteBuffer rb = b.asReadOnlyBuffer(); if (!b.equals(rb)) fail("Buffer not equal to read-only view", b, rb); show(level + 1, rb); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { relPut(rb); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { absPut(rb); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { bulkPutArray(rb); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { bulkPutBuffer(rb); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { rb.compact(); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { rb.putChar((char)1); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { rb.putChar(0, (char)1); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { rb.putShort((short)1); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { rb.putShort(0, (short)1); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { rb.putInt(1); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { rb.putInt(0, 1); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { rb.putLong((long)1); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { rb.putLong(0, (long)1); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { rb.putFloat((float)1); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { rb.putFloat(0, (float)1); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { rb.putDouble((double)1); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { rb.putDouble(0, (double)1); }}); if (rb.getClass().getName().startsWith("java.nio.Heap")) { tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { rb.array(); }}); tryCatch(b, ReadOnlyBufferException.class, new Runnable() { public void run() { rb.arrayOffset(); }}); if (rb.hasArray()) fail("Read-only heap buffer's backing array is accessible", rb); } // Bulk puts from read-only buffers b.clear(); rb.rewind(); b.put(rb); // For byte buffers, test both the direct and non-direct cases ByteBuffer ob = (b.isDirect() ? ByteBuffer.allocate(rb.capacity()) : ByteBuffer.allocateDirect(rb.capacity())); rb.rewind(); ob.put(rb); relPut(b); // Required by testViews } public static void test(final byte [] ba) { int offset = 47; int length = 900; final ByteBuffer b = ByteBuffer.wrap(ba, offset, length); show(0, b); ck(b, b.capacity(), ba.length); ck(b, b.position(), offset); ck(b, b.limit(), offset + length); // The offset must be non-negative and no larger than <array.length>. tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() { public void run() { ByteBuffer.wrap(ba, -1, ba.length); }}); tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() { public void run() { ByteBuffer.wrap(ba, ba.length + 1, ba.length); }}); tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() { public void run() { ByteBuffer.wrap(ba, 0, -1); }}); tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() { public void run() { ByteBuffer.wrap(ba, 0, ba.length + 1); }}); // A NullPointerException will be thrown if the array is null. tryCatch(ba, NullPointerException.class, new Runnable() { public void run() { ByteBuffer.wrap((byte []) null, 0, 5); }}); tryCatch(ba, NullPointerException.class, new Runnable() { public void run() { ByteBuffer.wrap((byte []) null); }}); } private static void testAllocate() { // An IllegalArgumentException will be thrown for negative capacities. tryCatch((Buffer) null, IllegalArgumentException.class, new Runnable() { public void run() { ByteBuffer.allocate(-1); }}); tryCatch((Buffer) null, IllegalArgumentException.class, new Runnable() { public void run() { ByteBuffer.allocateDirect(-1); }}); } public static void test() { testAllocate(); test(0, ByteBuffer.allocate(7 * 1024), false); test(0, ByteBuffer.wrap(new byte[7 * 1024], 0, 7 * 1024), false); test(new byte[1024]); ByteBuffer b = ByteBuffer.allocateDirect(7 * 1024); for (b.position(0); b.position() < b.limit(); ) ck(b, b.get(), 0); test(0, b, true); callReset(ByteBuffer.allocate(10)); } }
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.groovy.scripts; import groovy.lang.Closure; import org.gradle.api.Action; import org.gradle.api.PathValidation; import org.gradle.api.Script; import org.gradle.api.file.ConfigurableFileCollection; import org.gradle.api.file.ConfigurableFileTree; import org.gradle.api.file.CopySpec; import org.gradle.api.file.DeleteSpec; import org.gradle.api.file.FileTree; import org.gradle.api.initialization.dsl.ScriptHandler; import org.gradle.api.internal.ProcessOperations; import org.gradle.api.internal.file.DefaultFileOperations; import org.gradle.api.internal.file.FileLookup; import org.gradle.api.internal.file.FileOperations; import org.gradle.api.internal.file.FileResolver; import org.gradle.api.internal.file.HasFileOperations; import org.gradle.api.internal.file.collections.DirectoryFileTreeFactory; import org.gradle.api.internal.initialization.ClassLoaderScope; import org.gradle.api.internal.initialization.ScriptHandlerFactory; import org.gradle.api.internal.plugins.DefaultObjectConfigurationAction; import org.gradle.api.logging.Logger; import org.gradle.api.logging.Logging; import org.gradle.api.logging.LoggingManager; import org.gradle.api.provider.Provider; import org.gradle.api.provider.ProviderFactory; import org.gradle.api.resources.ResourceHandler; import org.gradle.api.tasks.WorkResult; import org.gradle.configuration.ScriptPluginFactory; import org.gradle.internal.Actions; import org.gradle.internal.hash.FileHasher; import org.gradle.internal.hash.StreamHasher; import org.gradle.internal.reflect.Instantiator; import org.gradle.internal.resource.TextResourceLoader; import org.gradle.internal.service.ServiceRegistry; import org.gradle.process.ExecResult; import org.gradle.process.ExecSpec; import org.gradle.process.JavaExecSpec; import org.gradle.process.internal.ExecFactory; import org.gradle.util.ConfigureUtil; import java.io.File; import java.net.URI; import java.util.Map; import java.util.concurrent.Callable; public abstract class DefaultScript extends BasicScript { private static final Logger LOGGER = Logging.getLogger(Script.class); private FileOperations fileOperations; private ProcessOperations processOperations; private ProviderFactory providerFactory; private LoggingManager loggingManager; public ServiceRegistry __scriptServices; @Override public void init(final Object target, ServiceRegistry services) { super.init(target, services); this.__scriptServices = services; loggingManager = services.get(LoggingManager.class); Instantiator instantiator = services.get(Instantiator.class); FileLookup fileLookup = services.get(FileLookup.class); ExecFactory execFactory = services.get(ExecFactory.class); DirectoryFileTreeFactory directoryFileTreeFactory = services.get(DirectoryFileTreeFactory.class); StreamHasher streamHasher = services.get(StreamHasher.class); FileHasher fileHasher = services.get(FileHasher.class); TextResourceLoader textResourceLoader = services.get(TextResourceLoader.class); if (target instanceof HasFileOperations) { fileOperations = ((HasFileOperations) target).getFileOperations(); } else { File sourceFile = getScriptSource().getResource().getLocation().getFile(); if (sourceFile != null) { fileOperations = new DefaultFileOperations(fileLookup.getFileResolver(sourceFile.getParentFile()), null, null, instantiator, fileLookup, directoryFileTreeFactory, streamHasher, fileHasher, execFactory, textResourceLoader); } else { fileOperations = new DefaultFileOperations(fileLookup.getFileResolver(), null, null, instantiator, fileLookup, directoryFileTreeFactory, streamHasher, fileHasher, execFactory, textResourceLoader); } } processOperations = (ProcessOperations) fileOperations; providerFactory = services.get(ProviderFactory.class); } public FileResolver getFileResolver() { return fileOperations.getFileResolver(); } @Override public FileOperations getFileOperations() { return fileOperations; } private DefaultObjectConfigurationAction createObjectConfigurationAction() { ClassLoaderScope classLoaderScope = __scriptServices.get(ClassLoaderScope.class); return new DefaultObjectConfigurationAction( getFileResolver(), __scriptServices.get(ScriptPluginFactory.class), __scriptServices.get(ScriptHandlerFactory.class), classLoaderScope, __scriptServices.get(TextResourceLoader.class), getScriptTarget() ); } @Override public void apply(Closure closure) { DefaultObjectConfigurationAction action = createObjectConfigurationAction(); ConfigureUtil.configure(closure, action); action.execute(); } @Override public void apply(Map options) { DefaultObjectConfigurationAction action = createObjectConfigurationAction(); ConfigureUtil.configureByMap(options, action); action.execute(); } @Override public ScriptHandler getBuildscript() { return __scriptServices.get(ScriptHandler.class); } @Override public void buildscript(Closure configureClosure) { ConfigureUtil.configure(configureClosure, getBuildscript()); } @Override public File file(Object path) { return fileOperations.file(path); } @Override public File file(Object path, PathValidation validation) { return fileOperations.file(path, validation); } @Override public URI uri(Object path) { return fileOperations.uri(path); } @Override public ConfigurableFileCollection files(Object... paths) { return fileOperations.configurableFiles(paths); } @Override public ConfigurableFileCollection files(Object paths, Closure configureClosure) { return ConfigureUtil.configure(configureClosure, fileOperations.configurableFiles(paths)); } @Override public String relativePath(Object path) { return fileOperations.relativePath(path); } @Override public ConfigurableFileTree fileTree(Object baseDir) { return fileOperations.fileTree(baseDir); } @Override public ConfigurableFileTree fileTree(Map<String, ?> args) { return fileOperations.fileTree(args); } @Override public ConfigurableFileTree fileTree(Object baseDir, Closure configureClosure) { return ConfigureUtil.configure(configureClosure, fileOperations.fileTree(baseDir)); } @Override public FileTree zipTree(Object zipPath) { return fileOperations.zipTree(zipPath); } @Override public FileTree tarTree(Object tarPath) { return fileOperations.tarTree(tarPath); } @Override public ResourceHandler getResources() { return fileOperations.getResources(); } @Override public WorkResult copy(Closure closure) { return copy(ConfigureUtil.configureUsing(closure)); } public WorkResult copy(Action<? super CopySpec> action) { return fileOperations.copy(action); } public WorkResult sync(Action<? super CopySpec> action) { return fileOperations.sync(action); } @Override public CopySpec copySpec(Closure closure) { return Actions.with(copySpec(), ConfigureUtil.configureUsing(closure)); } public CopySpec copySpec() { return fileOperations.copySpec(); } @Override public File mkdir(Object path) { return fileOperations.mkdir(path); } @Override public boolean delete(Object... paths) { return fileOperations.delete(paths); } public WorkResult delete(Action<? super DeleteSpec> action) { return fileOperations.delete(action); } @Override public ExecResult javaexec(Closure closure) { return processOperations.javaexec(ConfigureUtil.configureUsing(closure)); } @Override public ExecResult javaexec(Action<? super JavaExecSpec> action) { return processOperations.javaexec(action); } @Override public ExecResult exec(Closure closure) { return processOperations.exec(ConfigureUtil.configureUsing(closure)); } @Override public ExecResult exec(Action<? super ExecSpec> action) { return processOperations.exec(action); } @Override public <T> Provider<T> provider(Callable<T> value) { return providerFactory.provider(value); } @Override public LoggingManager getLogging() { return loggingManager; } @Override public Logger getLogger() { return LOGGER; } public String toString() { return "script"; } }
/* * ****************************************************************************** * Copyright (c) 2013-2014 Gabriele Mariotti. * * 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.cards.view; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.LayoutRes; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.ViewTreeObserver; import android.widget.LinearLayout; import java.util.HashMap; import com.android.cards.R; import com.android.cards.internal.Card; import com.android.cards.internal.CardExpand; import com.android.cards.internal.CardHeader; import com.android.cards.internal.CardThumbnail; import com.android.cards.internal.ViewToClickToExpand; import com.android.cards.view.base.CardViewWrapper; import com.android.cards.view.component.CardHeaderView; import com.android.cards.view.component.CardThumbnailView; import com.android.cards.view.helper.CardViewHelper; import com.android.cards.view.helper.CardViewHelperUtil; import com.android.cards.view.listener.SwipeDismissViewTouchListener; /** * Card view * </p> * Use an XML layout file to display it. * </p> * First, you need an XML layout that will display the Card. * <pre><code> * <com.android.cards.view.CardViewNative * android:id="@+id/carddemo_example_card3" * android:layout_width="match_parent" * android:layout_height="wrap_content" * android:layout_marginLeft="12dp" * android:layout_marginRight="12dp" * android:layout_marginTop="12dp"/> * </code></pre> * Then create a model: * <pre><code> * * //Create a Card * Card card = new Card(getContext()); * * //Create a CardHeader * CardHeader header = new CardHeader(getContext()); * * //Add Header to card * card.addCardHeader(header); * * </code></pre> * Last get a reference to the `CardViewNative` from your code, and set your `Card. * <pre><code> * //Set card in the cardView * CardViewNative cardView = (CardViewNative) getActivity().findViewById(R.id.carddemo); * * cardView.setCard(card); * </code></pre> * You can easily build your layout. * </p> * The quickest way to start with this would be to copy one of this files and create your layout. * Then you can inflate your layout in the `CardViewNative` using the attr: `card:card_layout_resourceID="@layout/my_layout` * Example: * <pre><code> * <com.android.cards.view.CardViewNative * android:id="@+id/carddemo_thumb_url" * android:layout_width="match_parent" * android:layout_height="wrap_content" * android:layout_marginLeft="12dp" * android:layout_marginRight="12dp" * card:card_layout_resourceID="@layout/card_thumbnail_layout" * android:layout_marginTop="12dp"/> * </code></pre> * </p> * @author Gabriele Mariotti (gabri.mariotti@gmail.com) */ public class CardViewNative extends android.support.v7.widget.CardView implements CardViewWrapper { protected static String TAG = "CardViewNative"; //-------------------------------------------------------------------------- // BaseCardView attribute //-------------------------------------------------------------------------- /** * Card Model */ protected Card mCard; /** * Default layout to apply to card */ protected @LayoutRes int card_layout_resourceID = R.layout.native_card_layout; /** * Global View for this Component */ protected View mInternalOuterView; /** * Header Compound View */ protected CardHeaderView mInternalHeaderLayout; /** * Thumbnail Compound View */ protected CardThumbnailView mInternalThumbnailLayout; /** * Used to recycle ui elements. */ protected boolean mIsRecycle=false; /** * Used to replace inner layout elements. */ protected boolean mForceReplaceInnerLayout =false; protected CardViewHelper mHelperImpl; //-------------------------------------------------------------------------- // CardView attribute //-------------------------------------------------------------------------- /** * {@link com.android.cards.internal.CardHeader} model */ protected CardHeader mCardHeader; /** * {@link com.android.cards.internal.CardThumbnail} model */ protected CardThumbnail mCardThumbnail; /** * {@link com.android.cards.internal.CardExpand} model */ protected CardExpand mCardExpand; //-------------------------------------------------------------------------- // Layout //-------------------------------------------------------------------------- /** * Main Layout */ protected View mInternalMainCardLayout; /** * Content Layout */ protected View mInternalContentLayout; /** * Inner View. */ protected View mInternalInnerView; /** * Hidden layout used by expand/collapse action */ protected View mInternalExpandLayout; /** * Expand Inner view */ protected View mInternalExpandInnerView; /** Animator to expand/collapse */ protected Animator mExpandAnimator; /** * Listener invoked when Expand Animator starts * It is used internally */ protected OnExpandListAnimatorListener mOnExpandListAnimatorListener; //-------------------------------------------------------------------------- // Constructor //-------------------------------------------------------------------------- public CardViewNative(Context context) { this(context, null, 0); } public CardViewNative(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CardViewNative(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); mHelperImpl = CardViewHelperUtil.getInstance(context); } //-------------------------------------------------------------------------- // Init //-------------------------------------------------------------------------- /** * Initialize * * @param attrs * @param defStyle */ protected void init(AttributeSet attrs, int defStyle) { //Init attrs initAttrs(attrs, defStyle); //Init view if (!isInEditMode()) initView(); } /** * Init custom attrs. * * @param attrs * @param defStyle */ protected void initAttrs(AttributeSet attrs, int defStyle) { card_layout_resourceID = R.layout.native_card_layout; TypedArray a = getContext().getTheme().obtainStyledAttributes( attrs, R.styleable.card_options, defStyle, defStyle); try { card_layout_resourceID = a.getResourceId(R.styleable.card_options_card_layout_resourceID, this.card_layout_resourceID); } finally { a.recycle(); } } /** * Init View */ protected void initView() { //Inflate outer view LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); mInternalOuterView = inflater.inflate(card_layout_resourceID, this, true); //Radius setRadius(getResources().getDimension(R.dimen.card_background_default_radius)); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void drawableHotspotChanged(float x, float y) { super.drawableHotspotChanged(x, y); if (mInternalMainCardLayout != null && mInternalMainCardLayout instanceof ForegroundLinearLayout) { mInternalMainCardLayout.drawableHotspotChanged(x,y); } } //-------------------------------------------------------------------------- // Card //-------------------------------------------------------------------------- /** * Add a {@link Card}. * It is very important to set all values and all components before launch this method. * * @param card {@link Card} model */ @Override public void setCard(Card card){ mCard = card; if (card!=null){ mCardHeader=card.getCardHeader(); mCardThumbnail=card.getCardThumbnail(); mCardExpand=card.getCardExpand(); } //Retrieve all IDs if (!isRecycle()){ retrieveLayoutIDs(); } //Build UI buildUI(); } /** * Refreshes the card content (it doesn't inflate layouts again) * * @param card */ public void refreshCard(Card card) { mIsRecycle=true; setCard(card); mIsRecycle=false; } /** * Refreshes the card content and replaces the inner layout elements (it inflates layouts again!) * * @param card */ public void replaceCard(Card card) { mForceReplaceInnerLayout=true; refreshCard(card); mForceReplaceInnerLayout=false; } //-------------------------------------------------------------------------- // Setup methods //-------------------------------------------------------------------------- protected void buildUI() { if (mCard == null) { Log.e(TAG, "No card model found. Please use setCard(card) to set all values."); return; } mCard.setCardView(this); //Shadow setupShadowView(); //Setup Header view setupHeaderView(); //Setup Main View setupMainView(); //setup Thumbnail setupThumbnailView(); //Setup Expand View setupExpandView(); //Setup Supplemental Actions setupSupplementalActions(); //Setup Listeners setupListeners(); //Setup Expand Action setupExpandAction(); //Setup Drawable Resources setupDrawableResources(); } /** * Retrieve all Layouts IDs */ protected void retrieveLayoutIDs(){ //Main Layout mInternalMainCardLayout = (View) findViewById(R.id.card_main_layout); //Get HeaderLayout mInternalHeaderLayout = (CardHeaderView) findViewById(R.id.card_header_layout); //Get ExpandHiddenView mInternalExpandLayout = (View) findViewById(R.id.card_content_expand_layout); //Get ContentLayout mInternalContentLayout = (View) findViewById(R.id.card_main_content_layout); //Get ThumbnailLayout mInternalThumbnailLayout = (CardThumbnailView) findViewById(R.id.card_thumbnail_layout); } /** * Sets up Shadow visibility * * @return */ protected void setupShadowView() { if (mCard != null && mCard.getCardElevation() != null) { this.setCardElevation(mCard.getCardElevation()); } } /** * Setup Header View */ protected void setupHeaderView(){ if (mCardHeader!=null){ if (mInternalHeaderLayout !=null){ mInternalHeaderLayout.setVisibility(VISIBLE); //Set recycle value (very important in a ListView) mInternalHeaderLayout.setRecycle(isRecycle()); mInternalHeaderLayout.setForceReplaceInnerLayout(isForceReplaceInnerLayout()); //Add Header View mInternalHeaderLayout.addCardHeader(mCardHeader); } }else{ //No header. Hide layouts if (mInternalHeaderLayout !=null){ mInternalHeaderLayout.setVisibility(GONE); //mInternalExpandLayout.setVisibility(View.GONE); if (isForceReplaceInnerLayout()){ mInternalHeaderLayout.addCardHeader(null); //mInternalHeaderLayout.removeAllViews(); } } } } /** * Setup the Main View */ protected void setupMainView(){ if (mInternalContentLayout !=null){ ViewGroup mParentGroup=null; try{ mParentGroup = (ViewGroup) mInternalContentLayout; }catch (Exception e){ setRecycle(false); } //Check if view can be recycled //It can happen in a listView, and improves performances if (!isRecycle() || isForceReplaceInnerLayout()){ if (isForceReplaceInnerLayout() && mInternalContentLayout!=null && mInternalInnerView!=null) ((ViewGroup)mInternalContentLayout).removeView(mInternalInnerView); mInternalInnerView=mCard.getInnerView(getContext(), (ViewGroup) mInternalContentLayout); }else{ //View can be recycled. //Only setup Inner Elements if (mCard.getInnerLayout()>-1) mCard.setupInnerViewElements(mParentGroup,mInternalInnerView); } } } /** * Setup the Thumbnail View */ protected void setupThumbnailView() { if (mInternalThumbnailLayout!=null){ if (mCardThumbnail!=null){ mInternalThumbnailLayout.setVisibility(VISIBLE); mInternalThumbnailLayout.setRecycle(isRecycle()); mInternalThumbnailLayout.setForceReplaceInnerLayout(isForceReplaceInnerLayout()); mInternalThumbnailLayout.addCardThumbnail(mCardThumbnail); }else{ mInternalThumbnailLayout.setVisibility(GONE); } } } /** * Setup Drawable Resources */ protected void setupDrawableResources() { //Card if (mCard!=null){ if (mCard.getBackgroundResourceId()!= Card.DEFAULT_COLOR){ changeBackgroundResourceId(mCard.getBackgroundResourceId()); }else if (mCard.getBackgroundResource()!=null){ changeBackgroundResource(mCard.getBackgroundResource()); } if (mCard.getBackgroundColorResourceId() != Card.DEFAULT_COLOR){ changeBackgroundColorResourceId(mCard.getBackgroundColorResourceId()); } } } protected void setupSupplementalActions() { if (mCard != null) mCard.setupSupplementalActions(); } //-------------------------------------------------------------------------- // Listeners //-------------------------------------------------------------------------- protected void setupExpandAction(){ //Config ExpandLayout and its animation if ( mInternalExpandLayout !=null && ( (mCardHeader!=null && mCardHeader.isButtonExpandVisible()) || mCard.getViewToClickToExpand()!=null) ){ //Create the expand/collapse animator mInternalExpandLayout.getViewTreeObserver().addOnPreDrawListener( new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { mInternalExpandLayout.getViewTreeObserver().removeOnPreDrawListener(this); View parent = (View) mInternalExpandLayout.getParent(); final int widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth() - parent.getPaddingLeft() - parent.getPaddingRight(), View.MeasureSpec.AT_MOST); final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); mInternalExpandLayout.measure(widthSpec, heightSpec); mExpandAnimator = ExpandCollapseHelper.createSlideAnimator((CardViewNative)mCard.getCardView(),0, mInternalExpandLayout.getMeasuredHeight()); return true; } }); } //Setup action and callback setupExpandCollapseActionListener(); } /** * Setup All listeners */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") protected void setupListeners(){ //Swipe listener if (mCard.isSwipeable()){ this.setOnTouchListener(new SwipeDismissViewTouchListener(this, mCard,new SwipeDismissViewTouchListener.DismissCallbacks() { @Override public boolean canDismiss(Card card) { return card.isSwipeable(); } @Override public void onDismiss(CardViewWrapper cardView, Card card) { final ViewGroup vg = (ViewGroup)(((View)cardView).getParent()); if (vg!=null){ vg.removeView((View)cardView); card.onSwipeCard(); } } })); }else{ this.setOnTouchListener(null); } //OnClick listeners and partial listener //Reset Partial Listeners resetPartialListeners(); if (mCard.isClickable()){ //Set the onClickListener if(!mCard.isMultiChoiceEnabled()){ if (mCard.getOnClickListener() != null) { this.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mCard.getOnClickListener()!=null) mCard.getOnClickListener().onClick(mCard,v); } }); //Prevent multiple events //if (!mCard.isSwipeable() && mCard.getOnSwipeListener() == null) { // this.setClickable(true); //} }else{ HashMap<Integer,Card.OnCardClickListener> mMultipleOnClickListner=mCard.getMultipleOnClickListener(); if (mMultipleOnClickListner!=null && !mMultipleOnClickListner.isEmpty()){ for (int key:mMultipleOnClickListner.keySet()){ View viewClickable= decodeAreaOnClickListener(key); final Card.OnCardClickListener mListener=mMultipleOnClickListner.get(key); if (viewClickable!=null){ //Add listener to this view viewClickable.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //Callback to card listener if (mListener!=null) mListener.onClick(mCard,v); } }); //Add Selector to this view if (key > Card.CLICK_LISTENER_ALL_VIEW) { mHelperImpl.setBackground(viewClickable, mHelperImpl.getResourceFromAttrs(getContext(),android.R.attr.selectableItemBackground)); } } } }else{ //There aren't listners this.setClickable(false); } } } }else{ this.setClickable(false); } //LongClick listener if(mCard.isLongClickable()){ this.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { if (mCard.getOnLongClickListener()!=null) return mCard.getOnLongClickListener().onLongClick(mCard,v); return false; } }); }else{ this.setLongClickable(false); } } /** * Reset all partial listeners */ protected void resetPartialListeners() { View viewClickable= decodeAreaOnClickListener(Card.CLICK_LISTENER_HEADER_VIEW); if (viewClickable!=null) viewClickable.setClickable(false); viewClickable= decodeAreaOnClickListener(Card.CLICK_LISTENER_THUMBNAIL_VIEW); if (viewClickable!=null) viewClickable.setClickable(false); viewClickable= decodeAreaOnClickListener(Card.CLICK_LISTENER_CONTENT_VIEW); if (viewClickable!=null) viewClickable.setClickable(false); viewClickable= decodeAreaOnClickListener(Card.CLICK_LISTENER_ACTIONAREA1_VIEW); if (viewClickable!=null) viewClickable.setClickable(false); } /** * * @param area * @return */ public View decodeAreaOnClickListener(int area) { if (area<Card.CLICK_LISTENER_ALL_VIEW && area>Card.CLICK_LISTENER_CONTENT_VIEW) return null; View view = null; switch (area){ case Card.CLICK_LISTENER_ALL_VIEW : view=this; break; case Card.CLICK_LISTENER_HEADER_VIEW : view=mInternalHeaderLayout; break; case Card.CLICK_LISTENER_THUMBNAIL_VIEW: view=mInternalThumbnailLayout; break; case Card.CLICK_LISTENER_CONTENT_VIEW: view=mInternalContentLayout; break; case Card.CLICK_LISTENER_ACTIONAREA1_VIEW: view=mInternalMainCardLayout; break; default: break; } return view; } //-------------------------------------------------------------------------- // Expandable Actions and Listeners //-------------------------------------------------------------------------- /** * Add ClickListener to expand and collapse hidden view */ protected void setupExpandCollapseActionListener() { if (mInternalExpandLayout != null) { mInternalExpandLayout.setVisibility(View.GONE); boolean internal_blockForLongClickOnImageButtonExpand = false; ViewToClickToExpand viewToClickToExpand = null; //ButtonExpandVisible has a priority to viewClickToExpand if (mCardHeader != null && mCardHeader.isButtonExpandVisible()) { viewToClickToExpand = ViewToClickToExpand.builder() .setupView(mInternalHeaderLayout.getImageButtonExpand()) .highlightView(true); internal_blockForLongClickOnImageButtonExpand = true; } else if (mCard.getViewToClickToExpand() != null) { viewToClickToExpand = mCard.getViewToClickToExpand(); } if (viewToClickToExpand != null) { TitleViewOnClickListener titleViewOnClickListener = new TitleViewOnClickListener(mInternalExpandLayout, mCard, viewToClickToExpand.isViewToSelect()); /*if (mCardHeader!=null && mCardHeader.isButtonExpandVisible() && mInternalHeaderLayout != null) { mInternalHeaderLayout.setOnClickExpandCollapseActionListener(titleViewOnClickListener); }*/ View viewToClick = viewToClickToExpand.getViewToClick(); if (viewToClick != null) { if (internal_blockForLongClickOnImageButtonExpand) { //The long click on Header button is now allowed viewToClick.setOnClickListener(titleViewOnClickListener); }else{ if (viewToClickToExpand.isUseLongClick()){ viewToClick.setOnLongClickListener(new TitleViewOnLongClickListener(titleViewOnClickListener)); }else{ viewToClick.setOnClickListener(titleViewOnClickListener); } } }else{ ViewToClickToExpand.CardElementUI cardElementUI=viewToClickToExpand.getCardElementUIToClick(); if (cardElementUI!=null){ switch (cardElementUI){ case CARD: viewToClick = this; break; case HEADER: viewToClick = getInternalHeaderLayout(); break; case THUMBNAIL: viewToClick = getInternalThumbnailLayout(); break; case MAIN_CONTENT: viewToClick = getInternalContentLayout(); break; } if (viewToClick != null) { if (viewToClickToExpand.isUseLongClick()){ viewToClick.setOnLongClickListener(new TitleViewOnLongClickListener(titleViewOnClickListener)); }else{ viewToClick.setOnClickListener(titleViewOnClickListener); } } } } if (isExpanded()) { //Make layout visible and button selected mInternalExpandLayout.setVisibility(View.VISIBLE); if (viewToClick != null) { if (viewToClickToExpand.isViewToSelect()) viewToClick.setSelected(true); } } else { //Make layout hidden and button not selected mInternalExpandLayout.setVisibility(View.GONE); if (viewToClick != null) { if (viewToClickToExpand.isViewToSelect()) viewToClick.setSelected(false); } } } } } /** * Listener to expand/collapse hidden Expand Layout * It starts animation */ protected class TitleViewOnLongClickListener implements OnLongClickListener { TitleViewOnClickListener mOnClickListener; private TitleViewOnLongClickListener(TitleViewOnClickListener onClickListener) { mOnClickListener = onClickListener; } @Override public boolean onLongClick(View view) { if (mOnClickListener != null){ mOnClickListener.onClick(view); return true; } return false; } } private class ExpandContainerHelper{ private View contentParent; private Card card; private boolean viewToSelect=true; private ExpandContainerHelper(View contentParent, Card card, boolean viewToSelect) { this.contentParent = contentParent; this.card = card; this.viewToSelect = viewToSelect; } public CardViewNative getCardView() { return (CardViewNative) card.getCardView(); } } private static class ExpandCollapseHelper { /** * Expanding animator. */ private static void animateExpanding(final ExpandContainerHelper helper) { if (helper.getCardView().getOnExpandListAnimatorListener()!=null){ //List Animator helper.getCardView().getOnExpandListAnimatorListener().onExpandStart(helper.getCardView(), helper.contentParent); }else{ //Std animator helper.contentParent.setVisibility(View.VISIBLE); if (helper.getCardView().mExpandAnimator != null) { helper.getCardView().mExpandAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { helper.card.setExpanded(true); //Callback if (helper.card.getOnExpandAnimatorEndListener() != null) helper.card.getOnExpandAnimatorEndListener().onExpandEnd(helper.card); } }); helper.getCardView().mExpandAnimator.start(); }else{ if (helper.card.getOnExpandAnimatorEndListener() != null) helper.card.getOnExpandAnimatorEndListener().onExpandEnd(helper.card); Log.w(TAG,"Does the card have the ViewToClickToExpand?"); } } } /** * Collapse animator */ private static void animateCollapsing(final ExpandContainerHelper helper) { if (helper.getCardView().getOnExpandListAnimatorListener()!=null){ //There is a List Animator. helper.getCardView().getOnExpandListAnimatorListener().onCollapseStart(helper.getCardView(), helper.contentParent); }else{ //Std animator int origHeight = helper.contentParent.getHeight(); ValueAnimator animator = createSlideAnimator(helper.getCardView(),origHeight, 0); animator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { helper.contentParent.setVisibility(View.GONE); helper.card.setExpanded(false); //Callback if (helper.card.getOnCollapseAnimatorEndListener()!=null) helper.card.getOnCollapseAnimatorEndListener().onCollapseEnd(helper.card); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); animator.start(); } } /** * Create the Slide Animator invoked when the expand/collapse button is clicked */ protected static ValueAnimator createSlideAnimator(final CardViewNative cardView,int start, int end) { ValueAnimator animator = ValueAnimator.ofInt(start, end); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { int value = (Integer) valueAnimator.getAnimatedValue(); ViewGroup.LayoutParams layoutParams = cardView.mInternalExpandLayout.getLayoutParams(); layoutParams.height = value; cardView.mInternalExpandLayout.setLayoutParams(layoutParams); } }); return animator; } } /** * Setup Expand View */ protected void setupExpandView(){ if (mInternalExpandLayout!=null && mCardExpand!=null){ //Check if view can be recycled //It can happen in a listView, and improves performances if (!isRecycle() || isForceReplaceInnerLayout()){ if (isForceReplaceInnerLayout() && mInternalExpandLayout!=null && mInternalExpandInnerView!=null) ((ViewGroup)mInternalExpandLayout).removeView(mInternalExpandInnerView); mInternalExpandInnerView=mCardExpand.getInnerView(getContext(),(ViewGroup) mInternalExpandLayout); }else{ //View can be recycled. //Only setup Inner Elements if (mCardExpand.getInnerLayout()>-1) mCardExpand.setupInnerViewElements((ViewGroup)mInternalExpandLayout,mInternalExpandInnerView); } ViewGroup.LayoutParams layoutParams = mInternalExpandLayout.getLayoutParams(); layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; mInternalExpandLayout.setLayoutParams(layoutParams); } } public void doToggleExpand() { if (mInternalExpandLayout != null) { ExpandContainerHelper helper = new ExpandContainerHelper(mInternalExpandLayout, mCard, false); boolean isVisible = mInternalExpandLayout.getVisibility() == View.VISIBLE; if (isVisible) { ExpandCollapseHelper.animateCollapsing(helper); } else { ExpandCollapseHelper.animateExpanding(helper); } } } public void doExpand() { if (mInternalExpandLayout != null) { ExpandContainerHelper helper = new ExpandContainerHelper(mInternalExpandLayout, mCard, false); boolean isVisible = mInternalExpandLayout.getVisibility() == View.VISIBLE; if (!isVisible) { ExpandCollapseHelper.animateExpanding(helper); } } } public void doCollapse() { if (mInternalExpandLayout != null) { ExpandContainerHelper helper = new ExpandContainerHelper(mInternalExpandLayout, mCard, false); boolean isVisible = mInternalExpandLayout.getVisibility() == View.VISIBLE; if (isVisible) { ExpandCollapseHelper.animateCollapsing(helper); } } } /** * Listener to expand/collapse hidden Expand Layout * It starts animation */ protected class TitleViewOnClickListener implements View.OnClickListener { ExpandContainerHelper mExpandContainerHelper; private TitleViewOnClickListener(View contentParent,Card card) { this (contentParent, card,true); } private TitleViewOnClickListener(View contentParent,Card card,boolean viewToSelect) { mExpandContainerHelper = new ExpandContainerHelper(contentParent, card, viewToSelect); } @Override public void onClick(View view) { boolean isVisible = mExpandContainerHelper.contentParent.getVisibility() == View.VISIBLE; if (isVisible) { ExpandCollapseHelper.animateCollapsing(mExpandContainerHelper); if (mExpandContainerHelper.viewToSelect) view.setSelected(false); } else { ExpandCollapseHelper.animateExpanding(mExpandContainerHelper); if (mExpandContainerHelper.viewToSelect) view.setSelected(true); } } } @Override protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld) { super.onSizeChanged(xNew, yNew, xOld, yOld); } // ------------------------------------------------------------- // OnExpandListAnimator Interface and Listener // ------------------------------------------------------------- /** * Returns the listener invoked when expand/collpase animation starts * It is used internally * * @return listener */ public OnExpandListAnimatorListener getOnExpandListAnimatorListener() { return mOnExpandListAnimatorListener; } /** * Sets the listener invoked when expand/collapse animation starts * It is used internally. Don't override it. * * @param onExpandListAnimatorListener listener */ @Override public void setOnExpandListAnimatorListener(CardViewWrapper.OnExpandListAnimatorListener onExpandListAnimatorListener) { this.mOnExpandListAnimatorListener = onExpandListAnimatorListener; } // ------------------------------------------------------------- // ChangeBackground // ------------------------------------------------------------- /** * Changes dynamically the drawable resource to override the style of MainLayout. * * @param drawableResourceId drawable resource Id */ @Override public void changeBackgroundResourceId(int drawableResourceId) { if (drawableResourceId!=Card.DEFAULT_COLOR){ changeBackgroundResource(getResources().getDrawable(drawableResourceId)); } } /** * Changes dynamically the drawable resource to override the style of MainLayout. * * @param drawableResource drawable resource */ @Override public void changeBackgroundResource(Drawable drawableResource) { if (drawableResource!=null){ if (mInternalMainCardLayout!=null){ mHelperImpl.setBackground(mInternalMainCardLayout, drawableResource); } } } /** * Changes dynamically the color of the background card * * @param colorResourceId color resource Id */ @Override public void changeBackgroundColorResourceId(int colorResourceId) { if (colorResourceId!=Card.DEFAULT_COLOR){ //this.setBackgroundDrawable(mHelperImpl.getResourceFromAttrs(getContext(),R.attr.cardBackgroundColor)); mInternalMainCardLayout.setBackgroundColor(getResources().getColor(colorResourceId)); } } // ------------------------------------------------------------- // Bitmap export // ------------------------------------------------------------- /** * Create a {@link android.graphics.Bitmap} from CardView * @return */ public Bitmap createBitmap(){ if (getWidth()<=0 && getHeight()<=0){ int spec = MeasureSpec.makeMeasureSpec( 0,MeasureSpec.UNSPECIFIED); measure(spec,spec); layout(0, 0, getMeasuredWidth(), getMeasuredHeight()); } Bitmap b = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); draw(c); return b; } //-------------------------------------------------------------------------- // Getters and Setters //-------------------------------------------------------------------------- public View getInternalOuterView() { return mInternalOuterView; } /** * Returns {@link Card} model * * @return {@link Card} model */ public Card getCard() { return mCard; } /** * Returns the view used for Header * * @return {@link CardHeaderView} */ public CardHeaderView getInternalHeaderLayout() { return mInternalHeaderLayout; } /** * Returns the view used by Thumbnail * * @return {@link CardThumbnailView} */ @Override public CardThumbnailView getInternalThumbnailLayout() { return mInternalThumbnailLayout; } /** * Indicates if view can recycle ui elements. * * @return <code>true</code> if views can recycle ui elements */ public boolean isRecycle() { return mIsRecycle; } /** * Sets if view can recycle ui elements * * @param isRecycle <code>true</code> to recycle */ @Override public void setRecycle(boolean isRecycle) { this.mIsRecycle = isRecycle; } /** * Indicates if inner layout have to be replaced * * @return <code>true</code> if inner layout can be recycled */ public boolean isForceReplaceInnerLayout() { return mForceReplaceInnerLayout; } /** * Sets if inner layout have to be replaced * * @param forceReplaceInnerLayout <code>true</code> to recycle */ @Override public void setForceReplaceInnerLayout(boolean forceReplaceInnerLayout) { this.mForceReplaceInnerLayout = forceReplaceInnerLayout; } /** * Returns the view used by Expand Layout * * @return {@link View} used by Expand Layout */ public View getInternalExpandLayout() { return mInternalExpandLayout; } /** * FIXME * @return */ public View getInternalContentLayout() { return mInternalContentLayout; } /** * FIXME * @return */ public View getInternalInnerView() { return mInternalInnerView; } /** * Indicates if the card is expanded or collapsed * * @return <code>true</code> if the card is expanded */ public boolean isExpanded() { if (mCard!=null){ return mCard.isExpanded(); }else return false; } /** * Sets the card as expanded or collapsed * * @param expanded <code>true</code> if the card is expanded */ public void setExpanded(boolean expanded) { if (mCard!=null){ mCard.setExpanded(expanded); } } @Override public boolean isNative() { return true; } /** * Retrieves the InternalMainCardGlobalLayout. * * @return */ public View getInternalMainCardLayout() { return mInternalMainCardLayout; } public ViewParent getCardParent() { return getParent(); } public View getCardView() { View v = this; return v; } }
package org.eclipse.packagedrone.dockerregistry.api.impl; import org.eclipse.dockerregistry.storage.StorageDriver; import org.eclipse.dockerregistry.storage.drivers.FileSystemStorageDriver; import org.eclipse.dockerregistry.utils.Digest; import org.eclipse.dockerregistry.utils.DockerMediaTypes; import org.eclipse.dockerregistry.utils.ErrorCodes; import org.eclipse.dockerregistry.utils.ErrorEntityBuilder; import org.eclipse.packagedrone.dockerregistry.api.*; import org.eclipse.packagedrone.dockerregistry.models.Error; import org.eclipse.packagedrone.dockerregistry.models.Tags; import java.io.*; import java.security.NoSuchAlgorithmException; import java.util.List; import org.eclipse.packagedrone.dockerregistry.api.NotFoundException; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; public class NameApiServiceImpl extends NameApiService { private static final Logger logger = LoggerFactory.getLogger(NameApiServiceImpl.class); @Override public Response nameBlobsDigestGet(String name, String digest, SecurityContext securityContext) throws NotFoundException { if (!isValidNamespace(name)) { Error error = ErrorEntityBuilder.buildError(ErrorCodes.NAME_INVALID, "invalid repository name", ""); return Response.status(Response.Status.BAD_REQUEST).entity(error).build(); } StorageDriver driver = FileSystemStorageDriver.getInstance(); if (!driver.repositoryExists(name)) { Error error = ErrorEntityBuilder.buildError(ErrorCodes.NAME_UNKNOWN, "Repository name not known to registry", ""); return Response.status(Response.Status.NOT_FOUND).entity(error).build(); } try { InputStream input = driver.getInputStreamForBlob(name, digest); return Response.ok(input, MediaType.APPLICATION_OCTET_STREAM) .header("Docker-Content-Digest", digest).build(); } catch (IOException e) { e.printStackTrace(); Error error = ErrorEntityBuilder.buildError(ErrorCodes.BLOB_UNKNOWN, "blob unknown to registry", ""); return Response.status(Response.Status.NOT_FOUND).entity(error).build(); } } @Override public Response nameBlobsDigestHead(String name, String digest, SecurityContext securityContext) throws NotFoundException { return null; } /* if (!isValidNamespace(name)) return Response.status(Response.Status.BAD_REQUEST).build(); StorageDriver driver = FileSystemStorageDriver.getInstance(); if (!driver.repositoryExists(name)) return Response.status(Response.Status.NOT_FOUND).build(); try { InputStream input = driver.getInputStreamForBlob(name, digest); long contentLength = 0; while (input.read() != -1) contentLength++; Logger log = LoggerFactory.getLogger(this.getClass()); log.info("Content Length: " + contentLength); return Response.ok(MediaType.APPLICATION_OCTET_STREAM) .header("Docker-Content-Digest", digest) .header("Content-Length", contentLength).build(); } catch (IOException e) { e.printStackTrace(); return Response.status(Response.Status.NOT_FOUND).build(); } }*/ @Override public Response nameBlobsUploadsPost(String name, String digest, InputStream inputStream, SecurityContext securityContext) throws NotFoundException { StorageDriver driver = FileSystemStorageDriver.getInstance(); if (digest != null) { try { OutputStream out = driver.getOutputStreamForBlobPostUpload(name, digest); writeToStream(inputStream, out); } catch (IOException e) { e.printStackTrace(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } } return Response.ok().header("Upload", "success").build(); } @Override public Response nameBlobsUploadsUuidDelete(String name, String uuid, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override public Response nameBlobsUploadsUuidGet(String name, String uuid, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override public Response nameBlobsUploadsUuidPatch(String name, String uuid, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override public Response nameBlobsUploadsUuidPut(String name, String uuid, String digest, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override public Response nameManifestsReferenceDelete(String name, String reference, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override public Response nameManifestsReferenceGet(String name, String reference, SecurityContext securityContext) throws NotFoundException { if (!isValidNamespace(name)) { Error error = ErrorEntityBuilder.buildError(ErrorCodes.NAME_INVALID, "invalid repository name", ""); logger.error(ErrorCodes.NAME_INVALID); return Response.status(Response.Status.BAD_REQUEST).entity(error).build(); } StorageDriver driver = FileSystemStorageDriver.getInstance(); if (!driver.repositoryExists(name)) { Error error = ErrorEntityBuilder.buildError(ErrorCodes.NAME_UNKNOWN, "Repository name not known to registry", ""); logger.error(ErrorCodes.NAME_UNKNOWN); return Response.status(Response.Status.NOT_FOUND).entity(error).build(); } try { InputStream input = driver.getInputStreamForManifest(name, reference); String manifest = readStream(input); manifest = cleanupString(manifest); String digest = "sha256:" + Digest.getDigest(manifest, "SHA-256"); logger.info("Manifest found for reference: " + reference); logger.info("Digest for the manifest: " + "sha256:" + digest); return Response.ok(manifest, DockerMediaTypes.SCHEMA2) .header("Docker-Content-Digest", digest).build(); } catch (IOException e) { e.printStackTrace(); Error error = ErrorEntityBuilder.buildError(ErrorCodes.BLOB_UNKNOWN, "blob unknown to registry", ""); logger.error(ErrorCodes.BLOB_UNKNOWN); return Response.status(Response.Status.NOT_FOUND).entity(error).build(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return Response.status(Response.Status.NOT_FOUND).build(); } } @Override public Response nameManifestsReferencePut(String name, String reference, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override public Response nameTagsListGet(String name, SecurityContext securityContext) throws NotFoundException { StorageDriver driver = FileSystemStorageDriver.getInstance(); // TODO: Set this to be taken from a config file List<String> tags = driver.getTags(name); Tags entity = new Tags() .name(name) .tags(tags); return Response.ok().entity(entity).build(); } private boolean isValidNamespace(String path) { Pattern pattern = Pattern.compile("^([A-Za-z0-9._s-]+)+$"); return pattern.matcher(path).matches(); } private String readStream(InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte buffer[] = new byte[1024]; int bytesRead; while ((bytesRead = input.read(buffer)) != -1) output.write(buffer, 0, bytesRead); return output.toString(); } private void writeToStream(InputStream inputStream, OutputStream outputStream) throws IOException { int bytesRead = 0; byte[] bytes = new byte[1024]; while ((bytesRead = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, bytesRead); } outputStream.flush(); outputStream.close(); } private String cleanupString(String str) { String cleaned = str.trim(); for (int i = cleaned.length() - 1; cleaned.charAt(i) == '\n'; i--) { cleaned = cleaned.substring(0, cleaned.length() - 1); } return cleaned; } }
/** * 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.camel.component.crypto.springboot; import java.security.KeyStore; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.cert.Certificate; import javax.annotation.Generated; import org.apache.camel.CamelContext; import org.apache.camel.component.crypto.CryptoOperation; import org.apache.camel.spring.boot.ComponentConfigurationPropertiesCommon; import org.apache.camel.util.jsse.KeyStoreParameters; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; /** * The crypto component is used for signing and verifying exchanges using the * Signature Service of the Java Cryptographic Extension (JCE). * * Generated by camel-package-maven-plugin - do not edit this file! */ @Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo") @ConfigurationProperties(prefix = "camel.component.crypto") public class DigitalSignatureComponentConfiguration extends ComponentConfigurationPropertiesCommon { /** * To use the shared DigitalSignatureConfiguration as configuration */ private DigitalSignatureConfigurationNestedConfiguration configuration; /** * Whether the component should resolve property placeholders on itself when * starting. Only properties which are of String type can use property * placeholders. */ private Boolean resolvePropertyPlaceholders = true; public DigitalSignatureConfigurationNestedConfiguration getConfiguration() { return configuration; } public void setConfiguration( DigitalSignatureConfigurationNestedConfiguration configuration) { this.configuration = configuration; } public Boolean getResolvePropertyPlaceholders() { return resolvePropertyPlaceholders; } public void setResolvePropertyPlaceholders( Boolean resolvePropertyPlaceholders) { this.resolvePropertyPlaceholders = resolvePropertyPlaceholders; } public static class DigitalSignatureConfigurationNestedConfiguration { public static final Class CAMEL_NESTED_CLASS = org.apache.camel.component.crypto.DigitalSignatureConfiguration.class; private CamelContext camelContext; /** * The logical name of this operation. */ private String name; /** * Sets the JCE name of the Algorithm that should be used for the * signer. */ private String algorithm = "SHA1WithDSA"; /** * Sets the alias used to query the KeyStore for keys and * {@link java.security.cert.Certificate Certificates} to be used in * signing and verifying exchanges. This value can be provided at * runtime via the message header * {@link org.apache.camel.component.crypto.DigitalSignatureConstants#KEYSTORE_ALIAS} */ private String alias; /** * Set the PrivateKey that should be used to sign the exchange * * @param privateKey * the key with with to sign the exchange. */ private PrivateKey privateKey; /** * Sets the reference name for a PrivateKey that can be fond in the * registry. */ private String privateKeyName; /** * Set the PublicKey that should be used to verify the signature in the * exchange. */ private PublicKey publicKey; /** * Sets the reference name for a publicKey that can be fond in the * registry. */ private String publicKeyName; /** * Set the Certificate that should be used to verify the signature in * the exchange based on its payload. */ private Certificate certificate; /** * Sets the reference name for a PrivateKey that can be fond in the * registry. */ private String certificateName; /** * Sets the KeyStore that can contain keys and Certficates for use in * signing and verifying exchanges. A {@link KeyStore} is typically used * with an alias, either one supplied in the Route definition or * dynamically via the message header "CamelSignatureKeyStoreAlias". If * no alias is supplied and there is only a single entry in the * Keystore, then this single entry will be used. */ private KeyStore keystore; /** * Sets the reference name for a Keystore that can be fond in the * registry. */ private String keystoreName; /** * Sets the password used to access an aliased {@link PrivateKey} in the * KeyStore. */ private char[] password; /** * Sets the KeyStore that can contain keys and Certficates for use in * signing and verifying exchanges based on the given * KeyStoreParameters. A {@link KeyStore} is typically used with an * alias, either one supplied in the Route definition or dynamically via * the message header "CamelSignatureKeyStoreAlias". If no alias is * supplied and there is only a single entry in the Keystore, then this * single entry will be used. */ @NestedConfigurationProperty private KeyStoreParameters keyStoreParameters; /** * Set the SecureRandom used to initialize the Signature service * * @param secureRandom * the random used to init the Signature service */ private SecureRandom secureRandom; /** * Sets the reference name for a SecureRandom that can be fond in the * registry. */ private String secureRandomName; /** * Set the size of the buffer used to read in the Exchange payload data. */ private Integer bufferSize = 2048; /** * Set the id of the security provider that provides the configured * {@link Signature} algorithm. * * @param provider * the id of the security provider */ private String provider; /** * Set the name of the message header that should be used to store the * base64 encoded signature. This defaults to 'CamelDigitalSignature' */ private String signatureHeaderName; /** * Determines if the Signature specific headers be cleared after signing * and verification. Defaults to true, and should only be made otherwise * at your extreme peril as vital private information such as Keys and * passwords may escape if unset. */ private Boolean clearHeaders = true; private CryptoOperation cryptoOperation; public CamelContext getCamelContext() { return camelContext; } public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAlgorithm() { return algorithm; } public void setAlgorithm(String algorithm) { this.algorithm = algorithm; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public PrivateKey getPrivateKey() { return privateKey; } public void setPrivateKey(PrivateKey privateKey) { this.privateKey = privateKey; } public String getPrivateKeyName() { return privateKeyName; } public void setPrivateKeyName(String privateKeyName) { this.privateKeyName = privateKeyName; } public PublicKey getPublicKey() { return publicKey; } public void setPublicKey(PublicKey publicKey) { this.publicKey = publicKey; } public String getPublicKeyName() { return publicKeyName; } public void setPublicKeyName(String publicKeyName) { this.publicKeyName = publicKeyName; } public Certificate getCertificate() { return certificate; } public void setCertificate(Certificate certificate) { this.certificate = certificate; } public String getCertificateName() { return certificateName; } public void setCertificateName(String certificateName) { this.certificateName = certificateName; } public KeyStore getKeystore() { return keystore; } public void setKeystore(KeyStore keystore) { this.keystore = keystore; } public String getKeystoreName() { return keystoreName; } public void setKeystoreName(String keystoreName) { this.keystoreName = keystoreName; } public char[] getPassword() { return password; } public void setPassword(char[] password) { this.password = password; } public KeyStoreParameters getKeyStoreParameters() { return keyStoreParameters; } public void setKeyStoreParameters(KeyStoreParameters keyStoreParameters) { this.keyStoreParameters = keyStoreParameters; } public SecureRandom getSecureRandom() { return secureRandom; } public void setSecureRandom(SecureRandom secureRandom) { this.secureRandom = secureRandom; } public String getSecureRandomName() { return secureRandomName; } public void setSecureRandomName(String secureRandomName) { this.secureRandomName = secureRandomName; } public Integer getBufferSize() { return bufferSize; } public void setBufferSize(Integer bufferSize) { this.bufferSize = bufferSize; } public String getProvider() { return provider; } public void setProvider(String provider) { this.provider = provider; } public String getSignatureHeaderName() { return signatureHeaderName; } public void setSignatureHeaderName(String signatureHeaderName) { this.signatureHeaderName = signatureHeaderName; } public Boolean getClearHeaders() { return clearHeaders; } public void setClearHeaders(Boolean clearHeaders) { this.clearHeaders = clearHeaders; } public CryptoOperation getCryptoOperation() { return cryptoOperation; } public void setCryptoOperation(CryptoOperation cryptoOperation) { this.cryptoOperation = cryptoOperation; } } }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ package fixtures.http.implementation; import retrofit2.Retrofit; import fixtures.http.HttpServerFailures; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; import com.microsoft.rest.ServiceResponseBuilder; import fixtures.http.models.Error; import fixtures.http.models.ErrorException; import java.io.IOException; import okhttp3.ResponseBody; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.HEAD; import retrofit2.http.Headers; import retrofit2.http.HTTP; import retrofit2.http.POST; import retrofit2.Response; import rx.functions.Func1; import rx.Observable; /** * An instance of this class provides access to all the operations defined * in HttpServerFailures. */ public final class HttpServerFailuresImpl implements HttpServerFailures { /** The Retrofit service to perform REST calls. */ private HttpServerFailuresService service; /** The service client containing this operation class. */ private AutoRestHttpInfrastructureTestServiceImpl client; /** * Initializes an instance of HttpServerFailures. * * @param retrofit the Retrofit instance built from a Retrofit Builder. * @param client the instance of the service client containing this operation class. */ public HttpServerFailuresImpl(Retrofit retrofit, AutoRestHttpInfrastructureTestServiceImpl client) { this.service = retrofit.create(HttpServerFailuresService.class); this.client = client; } /** * The interface defining all the services for HttpServerFailures to be * used by Retrofit to perform actually REST calls. */ interface HttpServerFailuresService { @Headers("Content-Type: application/json; charset=utf-8") @HEAD("http/failure/server/501") Observable<Response<Void>> head501(); @Headers("Content-Type: application/json; charset=utf-8") @GET("http/failure/server/501") Observable<Response<ResponseBody>> get501(); @Headers("Content-Type: application/json; charset=utf-8") @POST("http/failure/server/505") Observable<Response<ResponseBody>> post505(@Body Boolean booleanValue); @Headers("Content-Type: application/json; charset=utf-8") @HTTP(path = "http/failure/server/505", method = "DELETE", hasBody = true) Observable<Response<ResponseBody>> delete505(@Body Boolean booleanValue); } /** * Return 501 status code - should be represented in the client as an error. * * @return the Error object if successful. */ public Error head501() { return head501WithServiceResponseAsync().toBlocking().single().getBody(); } /** * Return 501 status code - should be represented in the client as an error. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ public ServiceCall<Error> head501Async(final ServiceCallback<Error> serviceCallback) { return ServiceCall.create(head501WithServiceResponseAsync(), serviceCallback); } /** * Return 501 status code - should be represented in the client as an error. * * @return the observable to the Error object */ public Observable<Error> head501Async() { return head501WithServiceResponseAsync().map(new Func1<ServiceResponse<Error>, Error>() { @Override public Error call(ServiceResponse<Error> response) { return response.getBody(); } }); } /** * Return 501 status code - should be represented in the client as an error. * * @return the observable to the Error object */ public Observable<ServiceResponse<Error>> head501WithServiceResponseAsync() { return service.head501() .flatMap(new Func1<Response<Void>, Observable<ServiceResponse<Error>>>() { @Override public Observable<ServiceResponse<Error>> call(Response<Void> response) { try { ServiceResponse<Error> clientResponse = head501Delegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Error> head501Delegate(Response<Void> response) throws ErrorException, IOException { return new ServiceResponseBuilder<Error, ErrorException>(this.client.mapperAdapter()) .registerError(ErrorException.class) .buildEmpty(response); } /** * Return 501 status code - should be represented in the client as an error. * * @return the Error object if successful. */ public Error get501() { return get501WithServiceResponseAsync().toBlocking().single().getBody(); } /** * Return 501 status code - should be represented in the client as an error. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ public ServiceCall<Error> get501Async(final ServiceCallback<Error> serviceCallback) { return ServiceCall.create(get501WithServiceResponseAsync(), serviceCallback); } /** * Return 501 status code - should be represented in the client as an error. * * @return the observable to the Error object */ public Observable<Error> get501Async() { return get501WithServiceResponseAsync().map(new Func1<ServiceResponse<Error>, Error>() { @Override public Error call(ServiceResponse<Error> response) { return response.getBody(); } }); } /** * Return 501 status code - should be represented in the client as an error. * * @return the observable to the Error object */ public Observable<ServiceResponse<Error>> get501WithServiceResponseAsync() { return service.get501() .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Error>>>() { @Override public Observable<ServiceResponse<Error>> call(Response<ResponseBody> response) { try { ServiceResponse<Error> clientResponse = get501Delegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Error> get501Delegate(Response<ResponseBody> response) throws ErrorException, IOException { return new ServiceResponseBuilder<Error, ErrorException>(this.client.mapperAdapter()) .registerError(ErrorException.class) .build(response); } /** * Return 505 status code - should be represented in the client as an error. * * @return the Error object if successful. */ public Error post505() { return post505WithServiceResponseAsync().toBlocking().single().getBody(); } /** * Return 505 status code - should be represented in the client as an error. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ public ServiceCall<Error> post505Async(final ServiceCallback<Error> serviceCallback) { return ServiceCall.create(post505WithServiceResponseAsync(), serviceCallback); } /** * Return 505 status code - should be represented in the client as an error. * * @return the observable to the Error object */ public Observable<Error> post505Async() { return post505WithServiceResponseAsync().map(new Func1<ServiceResponse<Error>, Error>() { @Override public Error call(ServiceResponse<Error> response) { return response.getBody(); } }); } /** * Return 505 status code - should be represented in the client as an error. * * @return the observable to the Error object */ public Observable<ServiceResponse<Error>> post505WithServiceResponseAsync() { final Boolean booleanValue = null; return service.post505(booleanValue) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Error>>>() { @Override public Observable<ServiceResponse<Error>> call(Response<ResponseBody> response) { try { ServiceResponse<Error> clientResponse = post505Delegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } /** * Return 505 status code - should be represented in the client as an error. * * @param booleanValue Simple boolean value true * @return the Error object if successful. */ public Error post505(Boolean booleanValue) { return post505WithServiceResponseAsync(booleanValue).toBlocking().single().getBody(); } /** * Return 505 status code - should be represented in the client as an error. * * @param booleanValue Simple boolean value true * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ public ServiceCall<Error> post505Async(Boolean booleanValue, final ServiceCallback<Error> serviceCallback) { return ServiceCall.create(post505WithServiceResponseAsync(booleanValue), serviceCallback); } /** * Return 505 status code - should be represented in the client as an error. * * @param booleanValue Simple boolean value true * @return the observable to the Error object */ public Observable<Error> post505Async(Boolean booleanValue) { return post505WithServiceResponseAsync(booleanValue).map(new Func1<ServiceResponse<Error>, Error>() { @Override public Error call(ServiceResponse<Error> response) { return response.getBody(); } }); } /** * Return 505 status code - should be represented in the client as an error. * * @param booleanValue Simple boolean value true * @return the observable to the Error object */ public Observable<ServiceResponse<Error>> post505WithServiceResponseAsync(Boolean booleanValue) { return service.post505(booleanValue) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Error>>>() { @Override public Observable<ServiceResponse<Error>> call(Response<ResponseBody> response) { try { ServiceResponse<Error> clientResponse = post505Delegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Error> post505Delegate(Response<ResponseBody> response) throws ErrorException, IOException { return new ServiceResponseBuilder<Error, ErrorException>(this.client.mapperAdapter()) .registerError(ErrorException.class) .build(response); } /** * Return 505 status code - should be represented in the client as an error. * * @return the Error object if successful. */ public Error delete505() { return delete505WithServiceResponseAsync().toBlocking().single().getBody(); } /** * Return 505 status code - should be represented in the client as an error. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ public ServiceCall<Error> delete505Async(final ServiceCallback<Error> serviceCallback) { return ServiceCall.create(delete505WithServiceResponseAsync(), serviceCallback); } /** * Return 505 status code - should be represented in the client as an error. * * @return the observable to the Error object */ public Observable<Error> delete505Async() { return delete505WithServiceResponseAsync().map(new Func1<ServiceResponse<Error>, Error>() { @Override public Error call(ServiceResponse<Error> response) { return response.getBody(); } }); } /** * Return 505 status code - should be represented in the client as an error. * * @return the observable to the Error object */ public Observable<ServiceResponse<Error>> delete505WithServiceResponseAsync() { final Boolean booleanValue = null; return service.delete505(booleanValue) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Error>>>() { @Override public Observable<ServiceResponse<Error>> call(Response<ResponseBody> response) { try { ServiceResponse<Error> clientResponse = delete505Delegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } /** * Return 505 status code - should be represented in the client as an error. * * @param booleanValue Simple boolean value true * @return the Error object if successful. */ public Error delete505(Boolean booleanValue) { return delete505WithServiceResponseAsync(booleanValue).toBlocking().single().getBody(); } /** * Return 505 status code - should be represented in the client as an error. * * @param booleanValue Simple boolean value true * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link ServiceCall} object */ public ServiceCall<Error> delete505Async(Boolean booleanValue, final ServiceCallback<Error> serviceCallback) { return ServiceCall.create(delete505WithServiceResponseAsync(booleanValue), serviceCallback); } /** * Return 505 status code - should be represented in the client as an error. * * @param booleanValue Simple boolean value true * @return the observable to the Error object */ public Observable<Error> delete505Async(Boolean booleanValue) { return delete505WithServiceResponseAsync(booleanValue).map(new Func1<ServiceResponse<Error>, Error>() { @Override public Error call(ServiceResponse<Error> response) { return response.getBody(); } }); } /** * Return 505 status code - should be represented in the client as an error. * * @param booleanValue Simple boolean value true * @return the observable to the Error object */ public Observable<ServiceResponse<Error>> delete505WithServiceResponseAsync(Boolean booleanValue) { return service.delete505(booleanValue) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Error>>>() { @Override public Observable<ServiceResponse<Error>> call(Response<ResponseBody> response) { try { ServiceResponse<Error> clientResponse = delete505Delegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Error> delete505Delegate(Response<ResponseBody> response) throws ErrorException, IOException { return new ServiceResponseBuilder<Error, ErrorException>(this.client.mapperAdapter()) .registerError(ErrorException.class) .build(response); } }
/** * 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.camel.processor.idempotent.jpa; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.PersistenceException; import javax.persistence.Query; import org.apache.camel.Exchange; import org.apache.camel.api.management.ManagedAttribute; import org.apache.camel.api.management.ManagedOperation; import org.apache.camel.api.management.ManagedResource; import org.apache.camel.spi.IdempotentRepository; import org.apache.camel.support.ServiceSupport; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import static org.apache.camel.component.jpa.JpaHelper.getTargetEntityManager; @ManagedResource(description = "JPA based message id repository") public class JpaMessageIdRepository extends ServiceSupport implements IdempotentRepository { protected static final String QUERY_STRING = "select x from " + MessageProcessed.class.getName() + " x where x.processorName = ?1 and x.messageId = ?2"; protected static final String QUERY_CLEAR_STRING = "select x from " + MessageProcessed.class.getName() + " x where x.processorName = ?1"; private final String processorName; private final EntityManagerFactory entityManagerFactory; private final TransactionTemplate transactionTemplate; private boolean joinTransaction = true; private boolean sharedEntityManager; public JpaMessageIdRepository(EntityManagerFactory entityManagerFactory, String processorName) { this(entityManagerFactory, createTransactionTemplate(entityManagerFactory), processorName); } public JpaMessageIdRepository(EntityManagerFactory entityManagerFactory, TransactionTemplate transactionTemplate, String processorName) { this.entityManagerFactory = entityManagerFactory; this.processorName = processorName; this.transactionTemplate = transactionTemplate; } public static JpaMessageIdRepository jpaMessageIdRepository(String persistenceUnit, String processorName) { return jpaMessageIdRepository(Persistence.createEntityManagerFactory(persistenceUnit), processorName); } public static JpaMessageIdRepository jpaMessageIdRepository(EntityManagerFactory entityManagerFactory, String processorName) { return new JpaMessageIdRepository(entityManagerFactory, processorName); } private static TransactionTemplate createTransactionTemplate(EntityManagerFactory entityManagerFactory) { TransactionTemplate transactionTemplate = new TransactionTemplate(); transactionTemplate.setTransactionManager(new JpaTransactionManager(entityManagerFactory)); transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); return transactionTemplate; } @ManagedOperation(description = "Adds the key to the store") public boolean add(String messageId) { return add(null, messageId); } @Override public boolean add(final Exchange exchange, final String messageId) { final EntityManager entityManager = getTargetEntityManager(exchange, entityManagerFactory, true, sharedEntityManager, true); // Run this in single transaction. Boolean rc = transactionTemplate.execute(new TransactionCallback<Boolean>() { public Boolean doInTransaction(TransactionStatus status) { if (isJoinTransaction()) { entityManager.joinTransaction(); } try { List<?> list = query(entityManager, messageId); if (list.isEmpty()) { MessageProcessed processed = new MessageProcessed(); processed.setProcessorName(processorName); processed.setMessageId(messageId); processed.setCreatedAt(new Date()); entityManager.persist(processed); entityManager.flush(); entityManager.close(); return Boolean.TRUE; } else { return Boolean.FALSE; } } catch (Exception ex) { log.error("Something went wrong trying to add message to repository {}", ex); throw new PersistenceException(ex); } finally { try { if (entityManager.isOpen()) { entityManager.close(); } } catch (Exception e) { // ignore } } } }); log.debug("add {} -> {}", messageId, rc); return rc; } @ManagedOperation(description = "Does the store contain the given key") public boolean contains(String messageId) { return contains(null, messageId); } @Override public boolean contains(final Exchange exchange, final String messageId) { final EntityManager entityManager = getTargetEntityManager(exchange, entityManagerFactory, true, sharedEntityManager, true); // Run this in single transaction. Boolean rc = transactionTemplate.execute(new TransactionCallback<Boolean>() { public Boolean doInTransaction(TransactionStatus status) { if (isJoinTransaction()) { entityManager.joinTransaction(); } List<?> list = query(entityManager, messageId); if (list.isEmpty()) { return Boolean.FALSE; } else { return Boolean.TRUE; } } }); log.debug("contains {} -> {}", messageId, rc); return rc; } @ManagedOperation(description = "Remove the key from the store") public boolean remove(String messageId) { return remove(null, messageId); } @Override public boolean remove(final Exchange exchange, final String messageId) { final EntityManager entityManager = getTargetEntityManager(exchange, entityManagerFactory, true, sharedEntityManager, true); Boolean rc = transactionTemplate.execute(new TransactionCallback<Boolean>() { public Boolean doInTransaction(TransactionStatus status) { if (isJoinTransaction()) { entityManager.joinTransaction(); } try { List<?> list = query(entityManager, messageId); if (list.isEmpty()) { return Boolean.FALSE; } else { MessageProcessed processed = (MessageProcessed) list.get(0); entityManager.remove(processed); entityManager.flush(); entityManager.close(); return Boolean.TRUE; } } catch (Exception ex) { log.error("Something went wrong trying to remove message to repository {}", ex); throw new PersistenceException(ex); } finally { try { if (entityManager.isOpen()) { entityManager.close(); } } catch (Exception e) { // ignore } } } }); log.debug("remove {}", messageId); return rc; } @Override public boolean confirm(String messageId) { return confirm(null, messageId); } @Override public boolean confirm(final Exchange exchange, String messageId) { log.debug("confirm {} -> true", messageId); return true; } @ManagedOperation(description = "Clear the store") public void clear() { final EntityManager entityManager = getTargetEntityManager(null, entityManagerFactory, true, sharedEntityManager, true); transactionTemplate.execute(new TransactionCallback<Boolean>() { public Boolean doInTransaction(TransactionStatus status) { if (isJoinTransaction()) { entityManager.joinTransaction(); } try { List<?> list = queryClear(entityManager); if (!list.isEmpty()) { Iterator it = list.iterator(); while (it.hasNext()) { Object item = it.next(); entityManager.remove(item); } entityManager.flush(); entityManager.close(); } return Boolean.TRUE; } catch (Exception ex) { log.error("Something went wrong trying to clear the repository {}", ex); throw new PersistenceException(ex); } finally { try { if (entityManager.isOpen()) { entityManager.close(); } } catch (Exception e) { // ignore } } } }); log.debug("clear the store {}", MessageProcessed.class.getName()); } private List<?> query(final EntityManager entityManager, final String messageId) { Query query = entityManager.createQuery(QUERY_STRING); query.setParameter(1, processorName); query.setParameter(2, messageId); return query.getResultList(); } private List<?> queryClear(final EntityManager entityManager) { Query query = entityManager.createQuery(QUERY_CLEAR_STRING); query.setParameter(1, processorName); return query.getResultList(); } @ManagedAttribute(description = "The processor name") public String getProcessorName() { return processorName; } @ManagedAttribute(description = "Whether to join existing transaction") public boolean isJoinTransaction() { return joinTransaction; } public void setJoinTransaction(boolean joinTransaction) { this.joinTransaction = joinTransaction; } @ManagedAttribute(description = "Whether to use shared EntityManager") public boolean isSharedEntityManager() { return sharedEntityManager; } public void setSharedEntityManager(boolean sharedEntityManager) { this.sharedEntityManager = sharedEntityManager; } @Override protected void doStart() throws Exception { // noop } @Override protected void doStop() throws Exception { // noop } }
/** * generated by Xtext 2.12.0 */ package fire.fire.impl; import fire.fire.AdditiveExpression; import fire.fire.AdditiveOperator; import fire.fire.Expression; import fire.fire.FirePackage; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Additive Expression</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link fire.fire.impl.AdditiveExpressionImpl#getLeft <em>Left</em>}</li> * <li>{@link fire.fire.impl.AdditiveExpressionImpl#getOperator <em>Operator</em>}</li> * <li>{@link fire.fire.impl.AdditiveExpressionImpl#getRight <em>Right</em>}</li> * </ul> * * @generated */ public class AdditiveExpressionImpl extends ExpressionImpl implements AdditiveExpression { /** * The cached value of the '{@link #getLeft() <em>Left</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLeft() * @generated * @ordered */ protected Expression left; /** * The default value of the '{@link #getOperator() <em>Operator</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOperator() * @generated * @ordered */ protected static final AdditiveOperator OPERATOR_EDEFAULT = AdditiveOperator.ADD; /** * The cached value of the '{@link #getOperator() <em>Operator</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOperator() * @generated * @ordered */ protected AdditiveOperator operator = OPERATOR_EDEFAULT; /** * The cached value of the '{@link #getRight() <em>Right</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRight() * @generated * @ordered */ protected Expression right; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected AdditiveExpressionImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return FirePackage.Literals.ADDITIVE_EXPRESSION; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Expression getLeft() { return left; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetLeft(Expression newLeft, NotificationChain msgs) { Expression oldLeft = left; left = newLeft; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FirePackage.ADDITIVE_EXPRESSION__LEFT, oldLeft, newLeft); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLeft(Expression newLeft) { if (newLeft != left) { NotificationChain msgs = null; if (left != null) msgs = ((InternalEObject)left).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FirePackage.ADDITIVE_EXPRESSION__LEFT, null, msgs); if (newLeft != null) msgs = ((InternalEObject)newLeft).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FirePackage.ADDITIVE_EXPRESSION__LEFT, null, msgs); msgs = basicSetLeft(newLeft, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FirePackage.ADDITIVE_EXPRESSION__LEFT, newLeft, newLeft)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public AdditiveOperator getOperator() { return operator; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setOperator(AdditiveOperator newOperator) { AdditiveOperator oldOperator = operator; operator = newOperator == null ? OPERATOR_EDEFAULT : newOperator; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FirePackage.ADDITIVE_EXPRESSION__OPERATOR, oldOperator, operator)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Expression getRight() { return right; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetRight(Expression newRight, NotificationChain msgs) { Expression oldRight = right; right = newRight; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FirePackage.ADDITIVE_EXPRESSION__RIGHT, oldRight, newRight); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setRight(Expression newRight) { if (newRight != right) { NotificationChain msgs = null; if (right != null) msgs = ((InternalEObject)right).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FirePackage.ADDITIVE_EXPRESSION__RIGHT, null, msgs); if (newRight != null) msgs = ((InternalEObject)newRight).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FirePackage.ADDITIVE_EXPRESSION__RIGHT, null, msgs); msgs = basicSetRight(newRight, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, FirePackage.ADDITIVE_EXPRESSION__RIGHT, newRight, newRight)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case FirePackage.ADDITIVE_EXPRESSION__LEFT: return basicSetLeft(null, msgs); case FirePackage.ADDITIVE_EXPRESSION__RIGHT: return basicSetRight(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case FirePackage.ADDITIVE_EXPRESSION__LEFT: return getLeft(); case FirePackage.ADDITIVE_EXPRESSION__OPERATOR: return getOperator(); case FirePackage.ADDITIVE_EXPRESSION__RIGHT: return getRight(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case FirePackage.ADDITIVE_EXPRESSION__LEFT: setLeft((Expression)newValue); return; case FirePackage.ADDITIVE_EXPRESSION__OPERATOR: setOperator((AdditiveOperator)newValue); return; case FirePackage.ADDITIVE_EXPRESSION__RIGHT: setRight((Expression)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case FirePackage.ADDITIVE_EXPRESSION__LEFT: setLeft((Expression)null); return; case FirePackage.ADDITIVE_EXPRESSION__OPERATOR: setOperator(OPERATOR_EDEFAULT); return; case FirePackage.ADDITIVE_EXPRESSION__RIGHT: setRight((Expression)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case FirePackage.ADDITIVE_EXPRESSION__LEFT: return left != null; case FirePackage.ADDITIVE_EXPRESSION__OPERATOR: return operator != OPERATOR_EDEFAULT; case FirePackage.ADDITIVE_EXPRESSION__RIGHT: return right != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (operator: "); result.append(operator); result.append(')'); return result.toString(); } } //AdditiveExpressionImpl
/* * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * @test * @bug 4823811 * @summary Confirm that text which includes numbers with a trailing minus sign is parsed correctly. * @run main/othervm -Duser.timezone=GMT+09:00 Bug4823811 */ import java.text.*; import java.util.*; public class Bug4823811 { private static Locale localeEG = new Locale("ar", "EG"); private static Locale localeUS = Locale.US; private static String JuneInArabic = "\u064a\u0648\u0646\u064a\u0648"; private static String JulyInArabic = "\u064a\u0648\u0644\u064a\u0648"; private static String JuneInEnglish = "June"; private static String JulyInEnglish = "July"; private static String BORDER = "============================================================"; /* * I don't use static import here intentionally so that this test program * can be run on JDK 1.4.2. */ private static int ERA = Calendar.ERA; private static int BC = GregorianCalendar.BC; // private static int JAN = Calendar.JANUARY; // private static int FEB = Calendar.FEBRUARY; // private static int MAR = Calendar.MARCH; private static int APR = Calendar.APRIL; private static int MAY = Calendar.MAY; private static int JUN = Calendar.JUNE; private static int JUL = Calendar.JULY; // private static int AUG = Calendar.AUGUST; // private static int SEP = Calendar.SEPTEMBER; // private static int OCT = Calendar.OCTOBER; // private static int NOV = Calendar.NOVEMBER; // private static int DEC = Calendar.DECEMBER; private static String[] patterns = { "yyyy MMMM d H m s", "yyyy MM dd hh mm ss", /* * Because 1-based HOUR_OF_DAY, 1-based HOUR, MONTH, and YEAR fields * are parsed using different code from the code for other numeric * fields, I prepared YEAR-preceding patterns and SECOND-preceding * patterns. */ "yyyy M d h m s", " yyyy M d h m s", "yyyy M d h m s ", "s m h d M yyyy", " s m h d M yyyy", "s m h d M yyyy ", }; private static char originalMinusSign1 = ':'; private static char originalMinusSign2 = '\uff0d'; // fullwidth minus private static String[] delimiters = {"-", "/", ":", "/", "\uff0d", "/"}; private static String[][] specialDelimiters = { // for Arabic formatter and modified English formatter {"--", "-/", "::", ":/", "\uff0d\uff0d", "\uff0d/"}, // for English formatter and modified Arabic formatter {"--", "/-", "::", "/:", "\uff0d\uff0d", "/\uff0d"}, }; /* * Format: * +-------------------------------------------------------------------+ * | Input | Output | * +---------------------+---------------------------------------------| * | datesEG & datesUS | formattedDatesEG & formattedDatesUS | * +-------------------------------------------------------------------+ * * Parse: * +-------------------------------------------------------------------+ * | Input | Output | * |---------------------+---------------------------------------------| * | datesToParse | datesEG & datesUS | * +-------------------------------------------------------------------+ */ private static String[][] datesToParse = { // "JUNE" and "JULY" are replaced with a localized month name later. {"2008 JULY 20 3 12 83", "2008 JULY 20 3 12 83", "2008 JULY 20 3 12 83"}, {"2008 07 20 03 12 83", "2008 07 20 03 12 83", "2008 07 20 03 12 83"}, {"2008 7 20 3 12 83", "2008 7 20 3 12 83", "2008 7 20 3 12 83"}, {" 2008 7 20 3 12 83", " 2008 7 20 3 12 83", " 2008 7 20 3 12 83", "2008 7 20 3 12 83"}, {"2008 7 20 3 12 83 ", "2008 7 20 3 12 83 ", "2008 7 20 3 12 83"}, {"83 12 3 20 7 2008", "83 12 3 20 7 2008", "83 12 3 20 7 2008"}, {" 83 12 3 20 7 2008", " 83 12 3 20 7 2008", " 83 12 3 20 7 2008", "83 12 3 20 7 2008"}, {"83 12 3 20 7 2008 ", "83 12 3 20 7 2008 ", "83 12 3 20 7 2008"}, }; // For formatting private static String[][] formattedDatesEG = { {"2008 JULY 20 3 13 23", "2009 JULY 20 3 13 23", null}, {"2008 07 20 03 13 23", "2009 07 20 03 13 23", "2007 05 20 03 13 23"}, {"2008 7 20 3 13 23", "2009 6 10 3 13 23", "2007 4 10 3 13 23"}, {" 2008 7 20 3 13 23", null, " 2009 7 20 3 13 23", null}, {"2008 7 20 3 13 23 ", "2008 7 20 3 10 37 ", null}, {"23 13 3 20 7 2008", "37 10 9 19 7 2008", "23 49 8 19 7 2008"}, {" 23 13 3 20 7 2008", null, " 37 10 3 20 7 2008", null}, {"23 13 3 20 7 2008 ", "23 13 3 20 7 2009 ", null}, }; private static String[][] formattedDatesUS = { {"2008 JULY 20 3 13 23", null, "2008 JUNE 10 3 13 23"}, {"2008 07 20 03 13 23", "2007 05 20 03 13 23", "2008 06 10 03 13 23"}, {"2008 7 20 3 13 23", "2007 5 19 9 13 23", "2008 6 9 9 13 23"}, {" 2008 7 20 3 13 23", " 2009 7 20 3 13 23", " 2007 5 20 3 13 23", null}, {"2008 7 20 3 13 23 ", "2008 7 20 3 13 23 ", null}, {"23 13 3 20 7 2008", "23 49 2 10 6 2008", "23 13 9 9 6 2008"}, {" 23 13 3 20 7 2008", " 37 10 3 20 7 2008", " 23 49 2 20 7 2008", null}, {"23 13 3 20 7 2008 ", "23 13 3 20 7 2008 ", null}, }; private static GregorianCalendar[][] datesEG = { {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), new GregorianCalendar(-2008, JUL, 20, 3, 12, 83), null}, {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), new GregorianCalendar(-2008, JUL, 20, 3, 12, 83), new GregorianCalendar( 2007, MAY, 20, 3, 12, 83)}, {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), new GregorianCalendar(-2008, JUL, -20, 3, 12, 83), new GregorianCalendar( 2007, APR, 10, 3, 12, 83)}, {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), null, new GregorianCalendar(-2008, JUL, 20, 3, 12, 83), null}, {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), new GregorianCalendar( 2008, JUL, 20, 3, 12, -83), null}, {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), new GregorianCalendar( 2008, JUL, 20, -3, 12, -83), new GregorianCalendar( 2008, JUL, 20, -3, -12, 83)}, {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), null, new GregorianCalendar( 2008, JUL, 20, 3, 12, -83), null}, {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), new GregorianCalendar(-2008, JUL, 20, 3, 12, 83), null}, }; private static GregorianCalendar[][] datesUS = { {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), null, new GregorianCalendar( 2008, JUN, 10, 3, 12, 83)}, {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), new GregorianCalendar( 2007, MAY, 20, 3, 12, 83), new GregorianCalendar( 2008, JUN, 10, 3, 12, 83)}, {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), new GregorianCalendar( 2007, MAY, 20, -3, 12, 83), new GregorianCalendar( 2008, JUL, -20, -3, 12, 83)}, {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), new GregorianCalendar(-2008, JUL, 20, 3, 12, 83), new GregorianCalendar( 2007, MAY, 20, 3, 12, 83), null}, {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), null}, {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), new GregorianCalendar( 2008, JUL, -20, 3, -12, 83), new GregorianCalendar( 2008, JUL, -20, -3, 12, 83)}, {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), new GregorianCalendar( 2008, JUL, 20, 3, 12, -83), new GregorianCalendar( 2008, JUL, 20, 3, -12, 83), null}, {new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), new GregorianCalendar( 2008, JUL, 20, 3, 12, 83), null}, }; /* flags */ private static boolean err = false; private static boolean verbose = false; public static void main(String[] args) { if (args.length == 1 && args[0].equals("-v")) { verbose = true; } Locale defaultLocale = Locale.getDefault(); TimeZone defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("Asia/Tokyo")); try { /* * Test SimpleDateFormat.parse() and format() for original * SimpleDateFormat instances */ testDateFormat1(); /* * Test SimpleDateFormat.parse() and format() for modified * SimpleDateFormat instances using an original minus sign, * pattern, and diffenrent month names in DecimalFormat */ testDateFormat2(); /* * Test SimpleDateFormat.parse() and format() for modified * SimpleDateFormat instances using a fullwidth minus sign */ testDateFormat3(); /* * Just to confirm that regressions aren't introduced in * DecimalFormat. This cannot happen, though. Because I didn't * change DecimalFormat at all. */ testNumberFormat(); } catch (Exception e) { err = true; System.err.println("Unexpected exception: " + e); } finally { Locale.setDefault(defaultLocale); TimeZone.setDefault(defaultTimeZone); if (err) { System.err.println(BORDER + " Test failed."); throw new RuntimeException("Date/Number formatting/parsing error."); } else { System.out.println(BORDER + " Test passed."); } } } // // DateFormat test // private static void testDateFormat1() { for (int i = 0; i < patterns.length; i++) { System.out.println(BORDER); for (int j = 0; j <= 1; j++) { // Generate a pattern String pattern = patterns[i].replaceAll(" ", delimiters[j]); System.out.println("Pattern=\"" + pattern + "\""); System.out.println("*** DateFormat.format test in ar_EG"); testDateFormatFormattingInRTL(pattern, i, j, null, localeEG, false); System.out.println("*** DateFormat.parse test in ar_EG"); testDateFormatParsingInRTL(pattern, i, j, null, localeEG, false); System.out.println("*** DateFormat.format test in en_US"); testDateFormatFormattingInLTR(pattern, i, j, null, localeUS, true); System.out.println("*** DateFormat.parse test in en_US"); testDateFormatParsingInLTR(pattern, i, j, null, localeUS, true); } } } private static void testDateFormat2() { /* * modified ar_EG Date&Time formatter : * minus sign: ':' * pattern: "#,##0.###" * month names: In Arabic * * modified en_US Date&Time formatter : * minus sign: ':' * pattern: "#,##0.###;#,##0.###-" * month names: In English */ DecimalFormat dfEG = (DecimalFormat)NumberFormat.getInstance(localeEG); DecimalFormat dfUS = (DecimalFormat)NumberFormat.getInstance(localeUS); DecimalFormatSymbols dfsEG = dfEG.getDecimalFormatSymbols(); DecimalFormatSymbols dfsUS = dfUS.getDecimalFormatSymbols(); dfsEG.setMinusSign(originalMinusSign1); dfsUS.setMinusSign(originalMinusSign1); dfEG.setDecimalFormatSymbols(dfsUS); dfUS.setDecimalFormatSymbols(dfsEG); String patternEG = dfEG.toPattern(); String patternUS = dfUS.toPattern(); dfEG.applyPattern(patternUS); dfUS.applyPattern(patternEG); for (int i = 0; i < patterns.length; i++) { System.out.println(BORDER); for (int j = 2; j <= 3; j++) { // Generate a pattern String pattern = patterns[i].replaceAll(" ", delimiters[j]); System.out.println("Pattern=\"" + pattern + "\""); System.out.println("*** DateFormat.format test in modified en_US"); testDateFormatFormattingInRTL(pattern, i, j, dfUS, localeUS, true); System.out.println("*** DateFormat.parse test in modified en_US"); testDateFormatParsingInRTL(pattern, i, j, dfUS, localeUS, true); System.out.println("*** DateFormat.format test in modified ar_EG"); testDateFormatFormattingInLTR(pattern, i, j, dfEG, localeEG, false); System.out.println("*** DateFormat.parse test in modified ar_EG"); testDateFormatParsingInLTR(pattern, i, j, dfEG, localeEG, false); } } } private static void testDateFormat3() { /* * modified ar_EG Date&Time formatter : * minus sign: '\uff0d' // fullwidth minus * pattern: "#,##0.###;#,##0.###-" * month names: In Arabic * * modified en_US Date&Time formatter : * minus sign: '\uff0d' // fullwidth minus * pattern: "#,##0.###" * month names: In English */ DecimalFormat dfEG = (DecimalFormat)NumberFormat.getInstance(localeEG); DecimalFormat dfUS = (DecimalFormat)NumberFormat.getInstance(localeUS); DecimalFormatSymbols dfsEG = dfEG.getDecimalFormatSymbols(); DecimalFormatSymbols dfsUS = dfUS.getDecimalFormatSymbols(); dfsEG.setMinusSign(originalMinusSign2); dfsUS.setMinusSign(originalMinusSign2); dfEG.setDecimalFormatSymbols(dfsEG); dfUS.setDecimalFormatSymbols(dfsUS); for (int i = 0; i < patterns.length; i++) { System.out.println(BORDER); for (int j = 4; j <= 5; j++) { // Generate a pattern String pattern = patterns[i].replaceAll(" ", delimiters[j]); System.out.println("Pattern=\"" + pattern + "\""); System.out.println("*** DateFormat.format test in modified ar_EG"); testDateFormatFormattingInRTL(pattern, i, j, dfEG, localeEG, false); System.out.println("*** DateFormat.parse test in modified ar_EG"); testDateFormatParsingInRTL(pattern, i, j, dfEG, localeEG, false); System.out.println("*** DateFormat.format test in modified en_US"); testDateFormatFormattingInLTR(pattern, i, j, dfUS, localeUS, true); System.out.println("*** DateFormat.parse test in modified en_US"); testDateFormatParsingInLTR(pattern, i, j, dfUS, localeUS, true); } } } private static void testDateFormatFormattingInRTL(String pattern, int basePattern, int delimiter, NumberFormat nf, Locale locale, boolean useEnglishMonthName) { Locale.setDefault(locale); SimpleDateFormat sdf = new SimpleDateFormat(pattern); if (nf != null) { sdf.setNumberFormat(nf); } for (int i = 0; i < datesToParse[basePattern].length; i++) { if (datesEG[basePattern][i] == null) { continue; } String expected = formattedDatesEG[basePattern][i] .replaceAll("JUNE", (useEnglishMonthName ? JuneInEnglish : JuneInArabic)) .replaceAll("JULY", (useEnglishMonthName ? JulyInEnglish : JulyInArabic)) .replaceAll(" ", delimiters[delimiter]); testDateFormatFormatting(sdf, pattern, datesEG[basePattern][i], expected, locale.toString()); } } private static void testDateFormatFormattingInLTR(String pattern, int basePattern, int delimiter, NumberFormat nf, Locale locale, boolean useEnglishMonthName) { Locale.setDefault(locale); SimpleDateFormat sdf = new SimpleDateFormat(pattern); if (nf != null) { sdf.setNumberFormat(nf); } for (int i = 0; i < datesToParse[basePattern].length; i++) { if (datesUS[basePattern][i] == null) { continue; } String expected = formattedDatesUS[basePattern][i] .replaceAll("JUNE", (useEnglishMonthName ? JuneInEnglish : JuneInArabic)) .replaceAll("JULY", (useEnglishMonthName ? JulyInEnglish : JulyInArabic)) .replaceAll(" ", delimiters[delimiter]); testDateFormatFormatting(sdf, pattern, datesUS[basePattern][i], expected, locale.toString()); } } private static void testDateFormatFormatting(SimpleDateFormat sdf, String pattern, GregorianCalendar givenGC, String expected, String locale) { Date given = givenGC.getTime(); String str = sdf.format(given); if (expected.equals(str)) { if (verbose) { System.out.print(" Passed: SimpleDateFormat("); System.out.print(locale + ", \"" + pattern + "\").format("); System.out.println(given + ")"); System.out.print(" ---> \"" + str + "\" "); System.out.println((givenGC.get(ERA) == BC) ? "(BC)" : "(AD)"); } } else { err = true; System.err.print(" Failed: Unexpected SimpleDateFormat("); System.out.print(locale + ", \"" + pattern + "\").format("); System.out.println(given + ") result."); System.out.println(" Expected: \"" + expected + "\""); System.out.print(" Got: \"" + str + "\" "); System.out.println((givenGC.get(ERA) == BC) ? "(BC)" : "(AD)"); } } private static void testDateFormatParsingInRTL(String pattern, int basePattern, int delimiter, NumberFormat nf, Locale locale, boolean useEnglishMonthName) { Locale.setDefault(locale); SimpleDateFormat sdf = new SimpleDateFormat(pattern); if (nf != null) { sdf.setNumberFormat(nf); } for (int i = 0; i < datesToParse[basePattern].length; i++) { String given = datesToParse[basePattern][i] .replaceAll(" ", specialDelimiters[0][delimiter]) .replaceAll(" ", delimiters[delimiter]); testDateFormatParsing(sdf, pattern, given.replaceAll("JULY", (useEnglishMonthName ? JulyInEnglish : JulyInArabic)), datesEG[basePattern][i], locale.toString()); } } private static void testDateFormatParsingInLTR(String pattern, int basePattern, int delimiter, NumberFormat nf, Locale locale, boolean useEnglishMonthName) { Locale.setDefault(locale); SimpleDateFormat sdf = new SimpleDateFormat(pattern); if (nf != null) { sdf.setNumberFormat(nf); } for (int i = 0; i < datesToParse[basePattern].length; i++) { String given = datesToParse[basePattern][i] .replaceAll(" ", specialDelimiters[1][delimiter]) .replaceAll(" ", delimiters[delimiter]); testDateFormatParsing(sdf, pattern, given.replaceAll("JULY", (useEnglishMonthName ? JulyInEnglish : JulyInArabic)), datesUS[basePattern][i], locale.toString()); } } private static void testDateFormatParsing(SimpleDateFormat sdf, String pattern, String given, GregorianCalendar expectedGC, String locale) { try { Date d = sdf.parse(given); if (expectedGC == null) { err = true; System.err.print(" Failed: SimpleDateFormat(" + locale); System.err.print(", \"" + pattern + "\").parse(\"" + given); System.err.println("\") should have thrown ParseException"); } else if (expectedGC.getTime().equals(d)) { if (verbose) { System.out.print(" Passed: SimpleDateFormat(" + locale); System.out.print(", \"" + pattern + "\").parse(\"" + given); System.out.println("\")"); System.out.print(" ---> " + d + " (" + d.getTime()); System.out.println(")"); } } else { err = true; System.err.print(" Failed: SimpleDateFormat(" + locale); System.err.print(", \"" + pattern + "\").parse(\"" + given); System.err.println("\")"); System.err.print(" Expected: " + expectedGC.getTime()); System.err.println(" (" + d.getTime() + ")"); System.err.print(" Got: " + d + " (" + d.getTime()); System.err.println(")"); System.err.print(" Pattern: \""); System.err.print(((DecimalFormat)sdf.getNumberFormat()).toPattern()); System.err.println("\""); } } catch (ParseException pe) { if (expectedGC == null) { if (verbose) { System.out.print(" Passed: SimpleDateFormat(" + locale); System.out.print(", \"" + pattern + "\").parse(\"" + given); System.out.println("\")"); System.out.println(" threw ParseException as expected"); } } else { err = true; System.err.println(" Failed: Unexpected exception with"); System.err.print(" SimpleDateFormat(" + locale); System.err.print(", \"" + pattern + "\").parse(\""); System.err.println(given + "\"):"); System.err.println(" " + pe); System.err.print(" Pattern: \""); System.err.print(((DecimalFormat)sdf.getNumberFormat()).toPattern()); System.err.println("\""); System.err.print(" Month 0: "); System.err.println(sdf.getDateFormatSymbols().getMonths()[0]); } } } // // NumberFormat test // private static void testNumberFormat() { NumberFormat nfEG = NumberFormat.getInstance(localeEG); NumberFormat nfUS = NumberFormat.getInstance(localeUS); System.out.println("*** DecimalFormat.format test in ar_EG"); testNumberFormatFormatting(nfEG, -123456789, "123,456,789-", "ar_EG"); testNumberFormatFormatting(nfEG, -456, "456-", "ar_EG"); System.out.println("*** DecimalFormat.parse test in ar_EG"); testNumberFormatParsing(nfEG, "123-", new Long(-123), "ar_EG"); testNumberFormatParsing(nfEG, "123--", new Long(-123), "ar_EG"); testNumberFormatParsingCheckException(nfEG, "-123", 0, "ar_EG"); System.out.println("*** DecimalFormat.format test in en_US"); testNumberFormatFormatting(nfUS, -123456789, "-123,456,789", "en_US"); testNumberFormatFormatting(nfUS, -456, "-456", "en_US"); System.out.println("*** DecimalFormat.parse test in en_US"); testNumberFormatParsing(nfUS, "123-", new Long(123), "en_US"); testNumberFormatParsing(nfUS, "-123", new Long(-123), "en_US"); testNumberFormatParsingCheckException(nfUS, "--123", 0, "en_US"); } private static void testNumberFormatFormatting(NumberFormat nf, int given, String expected, String locale) { String str = nf.format(given); if (expected.equals(str)) { if (verbose) { System.out.print(" Passed: NumberFormat(" + locale); System.out.println(").format(" + given + ")"); System.out.println(" ---> \"" + str + "\""); } } else { err = true; System.err.print(" Failed: Unexpected NumberFormat(" + locale); System.err.println(").format(" + given + ") result."); System.err.println(" Expected: \"" + expected + "\""); System.err.println(" Got: \"" + str + "\""); } } private static void testNumberFormatParsing(NumberFormat nf, String given, Number expected, String locale) { try { Number n = nf.parse(given); if (n.equals(expected)) { if (verbose) { System.out.print(" Passed: NumberFormat(" + locale); System.out.println(").parse(\"" + given + "\")"); System.out.println(" ---> " + n); } } else { err = true; System.err.print(" Failed: Unexpected NumberFormat(" + locale); System.err.println(").parse(\"" + given + "\") result."); System.err.println(" Expected: " + expected); System.err.println(" Got: " + n); } } catch (ParseException pe) { err = true; System.err.print(" Failed: Unexpected exception with NumberFormat("); System.err.println(locale + ").parse(\"" + given + "\") :"); System.err.println(" " + pe); } } private static void testNumberFormatParsingCheckException(NumberFormat nf, String given, int expected, String locale) { try { Number n = nf.parse(given); err = true; System.err.print(" Failed: NumberFormat(" + locale); System.err.println(").parse(\"" + given + "\")"); System.err.println(" should have thrown ParseException"); } catch (ParseException pe) { int errorOffset = pe.getErrorOffset(); if (errorOffset == expected) { if (verbose) { System.out.print(" Passed: NumberFormat(" + locale); System.out.println(").parse(\"" + given + "\")"); System.out.print(" threw ParseException as expected, and its errorOffset was correct: "); System.out.println(errorOffset); } } else { err = true; System.err.print(" Failed: NumberFormat(" + locale); System.err.println(").parse(\"" + given + "\")"); System.err.print(" threw ParseException as expected, but its errorOffset was incorrect: "); System.err.println(errorOffset); } } } }
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.formatter.xml; import com.intellij.formatting.*; import com.intellij.lang.ASTNode; import com.intellij.lang.xml.XMLLanguage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiWhiteSpace; import com.intellij.psi.TokenType; import com.intellij.psi.formatter.common.AbstractBlock; import com.intellij.psi.impl.source.SourceTreeToPsiMap; import com.intellij.psi.templateLanguages.OuterLanguageElement; import com.intellij.psi.tree.IElementType; import com.intellij.psi.xml.*; import com.intellij.util.SmartList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; public class XmlBlock extends AbstractXmlBlock { private final Indent myIndent; private final TextRange myTextRange; private static final Logger LOG = Logger.getInstance(XmlBlock.class); public XmlBlock(final ASTNode node, final Wrap wrap, final Alignment alignment, final XmlFormattingPolicy policy, final Indent indent, final TextRange textRange) { this(node, wrap, alignment, policy, indent, textRange, false); } public XmlBlock(final ASTNode node, final Wrap wrap, final Alignment alignment, final XmlFormattingPolicy policy, final Indent indent, final TextRange textRange, final boolean preserveSpace) { super(node, wrap, alignment, policy, preserveSpace); myIndent = indent; myTextRange = textRange; } @Override @NotNull public TextRange getTextRange() { if (myTextRange != null && !(isCDATAStart() || isCDATAEnd())) { return myTextRange; } else { return super.getTextRange(); } } @Override protected List<Block> buildChildren() { // // Fix for EA-19269: // Split XML attribute value to the value itself and delimiters (needed for the case when it contains // template language tags inside). // if (myNode.getElementType() == XmlElementType.XML_ATTRIBUTE_VALUE) { return splitAttribute(myNode, myXmlFormattingPolicy); } if (myNode.getElementType() == XmlElementType.XML_COMMENT) { List<Block> result = new SmartList<>(); if (buildInjectedPsiBlocks(result, myNode, myWrap, null, Indent.getNoneIndent())) { return result; } return splitComment(); } if (myNode.getFirstChildNode() != null) { boolean keepWhitespaces = shouldKeepWhitespaces(); final ArrayList<Block> result = new ArrayList<>(5); ASTNode child = myNode.getFirstChildNode(); while (child != null) { if (child.getTextLength() > 0) { if (containsWhiteSpacesOnly(child)) { if (keepWhitespaces) { result.add(new ReadOnlyBlock(child)); } } else { child = processChild(result, child, getDefaultWrap(child), null, getChildDefaultIndent()); } } if (child != null) { LOG.assertTrue(child.getTreeParent() == myNode); child = child.getTreeNext(); } } return result; } else { return EMPTY; } } private boolean shouldKeepWhitespaces() { if (myNode.getElementType() == XmlElementType.XML_TEXT) { if (myXmlFormattingPolicy.getShouldKeepWhiteSpaces()) { return true; } else { final ASTNode treeParent = myNode.getTreeParent(); final XmlTag tag = getTag(treeParent); if (tag != null) { if (myXmlFormattingPolicy.keepWhiteSpacesInsideTag(tag)) { return true; } } } } return false; } protected List<Block> splitAttribute(ASTNode node, XmlFormattingPolicy formattingPolicy) { final ArrayList<Block> result = new ArrayList<>(3); ASTNode child = node.getFirstChildNode(); while (child != null) { if (child.getElementType() == XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER || child.getElementType() == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER) { result.add(new XmlBlock(child, null, null, formattingPolicy, null, null, isPreserveSpace())); } else if (!child.getPsi().getLanguage().isKindOf(XMLLanguage.INSTANCE) && containsOuterLanguageElement(child)) { // Fix for EA-20311: // In case of another embedded language create a splittable XML block which can be // merged with other language's code blocks. createLeafBlocks(child, result); } else if (child.getElementType() != TokenType.ERROR_ELEMENT || child.getFirstChildNode() != null) { result.add(new ReadOnlyBlock(child)); } child = child.getTreeNext(); } return result; } private void createLeafBlocks(ASTNode node, List<Block> result) { if (node instanceof OuterLanguageElement) { processChild(result, node, null, null, null); return; } ASTNode child = node.getFirstChildNode(); if (child == null && !(node instanceof PsiWhiteSpace) && node.getElementType() != TokenType.ERROR_ELEMENT && node.getTextLength() > 0) { result.add(new ReadOnlyBlock(node)); return; } while (child != null) { createLeafBlocks(child, result); child = child.getTreeNext(); } } private static boolean containsOuterLanguageElement(ASTNode node) { if (node instanceof OuterLanguageElement) { return true; } ASTNode child = node.getFirstChildNode(); while (child != null) { if (child instanceof OuterLanguageElement) { return true; } if (containsOuterLanguageElement(child)) return true; child = child.getTreeNext(); } return false; } protected List<Block> splitComment() { if (myNode.getElementType() != XmlElementType.XML_COMMENT) return EMPTY; final ArrayList<Block> result = new ArrayList<>(3); ASTNode child = myNode.getFirstChildNode(); boolean hasOuterLangElements = false; while (child != null) { if (child instanceof OuterLanguageElement) { hasOuterLangElements = true; } result.add(new XmlBlock(child, null, null, myXmlFormattingPolicy, getChildIndent(), null, isPreserveSpace())); child = child.getTreeNext(); } if (hasOuterLangElements) { return result; } else { return EMPTY; } } @Nullable protected Wrap getDefaultWrap(ASTNode node) { return null; } @Nullable protected Indent getChildDefaultIndent() { if (myNode.getElementType() == XmlElementType.HTML_DOCUMENT) { return Indent.getNoneIndent(); } if (myNode.getElementType() == TokenType.DUMMY_HOLDER) { return Indent.getNoneIndent(); } if (myNode.getElementType() == XmlElementType.XML_PROLOG) { return Indent.getNoneIndent(); } else { return null; } } @Override public Spacing getSpacing(Block child1, @NotNull Block child2) { if (!(child1 instanceof AbstractBlock) || !(child2 instanceof AbstractBlock)) { return null; } final IElementType elementType = myNode.getElementType(); final ASTNode node1 = ((AbstractBlock)child1).getNode(); final IElementType type1 = node1.getElementType(); final ASTNode node2 = ((AbstractBlock)child2).getNode(); final IElementType type2 = node2.getElementType(); if ((isXmlTag(node2) || type2 == XmlTokenType.XML_END_TAG_START || type2 == XmlElementType.XML_TEXT) && myXmlFormattingPolicy .getShouldKeepWhiteSpaces()) { return Spacing.getReadOnlySpacing(); } if (elementType == XmlElementType.XML_TEXT) { return getSpacesInsideText(type1, type2); } else if (isAttributeElementType(elementType)) { return getSpacesInsideAttribute(type1, type2); } if (type1 == XmlElementType.XML_PROLOG) { return createDefaultSpace(true, false); } if (elementType == XmlElementType.XML_DOCTYPE) { return createDefaultSpace(true, false); } if (type1 == XmlElementType.XML_COMMENT) { return createDefaultSpace(true, false); } return createDefaultSpace(false, false); } protected Spacing getSpacesInsideAttribute(final IElementType type1, final IElementType type2) { if (type1 == XmlTokenType.XML_EQ || type2 == XmlTokenType.XML_EQ) { int spaces = myXmlFormattingPolicy.getShouldAddSpaceAroundEqualityInAttribute() ? 1 : 0; return Spacing .createSpacing(spaces, spaces, 0, myXmlFormattingPolicy.getShouldKeepLineBreaks(), myXmlFormattingPolicy.getKeepBlankLines()); } else { return createDefaultSpace(false, false); } } private Spacing getSpacesInsideText(final IElementType type1, final IElementType type2) { if (type1 == XmlTokenType.XML_DATA_CHARACTERS && type2 == XmlTokenType.XML_DATA_CHARACTERS) { return Spacing .createSpacing(1, 1, 0, myXmlFormattingPolicy.getShouldKeepLineBreaksInText(), myXmlFormattingPolicy.getKeepBlankLines()); } else { return createDefaultSpace(false, true); } } @Override public Indent getIndent() { if (myNode.getElementType() == XmlElementType.XML_PROLOG || myNode.getElementType() == XmlElementType.XML_DOCTYPE || SourceTreeToPsiMap.treeElementToPsi(myNode) instanceof XmlDocument) { return Indent.getNoneIndent(); } return myIndent; } @Override public boolean insertLineBreakBeforeTag() { return false; } @Override public boolean removeLineBreakBeforeTag() { return false; } @Override public boolean isTextElement() { return myNode.getElementType() == XmlElementType.XML_TEXT || myNode.getElementType() == XmlTokenType.XML_DATA_CHARACTERS || myNode.getElementType() == XmlTokenType.XML_CHAR_ENTITY_REF || myNode.getElementType() == XmlElementType.XML_ENTITY_REF; } @Override @NotNull public ChildAttributes getChildAttributes(final int newChildIndex) { PsiElement element = myNode.getPsi(); if (element instanceof PsiFile || element instanceof XmlDocument || element instanceof XmlProlog) { return new ChildAttributes(Indent.getNoneIndent(), null); } else { return super.getChildAttributes(newChildIndex); } } public XmlFormattingPolicy getPolicy() { return myXmlFormattingPolicy; } }
/** * 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.metamodel.excel; import java.io.File; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.metamodel.MetaModelException; import org.apache.metamodel.data.DataSet; import org.apache.metamodel.data.DataSetHeader; import org.apache.metamodel.data.DefaultRow; import org.apache.metamodel.data.EmptyDataSet; import org.apache.metamodel.data.Style; import org.apache.metamodel.data.Style.SizeUnit; import org.apache.metamodel.data.StyleBuilder; import org.apache.metamodel.query.SelectItem; import org.apache.metamodel.schema.ColumnType; import org.apache.metamodel.schema.Table; import org.apache.metamodel.util.DateUtils; import org.apache.metamodel.util.FileHelper; import org.apache.metamodel.util.FileResource; import org.apache.metamodel.util.InMemoryResource; import org.apache.metamodel.util.Resource; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.BuiltinFormats; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Color; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.FontUnderline; import org.apache.poi.ss.usermodel.FormulaError; import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFFont; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.XMLReader; /** * Convenience/reusable methods for Excel workbook handling. */ final class ExcelUtils { private static final Logger logger = LoggerFactory.getLogger(ExcelUtils.class); private ExcelUtils() { // prevent instantiation } public static XMLReader createXmlReader() { try { SAXParserFactory saxFactory = SAXParserFactory.newInstance(); SAXParser saxParser = saxFactory.newSAXParser(); XMLReader sheetParser = saxParser.getXMLReader(); return sheetParser; } catch (Exception e) { throw new MetaModelException(e); } } /** * Opens a {@link Workbook} based on a {@link Resource}. * * @param resource * @param allowFileOptimization whether or not to allow POI to use file handles which supposedly speeds things up, * but creates issues when writing multiple times to the same file in short bursts of time. * @return */ public static Workbook readWorkbook(Resource resource, boolean allowFileOptimization) { if (!resource.isExists()) { // resource does not exist- create a blank workbook if (isXlsxFile(resource)) { return new SXSSFWorkbook(1000); } else { return new HSSFWorkbook(); } } if (allowFileOptimization && resource instanceof FileResource) { final File file = ((FileResource) resource).getFile(); try { // open read-only mode return WorkbookFactory.create(file, null, true); } catch (Exception e) { logger.error("Could not open workbook", e); throw new IllegalStateException("Could not open workbook", e); } } return resource.read(inputStream -> { try { return WorkbookFactory.create(inputStream); } catch (Exception e) { logger.error("Could not open workbook", e); throw new IllegalStateException("Could not open workbook", e); } }); } public static boolean isXlsxFile(Resource resource) { if (resource == null) { return false; } return resource.getName().toLowerCase().endsWith(".xlsx"); } /** * Initializes a workbook instance based on a {@link ExcelDataContext}. * * @return a workbook instance based on the ExcelDataContext. */ public static Workbook readWorkbookForUpdate(ExcelDataContext dataContext) { Resource resource = dataContext.getResource(); return readWorkbook(resource, false); } /** * Writes the {@link Workbook} to a {@link Resource}. The {@link Workbook} will be closed as a result of this * operation! * * @param dataContext * @param wb */ public static void writeAndCloseWorkbook(ExcelDataContext dataContext, final Workbook wb) { // first write to a temp file to avoid that workbook source is the same // as the target (will cause read+write cyclic overflow) final Resource realResource = dataContext.getResource(); final Resource tempResource = new InMemoryResource(realResource.getQualifiedPath()); tempResource.write(out -> wb.write(out)); FileHelper.safeClose(wb); FileHelper.copy(tempResource, realResource); } public static String getCellValue(Workbook wb, Cell cell) { if (cell == null) { return null; } final String result; switch (cell.getCellType()) { case BLANK: case _NONE: result = null; break; case BOOLEAN: result = Boolean.toString(cell.getBooleanCellValue()); break; case ERROR: result = getErrorResult(cell); break; case FORMULA: result = getFormulaCellValue(wb, cell); break; case NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); if (date == null) { result = null; } else { result = DateUtils.createDateFormat().format(date); } } else { result = getNumericCellValueAsString(cell.getCellStyle(), cell.getNumericCellValue()); } break; case STRING: result = cell.getRichStringCellValue().getString(); break; default: throw new IllegalStateException("Unknown cell type: " + cell.getCellType()); } logger.debug("cell ({},{}) resolved to value: {}", cell.getRowIndex(), cell.getColumnIndex(), result); return result; } private static Object getCellValueAsObject(final Workbook workbook, final Cell cell) { if (cell == null) { return null; } final Object result; switch (cell.getCellType()) { case BLANK: case _NONE: result = null; break; case BOOLEAN: result = Boolean.valueOf(cell.getBooleanCellValue()); break; case ERROR: result = getErrorResult(cell); break; case FORMULA: result = getFormulaCellValueAsObject(workbook, cell); break; case NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { result = cell.getDateCellValue(); } else { result = getDoubleAsNumber(cell.getNumericCellValue()); } break; case STRING: result = cell.getRichStringCellValue().getString(); break; default: throw new IllegalStateException("Unknown cell type: " + cell.getCellType()); } logger.debug("cell ({},{}) resolved to value: {}", cell.getRowIndex(), cell.getColumnIndex(), result); return result; } private static String getErrorResult(final Cell cell) { try { return FormulaError.forInt(cell.getErrorCellValue()).getString(); } catch (final RuntimeException e) { logger .debug("Getting error code for ({},{}) failed!: {}", cell.getRowIndex(), cell.getColumnIndex(), e .getMessage()); if (cell instanceof XSSFCell) { // hack to get error string, which is available return ((XSSFCell) cell).getErrorCellString(); } else { logger .error("Couldn't handle unexpected error scenario in cell: ({},{})", cell.getRowIndex(), cell .getColumnIndex()); throw e; } } } private static Object evaluateCell(final Workbook workbook, final Cell cell, final ColumnType expectedColumnType) { final Object value = getCellValueAsObject(workbook, cell); if (value == null || value.getClass().equals(expectedColumnType.getJavaEquivalentClass()) || (value .getClass() .equals(Integer.class) && expectedColumnType.getJavaEquivalentClass().equals(Double.class))) { return value; } else { if (logger.isWarnEnabled()) { logger .warn("Cell ({},{}) has the value '{}' of data type '{}', which doesn't match the detected " + "column's data type '{}'. This cell gets value NULL in the DataSet.", cell .getRowIndex(), cell.getColumnIndex(), value, value.getClass().getSimpleName(), expectedColumnType); } return null; } } private static String getFormulaCellValue(Workbook workbook, Cell cell) { // first try with a cached/precalculated value try { double numericCellValue = cell.getNumericCellValue(); return getNumericCellValueAsString(cell.getCellStyle(), numericCellValue); } catch (Exception e) { if (logger.isInfoEnabled()) { logger.info("Failed to fetch cached/precalculated formula value of cell: " + cell, e); } } // evaluate cell first, if possible final Cell evaluatedCell = getEvaluatedCell(workbook, cell); if (evaluatedCell != null) { return getCellValue(workbook, evaluatedCell); } else { // last resort: return the string formula return cell.getCellFormula(); } } private static Object getFormulaCellValueAsObject(final Workbook workbook, final Cell cell) { // first try with a cached/precalculated value try { return getDoubleAsNumber(cell.getNumericCellValue()); } catch (final Exception e) { if (logger.isInfoEnabled()) { logger.info("Failed to fetch cached/precalculated formula value of cell: " + cell, e); } } // evaluate cell first, if possible final Cell evaluatedCell = getEvaluatedCell(workbook, cell); if (evaluatedCell != null) { return getCellValueAsObject(workbook, evaluatedCell); } else { // last resort: return the string formula return cell.getCellFormula(); } } private static Cell getEvaluatedCell(final Workbook workbook, final Cell cell) { try { if (logger.isInfoEnabled()) { logger .info("cell ({},{}) is a formula. Attempting to evaluate: {}", cell.getRowIndex(), cell .getColumnIndex(), cell.getCellFormula()); } final FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); // calculates the formula and puts it's value back into the cell return evaluator.evaluateInCell(cell); } catch (RuntimeException e) { logger .warn("Exception occurred while evaluating formula at position ({},{}): {}", cell.getRowIndex(), cell.getColumnIndex(), e.getMessage()); } return null; } private static Number getDoubleAsNumber(final double value) { final Double doubleValue = Double.valueOf(value); if (doubleValue % 1 == 0 && doubleValue <= Integer.MAX_VALUE) { return Integer.valueOf(doubleValue.intValue()); } else { return doubleValue; } } public static Style getCellStyle(Workbook workbook, Cell cell) { if (cell == null) { return Style.NO_STYLE; } final CellStyle cellStyle = cell.getCellStyle(); final int fontIndex = cellStyle.getFontIndexAsInt(); final Font font = workbook.getFontAt(fontIndex); final StyleBuilder styleBuilder = new StyleBuilder(); // Font bold, italic, underline if (font.getBold()) { styleBuilder.bold(); } if (font.getItalic()) { styleBuilder.italic(); } if (font.getUnderline() != FontUnderline.NONE.getByteValue()) { styleBuilder.underline(); } // Font size final Font stdFont = workbook.getFontAt(0); final short fontSize = font.getFontHeightInPoints(); if (stdFont.getFontHeightInPoints() != fontSize) { styleBuilder.fontSize(fontSize, SizeUnit.PT); } // Font color final short colorIndex = font.getColor(); if (font instanceof HSSFFont) { if (colorIndex != HSSFFont.COLOR_NORMAL) { final HSSFWorkbook wb = (HSSFWorkbook) workbook; HSSFColor color = wb.getCustomPalette().getColor(colorIndex); if (color != null) { short[] triplet = color.getTriplet(); styleBuilder.foreground(triplet); } } } else if (font instanceof XSSFFont) { XSSFFont xssfFont = (XSSFFont) font; XSSFColor color = xssfFont.getXSSFColor(); if (color != null) { String argbHex = color.getARGBHex(); if (argbHex != null) { styleBuilder.foreground(argbHex.substring(2)); } } } else { throw new IllegalStateException("Unexpected font type: " + (font == null ? "null" : font.getClass()) + ")"); } // Background color if (cellStyle.getFillPattern() == FillPatternType.SOLID_FOREGROUND) { Color color = cellStyle.getFillForegroundColorColor(); if (color instanceof HSSFColor) { short[] triplet = ((HSSFColor) color).getTriplet(); if (triplet != null) { styleBuilder.background(triplet); } } else if (color instanceof XSSFColor) { String argb = ((XSSFColor) color).getARGBHex(); if (argb != null) { styleBuilder.background(argb.substring(2)); } } else { throw new IllegalStateException( "Unexpected color type: " + (color == null ? "null" : color.getClass()) + ")"); } } // alignment switch (cellStyle.getAlignment()) { case LEFT: styleBuilder.leftAligned(); break; case RIGHT: styleBuilder.rightAligned(); break; case CENTER: styleBuilder.centerAligned(); break; case JUSTIFY: styleBuilder.justifyAligned(); break; default: // we currently don't support other alignment styles break; } return styleBuilder.create(); } public static Iterator<Row> getRowIterator(Sheet sheet, ExcelConfiguration configuration, boolean jumpToDataRows) { final Iterator<Row> iterator; if (configuration.isSkipEmptyLines()) { iterator = sheet.rowIterator(); } else { iterator = new ZeroBasedRowIterator(sheet); } if (jumpToDataRows) { final int columnNameLineNumber = configuration.getColumnNameLineNumber(); if (columnNameLineNumber != ExcelConfiguration.NO_COLUMN_NAME_LINE) { // iterate past the column headers if (iterator.hasNext()) { iterator.next(); } for (int i = 1; i < columnNameLineNumber; i++) { if (iterator.hasNext()) { iterator.next(); } else { // no more rows! break; } } } } return iterator; } /** * Creates a MetaModel row based on an Excel row * * @param workbook * @param row * @param selectItems select items of the columns in the table * @return */ public static DefaultRow createRow(final Workbook workbook, final Row row, final DataSetHeader header) { final int size = header.size(); final Object[] values = new Object[size]; final Style[] styles = new Style[size]; if (row != null) { for (int i = 0; i < size; i++) { final int columnNumber = header.getSelectItem(i).getColumn().getColumnNumber(); final ColumnType columnType = header.getSelectItem(i).getColumn().getType(); final Cell cell = row.getCell(columnNumber); final Object value; if (columnType.equals(DefaultSpreadsheetReaderDelegate.DEFAULT_COLUMN_TYPE) || columnType .equals(DefaultSpreadsheetReaderDelegate.LEGACY_COLUMN_TYPE)) { value = ExcelUtils.getCellValue(workbook, cell); } else { value = ExcelUtils.evaluateCell(workbook, cell, columnType); } final Style style = ExcelUtils.getCellStyle(workbook, cell); values[i] = value; styles[i] = style; } } return new DefaultRow(header, values, styles); } public static DataSet getDataSet(Workbook workbook, Sheet sheet, Table table, ExcelConfiguration configuration) { final List<SelectItem> selectItems = table.getColumns().stream().map(SelectItem::new).collect(Collectors.toList()); final Iterator<Row> rowIterator = getRowIterator(sheet, configuration, true); if (!rowIterator.hasNext()) { // no more rows! FileHelper.safeClose(workbook); return new EmptyDataSet(selectItems); } final DataSet dataSet = new XlsDataSet(selectItems, workbook, rowIterator); return dataSet; } private static String getNumericCellValueAsString(final CellStyle cellStyle, final double cellValue) { final int formatIndex = cellStyle.getDataFormat(); String formatString = cellStyle.getDataFormatString(); if (formatString == null) { formatString = BuiltinFormats.getBuiltinFormat(formatIndex); } final DataFormatter formatter = new DataFormatter(); return formatter.formatRawCellContents(cellValue, formatIndex, formatString); } }
package net.njcull.collections; import java.util.Comparator; import java.util.Spliterator; import java.util.function.Consumer; import java.util.function.IntFunction; /** * A Spliterator designed for use by sources that traverse and split * elements maintained in an unmodifiable indexer. This is based on * the {@code Spliterators.ArraySpliterator} implementation. * <p> * The spliterator, out-of-the-box, has the following characteristics: * <ul> * <li>{@code Spliterator.ORDERED}</li> * <li>{@code Spliterator.IMMUTABLE}</li> * <li>{@code Spliterator.SIZED}</li> * <li>{@code Spliterator.SUBSIZED}</li> * </ul> * * @param <T> the type of elements returned by the spliterator * @author run2000 * @version 2/09/2017. */ final class ImmutableIndexerSpliterator<T> implements Spliterator<T> { /** * The indexer, explicitly typed as {@code IntFunction<T>}. */ private final IntFunction<T> array; private int index; // current index, modified on advance/split private final int fence; // one past last index private final int characteristics; private final Comparator<? super T> comparator; /** * Creates a spliterator covering all of the given indexer. * * @param array the array, assumed to be unmodified during use * @param size the size of the array * @param additionalCharacteristics Additional spliterator characteristics * of this spliterator's source or elements beyond {@code SIZED}, * {@code SUBSIZED}, {@code ORDERED}, and {@code IMMUTABLE} which are * always reported */ public ImmutableIndexerSpliterator(IntFunction<T> array, int size, int additionalCharacteristics) { this(array, 0, size, null, additionalCharacteristics); } /** * Creates a spliterator covering all of the given indexer, with the * given comparator. * * @param array the array, assumed to be unmodified during use * @param size the size of the array * @param comparator the comparator for the SORTED order * @param additionalCharacteristics Additional spliterator characteristics * of this spliterator's source or elements beyond {@code SIZED}, * {@code SUBSIZED}, {@code ORDERED}, and {@code IMMUTABLE} which are * always reported */ public ImmutableIndexerSpliterator(IntFunction<T> array, int size, Comparator<? super T> comparator, int additionalCharacteristics) { this(array, 0, size, comparator, additionalCharacteristics); } /** * Creates a spliterator covering the given array and range * @param array the array, assumed to be unmodified during use * @param origin the least index (inclusive) to cover * @param fence one past the greatest index to cover * @param comparator the comparator for the SORTED order * @param additionalCharacteristics Additional spliterator characteristics * of this spliterator's source or elements beyond {@code SIZED}, * {@code SUBSIZED}, {@code ORDERED}, and {@code IMMUTABLE} which are * always reported */ public ImmutableIndexerSpliterator(IntFunction<T> array, int origin, int fence, Comparator<? super T> comparator, int additionalCharacteristics) { this.array = array; this.index = origin; this.fence = fence; this.comparator = comparator; if ((comparator != null) && ((additionalCharacteristics & Spliterator.SORTED) == 0)) { throw new IllegalArgumentException("an unsorted spliterator cannot have a comparator"); } this.characteristics = additionalCharacteristics | Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.SIZED | Spliterator.SUBSIZED; } /** * If this spliterator can be partitioned, returns a Spliterator * covering elements, that will, upon return from this method, not * be covered by this Spliterator. * * <p>This Spliterator is {@link #ORDERED}, so the returned Spliterator * covers a strict prefix of the elements. * * <p>Repeated calls to {@code trySplit()} must eventually return {@code null}. * Upon non-null return: * <ul> * <li>the value reported for {@code estimateSize()} before splitting, * must, after splitting, be greater than or equal to {@code estimateSize()} * for this and the returned Spliterator; and</li> * <li>This Spliterator is {@code SUBSIZED}, so {@code estimateSize()} * for this spliterator before splitting must be equal to the sum of * {@code estimateSize()} for this and the returned Spliterator after * splitting.</li> * </ul> * * <p>This method may return {@code null} for any reason, * including emptiness, inability to split after traversal has * commenced, data structure constraints, and efficiency * considerations. * * <p> * An ideal {@code trySplit} method efficiently (without * traversal) divides its elements exactly in half, allowing * balanced parallel computation. * * @return a {@code Spliterator} covering some portion of the * elements, or {@code null} if this spliterator cannot be split */ @Override public Spliterator<T> trySplit() { int lo = index, mid = (lo + fence) >>> 1; return (lo >= mid) ? null : new ImmutableIndexerSpliterator<>(array, lo, index = mid, comparator, characteristics); } /** * Performs the given action for each remaining element, sequentially in * the current thread, until all elements have been processed or the action * throws an exception. The Spliterator is {@link #ORDERED}, so actions * are performed in encounter order. Exceptions thrown by the action * are relayed to the caller. * * @param action The action * @throws NullPointerException if the specified action is null */ @Override public void forEachRemaining(Consumer<? super T> action) { IntFunction<T> a; int i, hi; // hoist accesses and checks from loop if (action == null) { throw new NullPointerException("action is null"); } a = array; hi = fence; if ((i = index) >= 0 && i < (index = hi)) { do { action.accept(a.apply(i)); } while (++i < hi); } } /** * If a remaining element exists, performs the given action on it, * returning {@code true}; else returns {@code false}. The * Spliterator is {@link #ORDERED}, so the action is performed on the * next element in encounter order. Exceptions thrown by the * action are relayed to the caller. * * @param action The action * @return {@code false} if no remaining elements existed * upon entry to this method, else {@code true}. * @throws NullPointerException if the specified action is null */ @Override public boolean tryAdvance(Consumer<? super T> action) { if (action == null) { throw new NullPointerException("action is null"); } if ((index >= 0) && (index < fence)) { T e = array.apply(index++); action.accept(e); return true; } return false; } /** * Returns an estimate of the number of elements that would be * encountered by a {@link #forEachRemaining} traversal, or returns {@link * Long#MAX_VALUE} if infinite, unknown, or too expensive to compute. * * <p>This estimate must be an accurate count of elements that would be * encountered by a complete traversal. * * @return the estimated size, or {@code Long.MAX_VALUE} if infinite, * unknown, or too expensive to compute. */ @Override public long estimateSize() { return (long)(fence - index); } /** * Returns a set of characteristics of this Spliterator and its * elements. The result is represented as ORed values from {@link * #ORDERED}, {@link #DISTINCT}, {@link #SORTED}, {@link #SIZED}, * {@link #NONNULL}, {@link #IMMUTABLE}, {@link #SUBSIZED}. * Repeated calls to {@code characteristics()} on a given * spliterator, prior to or in-between calls to {@code trySplit}, * always return the same result. * * @return a representation of characteristics */ @Override public int characteristics() { return characteristics; } /** * If this Spliterator's source is {@link #SORTED} by a {@link Comparator}, * returns that {@code Comparator}. If the source is {@code SORTED} in * {@linkplain Comparable natural order}, returns {@code null}. Otherwise, * if the source is not {@code SORTED}, throws {@link IllegalStateException}. * * <p>This implementation always returns {@code null}. * * @return a Comparator, or {@code null} if the elements are sorted in the * natural order. * @throws IllegalStateException if the spliterator does not report * a characteristic of {@code SORTED}. */ @Override public Comparator<? super T> getComparator() { if ((characteristics & Spliterator.SORTED) == Spliterator.SORTED) { return comparator; } throw new IllegalStateException("no comparator for non-sorted spliterator"); } }
/* The MIT License (MIT) Copyright (c) 2015 Manish Kumar Singh 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 singlelegtrading; import java.util.Arrays; import java.util.Calendar; import java.util.Map; import java.util.TimeZone; import redis.clients.jedis.*; import redis.clients.jedis.exceptions.JedisException; /** * @author Manish Kumar Singh */ public class MonitorEODSignals extends Thread { private Thread t; private String threadName = "MonitoringEndOfDayEntryExitSignalsThread"; private boolean debugFlag; private JedisPool jedisPool; private String redisConfigurationKey; private IBInteraction ibInteractionClient; private MyExchangeClass myExchangeObj; private MyUtils myUtils; private String strategyName = "singlestr01"; private String openPositionsQueueKeyName = "INRSTR01OPENPOSITIONS"; private String entrySignalsQueueKeyName = "INRSTR01ENTRYSIGNALS"; private String manualInterventionSignalsQueueKeyName = "INRSTR01MANUALINTERVENTIONS"; private String eodEntryExitSignalsQueueKeyName = "INRSTR01EODENTRYEXITSIGNALS"; public String exchangeHolidayListKeyName; public class MyExistingPosition { String symbolName, symbolType; // symbolType would be "STK" or "FUT" or "OPT" String optionRightType = "NA"; boolean exists; int slotNumber, positionSideAndSize; } public class MyEntrySignalParameters { String elementName, elementStructure, signalTimeStamp, currentState, signalType; int tradeSide, elementLotSize, halflife, timeSlot, RLSignal, TSISignal; double zscore, dtsma200, onePctReturn, qscore, spread; // Structure of signal is SIGNALTYPE,SYMBOLNAME,LOTSIZE,RLSIGNAL,TSISIGNAL,HALFLIFE,CURRENTSTATE,ZSCORE, // DTSMA200,ONEPCTRETURN,QSCORE,SPREAD,STRUCTURE,TIMESTAMP,SIGNALTYPE,TIMESLOT // Index Values for Object final int EODSIGNALSYMBOLNAME_INDEX = 0; final int EODSIGNALLOTSIZE_INDEX = 1; final int EODSIGNALRLSIGNAL_INDEX = 2; final int EODSIGNALTSISIGNAL_INDEX = 3; final int EODSIGNALHALFLIFE_INDEX = 4; final int EODSIGNALCURRENTSTATE_INDEX = 5; final int EODSIGNALZSCORE_INDEX = 6; final int EODSIGNALDTSMA200_INDEX = 7; final int EODSIGNALONEPCTRETURN_INDEX = 8; final int EODSIGNALQSCORE_INDEX = 9; final int EODSIGNALSPREAD_INDEX = 10; final int EODSIGNALSTRUCTURE_INDEX = 11; final int EODSIGNALTIMESTAMP_INDEX = 12; final int EODSIGNALSIGNALTYPE_INDEX = 13; final int EODSIGNALTIMESLOT_INDEX = 14; final int EODSIGNALMAX_ELEMENTS = 15; String[] eodSignalObjectStructure; MyEntrySignalParameters(String incomingSignal) { eodSignalObjectStructure = new String[EODSIGNALMAX_ELEMENTS]; if (incomingSignal.length() > 0) { String[] tempObjectStructure = incomingSignal.split(","); for (int index = 0; (index < tempObjectStructure.length) && (index < EODSIGNALMAX_ELEMENTS); index++) { eodSignalObjectStructure[index] = tempObjectStructure[index]; } } this.elementName = eodSignalObjectStructure[EODSIGNALSYMBOLNAME_INDEX]; this.elementLotSize = Integer.parseInt(eodSignalObjectStructure[EODSIGNALLOTSIZE_INDEX]); this.RLSignal = Integer.parseInt(eodSignalObjectStructure[EODSIGNALRLSIGNAL_INDEX]); this.TSISignal = Integer.parseInt(eodSignalObjectStructure[EODSIGNALTSISIGNAL_INDEX]); this.tradeSide = this.RLSignal; this.halflife = Integer.parseInt(eodSignalObjectStructure[EODSIGNALHALFLIFE_INDEX]); this.currentState = eodSignalObjectStructure[EODSIGNALCURRENTSTATE_INDEX]; this.zscore = Double.parseDouble(eodSignalObjectStructure[EODSIGNALZSCORE_INDEX]); this.dtsma200 = Double.parseDouble(eodSignalObjectStructure[EODSIGNALDTSMA200_INDEX]); this.onePctReturn = Double.parseDouble(eodSignalObjectStructure[EODSIGNALONEPCTRETURN_INDEX]); this.qscore = Double.parseDouble(eodSignalObjectStructure[EODSIGNALQSCORE_INDEX]); this.spread = Double.parseDouble(eodSignalObjectStructure[EODSIGNALSPREAD_INDEX]); this.elementStructure = eodSignalObjectStructure[EODSIGNALSTRUCTURE_INDEX]; this.signalTimeStamp = eodSignalObjectStructure[EODSIGNALTIMESTAMP_INDEX]; this.signalType = eodSignalObjectStructure[EODSIGNALSIGNALTYPE_INDEX]; this.timeSlot = Integer.parseInt(eodSignalObjectStructure[EODSIGNALTIMESLOT_INDEX]); } } MonitorEODSignals(String name, JedisPool redisConnectionPool, String redisConfigKey, MyUtils utils, MyExchangeClass exchangeObj, IBInteraction ibInterClient, boolean debugIndicator) { threadName = name; debugFlag = debugIndicator; jedisPool = redisConnectionPool; ibInteractionClient = ibInterClient; myUtils = utils; redisConfigurationKey = redisConfigKey; myExchangeObj = exchangeObj; TimeZone.setDefault(myExchangeObj.getExchangeTimeZone()); //"singlestr01", "INRSTR01OPENPOSITIONS", "INRSTR01ENTRYSIGNALS" strategyName = myUtils.getHashMapValueFromRedis(jedisPool, redisConfigurationKey, "STRATEGYNAME", false); openPositionsQueueKeyName = myUtils.getHashMapValueFromRedis(jedisPool, redisConfigurationKey, "OPENPOSITIONSQUEUE", false); entrySignalsQueueKeyName = myUtils.getHashMapValueFromRedis(jedisPool, redisConfigurationKey, "ENTRYSIGNALSQUEUE", false); manualInterventionSignalsQueueKeyName = myUtils.getHashMapValueFromRedis(jedisPool, redisConfigurationKey, "MANUALINTERVENTIONQUEUE", false); eodEntryExitSignalsQueueKeyName = myUtils.getHashMapValueFromRedis(jedisPool, redisConfigurationKey, "EODENTRYEXITSIGNALSQUEUE", false); exchangeHolidayListKeyName = myUtils.getHashMapValueFromRedis(jedisPool, redisConfigurationKey, "EXCHANGEHOLIDAYLISTKEYNAME", false); // Debug Message System.out.println(String.format("%1$tY%1$tm%1$td:%1$tH:%1$tM:%1$tS ", Calendar.getInstance(myExchangeObj.getExchangeTimeZone())) + "Info : Monitoring End of Day Entry/Exit Signals for Strategy " + strategyName + " queue Name " + eodEntryExitSignalsQueueKeyName); } int getNearestHundredStrikePrice(double indexLevel) { int returnValue = -1; returnValue = 100 * (int) (Math.round(indexLevel + 50) / 100); return(returnValue); } boolean subscribedToGivenTimeslot(String YYYYMMDDHHMMSS) { boolean retValue = false; String[] subscribedTimeslotList = myUtils.getHashMapValueFromRedis(jedisPool, redisConfigurationKey, "SUBSCRIBEDTIMESLOTS", false).split(","); String HHMM = YYYYMMDDHHMMSS.substring(8, 10); int MM = Integer.parseInt(YYYYMMDDHHMMSS.substring(10, 12)); if ((MM >= 0) && (MM < 15)) { HHMM = HHMM + "00"; } else if ((MM >= 15) && (MM < 30)) { HHMM = HHMM + "15"; } else if ((MM >= 30) && (MM < 45)) { HHMM = HHMM + "30"; } else if (MM >= 45) { HHMM = HHMM + "45"; } // Provision to check if current HHMM falls on any of the subsribed timeslots for (int index = 0; index < subscribedTimeslotList.length; index++) { if ( HHMM.equalsIgnoreCase(subscribedTimeslotList[index]) ) { retValue = true; } } if (retValue) { System.out.println("Found Timeslot Subscription for : " + YYYYMMDDHHMMSS); } else { System.out.println("Did not Find Timeslot Subscription for : " + YYYYMMDDHHMMSS + " Existing Subscriptions : " + Arrays.toString(subscribedTimeslotList)); } return (retValue); } // End of method boolean hhmmMatchesTimeSlot(int HHMM, String entryYYYYMMDDHHMMSS) { boolean retValue = false; int timeSlotHH = HHMM / 100; int timeSlotMM = HHMM % 100; int entryHH = Integer.parseInt(entryYYYYMMDDHHMMSS.substring(8, 10)); int entryMM = Integer.parseInt(entryYYYYMMDDHHMMSS.substring(10, 12)); if (entryHH == timeSlotHH) { if ((timeSlotMM == 0) && (entryMM >= 0) && (entryMM < 15)) { retValue = true; } else if ((timeSlotMM == 15) && (entryMM >= 15) && (entryMM < 30)) { retValue = true; } else if ((timeSlotMM == 30) && (entryMM >= 30) && (entryMM < 45)) { retValue = true; } else if ((timeSlotMM == 45) && (entryMM >= 45)) { retValue = true; } } if (retValue) { // Debug Messages if any System.out.println(String.format("%1$tY%1$tm%1$td:%1$tH:%1$tM:%1$tS ", Calendar.getInstance(myExchangeObj.getExchangeTimeZone())) + " Within given timeSlot OR not : " + retValue + " timeSlot " + HHMM + " timeSlotHH " + timeSlotHH + " timeSlotMM " + timeSlotMM + " for entry timeStamp as " + entryYYYYMMDDHHMMSS); } return(retValue); } void getExistingPositionDetails(String openPositionsQueueKeyName, String signalSymbolName, MyExistingPosition currentPos, int timeSlot) { currentPos.exists = false; currentPos.positionSideAndSize = 0; currentPos.slotNumber = 0; currentPos.symbolName = ""; Jedis jedis; jedis = jedisPool.getResource(); try { // retrieve open position map from redis Map<String, String> retrieveMap = jedis.hgetAll(openPositionsQueueKeyName); // Go through all open position slots to check for existance of Current Symbol for (String keyMap : retrieveMap.keySet()) { // Do Stuff here TradingObject myTradeObject = new TradingObject(retrieveMap.get(keyMap)); String entryTimeStamp = myTradeObject.getEntryTimeStamp(); if ( (!currentPos.exists) && (myTradeObject.getTradingObjectName().matches("ON_" + signalSymbolName)) && (hhmmMatchesTimeSlot(timeSlot, entryTimeStamp)) && (myTradeObject.getOrderState().equalsIgnoreCase("entryorderfilled")) ) { // if already not found and position for existing symbol exists. // and if position belongs to timeslot //Timing slot of current position matches. Set the values of parameters... currentPos.exists = true; currentPos.positionSideAndSize = myTradeObject.getSideAndSize(); currentPos.slotNumber = Integer.parseInt(keyMap); currentPos.symbolName = myTradeObject.getTradingObjectName(); currentPos.symbolType = myTradeObject.getContractType(); if (myTradeObject.getContractType().equalsIgnoreCase("OPT")) { currentPos.optionRightType = myTradeObject.getContractOptionRightType(); } // Debug Messages if any System.out.println(String.format("%1$tY%1$tm%1$td:%1$tH:%1$tM:%1$tS ", Calendar.getInstance(myExchangeObj.getExchangeTimeZone())) + " Found Existing Position " + currentPos.symbolName + " " + currentPos.symbolType + " " + currentPos.optionRightType + " " + currentPos.exists + " " + currentPos.positionSideAndSize + " " + currentPos.slotNumber + " for timeSlot " + timeSlot); } // Debug Messages if any //System.out.println(String.format("%1$tY%1$tm%1$td:%1$tH:%1$tM:%1$tS ", Calendar.getInstance(myExchangeObj.getExchangeTimeZone())) + " Position Match Status " + signalSymbolName + " " + keyMap + " " + currentPos.exists + " " + currentPos.positionSideAndSize + " " + currentPos.slotNumber + " for timeSlot " + timeSlot); } } catch (JedisException e) { //if something wrong happen, return it back to the pool if (null != jedis) { jedisPool.returnBrokenResource(jedis); jedis = null; } } finally { //Return the Jedis instance to the pool once finished using it if (null != jedis) { jedisPool.returnResource(jedis); } } // Debug Messages if any //System.out.println(String.format("%1$tY%1$tm%1$td:%1$tH:%1$tM:%1$tS ", Calendar.getInstance(myExchangeObj.getExchangeTimeZone())) + "Existing pos Vs New Position " + signalSymbolName + " " + currentPos.exists + " " + currentPos.positionSideAndSize + " " + currentPos.slotNumber); } void sendUpdateStoplossLimitSignal(String manualInterventionSignalsQueue, int slotNumber) { // perl code to push stop loss signal Calendar timeNow = Calendar.getInstance(myExchangeObj.getExchangeTimeZone()); String stopLossSignal = String.format("%1$tY%1$tm%1$td%1$tH%1$tM%1$tS", timeNow) + ",trade," + slotNumber + ",1,0"; Jedis jedis; jedis = jedisPool.getResource(); try { // push the square off signal // jedis.lpush(manualInterventionSignalsQueue, stopLossSignal); } catch (JedisException e) { //if something wrong happen, return it back to the pool if (null != jedis) { jedisPool.returnBrokenResource(jedis); jedis = null; } } finally { //Return the Jedis instance to the pool once finished using it if (null != jedis) { jedisPool.returnResource(jedis); } } } void sendSquareOffSignal(String manualInterventionSignalsQueue, int slotNumber) { // perl code to push square off signal //$MISignalForRedis = $YYYYMMDDHHMMSS.",trade,".$positionID.",1,0"; //$redis->lpush($queueKeyName, $MISignalForRedis); Calendar timeNow = Calendar.getInstance(myExchangeObj.getExchangeTimeZone()); String squareOffSignal = String.format("%1$tY%1$tm%1$td%1$tH%1$tM%1$tS", timeNow) + ",trade," + slotNumber + ",1,0"; Jedis jedis; jedis = jedisPool.getResource(); try { // push the square off signal jedis.lpush(manualInterventionSignalsQueue, squareOffSignal); } catch (JedisException e) { //if something wrong happen, return it back to the pool if (null != jedis) { jedisPool.returnBrokenResource(jedis); jedis = null; } } finally { //Return the Jedis instance to the pool once finished using it if (null != jedis) { jedisPool.returnResource(jedis); } } } void sendEntrySignal(String entrySignalsQueue, MyEntrySignalParameters signalParam) { // R code to form entry signal //entrySignalForRedis <- paste0(timestamp,",","ON_",elementName,",",tradeSide,",",elementName,"_",elementLotSize,"," //,zscore[1],",",t_10min$dtsma_200[lastIndex],",",halflife,",",onePercentReturn,",",positionRank,",",abs(predSVM), //",1,",t_10min$spread[lastIndex]); // Check for subscription for given timeslot. Proceed only if subscribed if (!subscribedToGivenTimeslot(signalParam.signalTimeStamp)) { return; } String entrySignal = null; if ( signalParam.elementStructure.contains("_FUT") || signalParam.elementStructure.contains("_STK") ) { // this is for STK or FUT type of contract entrySignal = signalParam.signalTimeStamp + "," + "ON_" + signalParam.elementName + "," + signalParam.tradeSide + "," + signalParam.elementStructure + "_" + signalParam.elementLotSize + "," + String.format( "%.2f", signalParam.zscore ) + "," + String.format( "%.2f", signalParam.dtsma200 ) + "," + signalParam.halflife + "," + String.format( "%.2f", signalParam.onePctReturn ) + "," + signalParam.currentState + "," + String.format( "%.5f", signalParam.qscore ) + "," + "1" + "," + String.format( "%.2f", signalParam.spread ); } else if (signalParam.elementStructure.contains("_OPT")) { // this is for OPT type of contract String optionRightType = "CALL"; int optionTradeSide = 0; int optionStrikePrice = -1; if (signalParam.tradeSide > 0) { optionRightType = "CALL"; optionTradeSide = 1 * signalParam.tradeSide; } else if (signalParam.tradeSide < 0) { optionRightType = "PUT"; optionTradeSide = -1 * signalParam.tradeSide; } optionStrikePrice = getNearestHundredStrikePrice(signalParam.spread/signalParam.elementLotSize); String optionStructure = signalParam.elementName + "_" + signalParam.elementLotSize + "_" + "OPT" + "_" + optionRightType + "_" + optionStrikePrice; entrySignal = signalParam.signalTimeStamp + "," + "ON_" + signalParam.elementName + "," + optionTradeSide + "," + optionStructure + "," + String.format( "%.2f", signalParam.zscore ) + "," + String.format( "%.2f", signalParam.dtsma200 ) + "," + signalParam.halflife + "," + String.format( "%.2f", signalParam.onePctReturn ) + "," + signalParam.currentState + "," + String.format( "%.5f", signalParam.qscore ) + "," + "1" + "," + String.format( "%.2f", signalParam.spread ); } if (entrySignal != null) { Jedis jedis; jedis = jedisPool.getResource(); try { // push the entry signal jedis.lpush(entrySignalsQueue, entrySignal); } catch (JedisException e) { //if something wrong happen, return it back to the pool if (null != jedis) { jedisPool.returnBrokenResource(jedis); jedis = null; } } finally { //Return the Jedis instance to the pool once finished using it if (null != jedis) { jedisPool.returnResource(jedis); } } } } void processEntryExitSignal(MyEntrySignalParameters signalParam) { // RLSIGNAL - Reinforced Learning Signal - can take values 0, +1, -1 // 0 meaning non action necessary // +1 meaning recommended Buy if no position/Square off if existing Short position // -1 meaning recommended Sell if no position/Square off if existing Long position // TSISIGNAL - True Strength Index Signal - can take values 0, +1, -1 // 0 meaning non action necessary // +1 meaning recommended Square off if existing Short position // -1 meaning recommended Square off if existing Long position MyExistingPosition currentExistingPos = new MyExistingPosition(); getExistingPositionDetails(openPositionsQueueKeyName, signalParam.elementName, currentExistingPos, signalParam.timeSlot); // trading rule implemented : // if no position for given symbol then take position as per RLSIGNAL // else if LONG position exists for given symbol then square off if either of RLSIGNAL OR TSISIGNAL are -1 // else if SHORT position exists for given symbol then square off if either of RLSIGNAL OR TSISIGNAL are +1 // for taking position, send form the signal and send to entrySignalsQueue // for square off, send signal to manual intervention queue if ( (currentExistingPos.exists) && ( (currentExistingPos.symbolType.equalsIgnoreCase("FUT")) || (currentExistingPos.symbolType.equalsIgnoreCase("STK")) ) ) { if ( signalParam.elementStructure.contains("_FUT") || signalParam.elementStructure.contains("_STK") ) { //if LONG position exists for given symbol then square off if either of RLSIGNAL OR TSISIGNAL are -1 if (currentExistingPos.positionSideAndSize > 0) { if ( (signalParam.RLSignal < 0 ) || (signalParam.TSISignal < 0) ) { sendSquareOffSignal(manualInterventionSignalsQueueKeyName,currentExistingPos.slotNumber); // if exit is due to RLSignal, then take opposite position after exiting if ( (signalParam.RLSignal < 0 ) && (signalParam.tradeSide != 0)) { sendEntrySignal(entrySignalsQueueKeyName, signalParam); } } } //if SHORT position exists for given symbol then square off if either of RLSIGNAL OR TSISIGNAL are +1 if (currentExistingPos.positionSideAndSize < 0 ) { if ( (signalParam.RLSignal > 0 ) || (signalParam.TSISignal > 0) ) { sendSquareOffSignal(manualInterventionSignalsQueueKeyName,currentExistingPos.slotNumber); // if exit is due to RLSignal, then take do opposite position after exiting if ( (signalParam.RLSignal > 0 ) && (signalParam.tradeSide != 0)) { sendEntrySignal(entrySignalsQueueKeyName, signalParam); } } } } } else if ( (currentExistingPos.exists) && (currentExistingPos.symbolType.equalsIgnoreCase("OPT")) ) { if ( signalParam.elementStructure.contains("_OPT") ) { //if LONG position exists i.e. it is CALL OPTION then square off if either of RLSIGNAL OR TSISIGNAL are -1 if (currentExistingPos.optionRightType.equalsIgnoreCase("CALL") || currentExistingPos.optionRightType.equalsIgnoreCase("C") ) { if ( (signalParam.RLSignal < 0 ) || (signalParam.TSISignal < 0) ) { sendSquareOffSignal(manualInterventionSignalsQueueKeyName,currentExistingPos.slotNumber); // if exit is due to RLSignal, then take opposite position after exiting if ( (signalParam.RLSignal < 0 ) && (signalParam.tradeSide != 0)) { sendEntrySignal(entrySignalsQueueKeyName, signalParam); } } } //if SHORT position exists i.e. it is PUT OPTION then square off if either of RLSIGNAL OR TSISIGNAL are +1 if (currentExistingPos.optionRightType.equalsIgnoreCase("PUT") || currentExistingPos.optionRightType.equalsIgnoreCase("P") ) { if ( (signalParam.RLSignal > 0 ) || (signalParam.TSISignal > 0) ) { sendSquareOffSignal(manualInterventionSignalsQueueKeyName,currentExistingPos.slotNumber); // if exit is due to RLSignal, then take do opposite position after exiting if ( (signalParam.RLSignal > 0 ) && (signalParam.tradeSide != 0)) { sendEntrySignal(entrySignalsQueueKeyName, signalParam); } } } } } else { // since no position for given symbol so take position as per RLSIGNAL if (signalParam.tradeSide != 0) { sendEntrySignal(entrySignalsQueueKeyName, signalParam); } } } void processExitSignalForMatchingPosition(MyEntrySignalParameters signalParam) { // symbolName, timeSlot and signalType are important. Other signal fields are redundant MyExistingPosition currentExistingPos = new MyExistingPosition(); getExistingPositionDetails(openPositionsQueueKeyName, signalParam.elementName, currentExistingPos, signalParam.timeSlot); // trading rule implemented : // if matching position found then square off // for square off, send signal to manual intervention queue if (currentExistingPos.exists) { sendSquareOffSignal(manualInterventionSignalsQueueKeyName,currentExistingPos.slotNumber); // Debug Messages if any System.out.println(String.format("%1$tY%1$tm%1$td:%1$tH:%1$tM:%1$tS ", Calendar.getInstance(myExchangeObj.getExchangeTimeZone())) + " Sent Square Off Signal for " + currentExistingPos.slotNumber + " for symbol " + signalParam.elementName); } } void processExitSignalForAllPositions(MyEntrySignalParameters signalParam) { // symbolName and signalType are important. Other signal fields are redundant // trading rule implemented : // square off all positions // for square off, send signal to manual intervention queue Jedis jedis; jedis = jedisPool.getResource(); try { // retrieve open position map from redis Map<String, String> retrieveMap = jedis.hgetAll(openPositionsQueueKeyName); // Go through all open position slots to check for existance of Current Symbol for (String keyMap : retrieveMap.keySet()) { // Do Stuff here TradingObject myTradeObject = new TradingObject(retrieveMap.get(keyMap)); if ( myTradeObject.getOrderState().equalsIgnoreCase("entryorderfilled") ) { // position exists and suitable for square off sendSquareOffSignal(manualInterventionSignalsQueueKeyName,Integer.parseInt(keyMap)); // Debug Messages if any System.out.println(String.format("%1$tY%1$tm%1$td:%1$tH:%1$tM:%1$tS ", Calendar.getInstance(myExchangeObj.getExchangeTimeZone())) + " Squaring off Position " + keyMap + " for symbol " + signalParam.elementName); } // Debug Messages if any System.out.println(String.format("%1$tY%1$tm%1$td:%1$tH:%1$tM:%1$tS ", Calendar.getInstance(myExchangeObj.getExchangeTimeZone())) + " Processed Square Off for " + keyMap + " for symbol " + signalParam.elementName); } } catch (JedisException e) { //if something wrong happen, return it back to the pool if (null != jedis) { jedisPool.returnBrokenResource(jedis); jedis = null; } } finally { //Return the Jedis instance to the pool once finished using it if (null != jedis) { jedisPool.returnResource(jedis); } } } void processUpdateStoplossLimitForMatchingPosition(MyEntrySignalParameters signalParam) { // symbolName, timeSlot and signalType are important. Other signal fields are redundant MyExistingPosition currentExistingPos = new MyExistingPosition(); getExistingPositionDetails(openPositionsQueueKeyName, signalParam.elementName, currentExistingPos, signalParam.timeSlot); // trading rule implemented : // if matching position found then update stop loss limit // for square off, send signal to manual intervention queue if (currentExistingPos.exists) { sendUpdateStoplossLimitSignal(manualInterventionSignalsQueueKeyName,currentExistingPos.slotNumber); // Debug Messages if any System.out.println(String.format("%1$tY%1$tm%1$td:%1$tH:%1$tM:%1$tS ", Calendar.getInstance(myExchangeObj.getExchangeTimeZone())) + " Sent Update Stop Loss Signal for " + currentExistingPos.slotNumber + " for symbol " + signalParam.elementName); } } void processUpdateStoplossLimitForAllPositions(MyEntrySignalParameters signalParam) { // symbolName and signalType are important. Other signal fields are redundant // trading rule implemented : // square off all positions // for square off, send signal to manual intervention queue Jedis jedis; jedis = jedisPool.getResource(); try { // retrieve open position map from redis Map<String, String> retrieveMap = jedis.hgetAll(openPositionsQueueKeyName); // Go through all open position slots to check for existance of Current Symbol for (String keyMap : retrieveMap.keySet()) { // Do Stuff here TradingObject myTradeObject = new TradingObject(retrieveMap.get(keyMap)); if ( myTradeObject.getOrderState().equalsIgnoreCase("entryorderfilled") ) { // position exists and suitable for square off sendUpdateStoplossLimitSignal(manualInterventionSignalsQueueKeyName,Integer.parseInt(keyMap)); // Debug Messages if any System.out.println(String.format("%1$tY%1$tm%1$td:%1$tH:%1$tM:%1$tS ", Calendar.getInstance(myExchangeObj.getExchangeTimeZone())) + " Updating Stop Loss for " + keyMap + " for symbol " + signalParam.elementName); } // Debug Messages if any System.out.println(String.format("%1$tY%1$tm%1$td:%1$tH:%1$tM:%1$tS ", Calendar.getInstance(myExchangeObj.getExchangeTimeZone())) + " Processed Stop Loss Signal " + keyMap + " for symbol " + signalParam.elementName); } } catch (JedisException e) { //if something wrong happen, return it back to the pool if (null != jedis) { jedisPool.returnBrokenResource(jedis); jedis = null; } } finally { //Return the Jedis instance to the pool once finished using it if (null != jedis) { jedisPool.returnResource(jedis); } } } @Override public void run() { int firstEntryOrderTime = 1515; String firstEntryOrderTimeConfigValue = myUtils.getHashMapValueFromRedis(jedisPool, redisConfigurationKey, "FIRSTENTRYORDERTIME", debugFlag); if ((firstEntryOrderTimeConfigValue != null) && (firstEntryOrderTimeConfigValue.length() > 0)) { firstEntryOrderTime = Integer.parseInt(firstEntryOrderTimeConfigValue); } myUtils.waitForStartTime(firstEntryOrderTime, myExchangeObj.getExchangeTimeZone(), "first entry order time", false); String eodSignalReceived = null; int eodExitTime = 1530; String eodExitTimeConfigValue = myUtils.getHashMapValueFromRedis(jedisPool, redisConfigurationKey, "EODEXITTIME", debugFlag); if ((eodExitTimeConfigValue != null) && (eodExitTimeConfigValue.length() > 0)) { eodExitTime = Integer.parseInt(eodExitTimeConfigValue); } // Enter an infinite loop with blocking pop call to retireve messages from queue // while market is open keep monitoring eod signals queue while (myUtils.marketIsOpen(eodExitTime, myExchangeObj.getExchangeTimeZone(), false)) { eodSignalReceived = myUtils.popKeyValueFromQueueRedis(jedisPool, eodEntryExitSignalsQueueKeyName, 60, false); if (eodSignalReceived != null) { System.out.println(String.format("%1$tY%1$tm%1$td:%1$tH:%1$tM:%1$tS ", Calendar.getInstance(myExchangeObj.getExchangeTimeZone())) + "Info : Received EOD Signal as : " + eodSignalReceived); MyEntrySignalParameters signalParam = new MyEntrySignalParameters(eodSignalReceived); // Structure of signal is SYMBOLNAME,LOTSIZE,RLSIGNAL,TSISIGNAL,HALFLIFE,CURRENTSTATE,ZSCORE,DTSMA200,ONEPCTRETURN,QSCORE,SPREAD,,STRUCTURE,TIMESTAMP,SIGNALTYPE,TIMESLOT System.out.println("timeSlot Subscription Status : " + subscribedToGivenTimeslot(signalParam.signalTimeStamp)); if ( signalParam.signalType.equalsIgnoreCase("exitentry") || signalParam.signalType.equalsIgnoreCase("exitandentry") || signalParam.signalType.equalsIgnoreCase("entryexit") || signalParam.signalType.equalsIgnoreCase("entryandexit") ) { processEntryExitSignal(signalParam); } else if (signalParam.signalType.equalsIgnoreCase("exitonlymatchingtimeslot")) { processExitSignalForMatchingPosition(signalParam); } else if (signalParam.signalType.equalsIgnoreCase("exitalltimeslots")) { processExitSignalForAllPositions(signalParam); } else if (signalParam.signalType.equalsIgnoreCase("updatestoplosslimitmatchingtimeslot")) { processUpdateStoplossLimitForMatchingPosition(signalParam); } else if (signalParam.signalType.equalsIgnoreCase("updatestoplosslimitalltimeslots")) { processUpdateStoplossLimitForAllPositions(signalParam); } //write code to update take profit for all as well as matching timeslots } } // Day Over. Now Exiting. } @Override public void start() { this.setName(threadName); if (t == null) { t = new Thread(this, threadName); t.start(); } } }
package org.traccar.protocol; import org.junit.Test; import org.traccar.ProtocolTest; public class Gl200TextProtocolDecoderTest extends ProtocolTest { @Test public void testDecode() throws Exception { Gl200TextProtocolDecoder decoder = new Gl200TextProtocolDecoder(new Gl200Protocol()); verifyAttributes(decoder, buffer( "+RESP:GTINF,280500,A1000043D20139,GL300VC,41,,31,0,0,,,3.87,0,1,1,,,20170802150751,70,,48.0,,,20170802112145,03AC$")); verifyAttributes(decoder, buffer( "+RESP:GTINF,2D0300,A1000043D20139,1G1JC5444R7252367,,11,,31,0,1,12986,,4.16,0,2,,,20170802145640,,,,,,+0000,0,20170802145643,CD5A$")); verifyPosition(decoder, buffer( "+RESP:GTMPN,450102,865084030001323,gb100,0,1.6,0,-93.1,121.393023,31.164105,20170619103113,0460,0000,1806,2142,00,20170619103143,0512$")); verifyPosition(decoder, buffer( "+RESP:GTTRI,862370030005908,1,0,99,1,0.0,354,18.5,18.821100,-34.084002,20170607152024,0655,0001,00DD,1CAE,00,0103010100,20170607172115,3E7D$")); verifyPositions(decoder, buffer( "+RESP:GTERI,060800,861074023677175,,00000002,12351,10,1,1,0.0,0,2862.4,-78.467273,-0.164998,20170529181717,,,,,,0.0,00259:11:50,,,0,210104,2,1,28E17436060000E2,1,015F,0,20170529181723,2824$")); verifyPosition(decoder, buffer( "+RESP:GTSWG,110100,358688000000158,,1,0,2.1,0,27.1,121.390717,31.164424,20110901073917,0460,0000,1878,0873,,20110901154653,0015$")); verifyPosition(decoder, buffer( "+RESP:GTTMP,110100,358688000000158,,2,60,1,1,4.3,92,70.0,121.354335,31.222073,20110214013254,0460,0000,18d8,6141,00,80,20110214093254,000F$")); verifyPosition(decoder, buffer( "+RESP:GTSTT,110100,358688000000158,,41,0,4.3,92,70.0,121.354335,31.222073,20110214013254,0460,0000,18d8,6141,,20110214093254,0022$")); verifyPosition(decoder, buffer( "+RESP:GTBPL,110100,358688000000158,,3.53,0,4.3,92,70.0,121.354335,31.222073,20110214013254,0460,0000,18d8,6141,,20110214093254,001F$")); verifyNotNull(decoder, buffer( "+BUFF:GTIGL,060228,862894020180553,,,00,1,1,3.4,199,409.6,-63.174466,-17.739317,20170407121823,0000,0000,0000,0000,00,15989.5,20170407081824,9606$")); verifyNotNull(decoder, buffer( "+RESP:GTFRI,060228,862894020180553,,14827,10,1,1,3.4,199,409.6,-63.174466,-17.739317,20170407121823,0000,0000,0000,0000,00,15989.5,01070:43:13,13,180,0,220101,,,,20170407081824,9607$")); verifyPositions(decoder, buffer( "+RESP:GTERI,060502,861074023376992,,00000002,27239,10,1,1,0.2,312,183.3,-79.320820,-2.499110,20170401212005,0740,0000,EE4E,C98F,00,0.0,02114:36:35,,,90,220504,2,0,0,20170401212007,9E3D$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,060502,861074023689626,,25202,10,1,1,0.0,0,2744.1,-78.261047,0.023452,20170401211940,,,,,,0.0,00079:19:15,,,51,110000,,,,20170401212003,4DA7$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,060100,135790246811220,,,00,1,1,4.3,92,70.0,121.354335,31.222073,20090214013254,0460,0000,18d8,6141,00,2000.0,12345:12:34,,,80,210100,,,,20090214093254,11F0$")); verifyPositions(decoder, buffer( "+RESP:GTERI,06020B,862170010196747,,00000000,,10,1,2,1.8,0,-2.5,117.198440,31.845219,20120802061037,0460,0000,5663,0358,00,0.0,,,,0,410000,20120802061040,0012$")); verifyPositions(decoder, buffer( "+RESP:GTERI,060502,861074023692562,,00000002,14197,10,1,1,0.2,220,491.8,-79.064212,-2.159754,20170401212007,0740,0000,EE49,CE25,00,0.0,01509:10:58,,,87,220104,2,0,0,20170401212010,D14D$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,210102,354524044925825,,1,1,1,29,2.8,0,133.7,-90.203063,32.265473,20170318005208,,,,,10800,4,20170318005208,0002$")); verifyPositions(decoder, false, buffer( "+RESP:GTFRI,210102,354524044925825,,1,1,1,,,,,,,,310,410,51bc,ca1dae6,10800,1,20170318214333,0002$")); verifyAttributes(decoder, buffer( "+RESP:GTGSM,400201,862365030025161,STR,0234,0015,003a,62a2,16,,0234,0015,003a,56a2,14,,0234,0015,003a,062a,13,,0234,0015,003a,32d9,11,,0234,0015,003a,56a0,11,,,,,,,,0234,0015,003a,7489,17,,20170219200048,0033$")); verifyAttributes(decoder, buffer( "+RESP:GTGSM,400201,862365030025161,STR,0234,0015,003a,56a2,18,,0234,0015,003a,77bc,14,,0234,0015,003a,32d9,12,,0234,0015,003a,062a,12,,0234,0015,003a,62a2,11,,0234,0015,003a,56a0,10,,0234,0015,003a,7489,15,,20170219080049,0030$")); verifyAttributes(decoder, buffer( "+RESP:GTGSM,400201,862365030034940,STR,0234,0030,0870,2469,19,,0234,0030,0870,35ee,18,,0234,0030,0870,16ac,12,,0234,0030,0870,16b2,11,,0234,0030,0870,360f,6,,0234,0030,0870,165d,6,,0234,0030,0870,35ef,17,,20170215220049,008D$")); verifyPosition(decoder, buffer( "+RESP:GTSTR,400201,862365030034940,GL500,0,0,2,21.1,86,0,1.6,0,5.8,0.622831,51.582688,20170215090422,0234,0030,0870,35EF,,,,20170215220049,008C$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,2C0402,867162020000816,,0,0,1,2,0.3,337,245.7,-82.373387,34.634011,20170215003054,,,,,,63,20170215003241,3EAB$")); verifyNotNull(decoder, buffer( "+RESP:GTWIF,210102,354524044608058,,4,c413e200ff14,-39,,,,c413e2010e55,-39,,,,c8d3ff04a837,-43,,,,42490f997c6d,-57,,,,,,,,100,20170201020055,0001$")); verifyNotNull(decoder, buffer( "+RESP:GTWIF,210102,354524044484948,,1,08626693fb98,-36,,,,,,,,97,20170119071300,05E3$")); verifyAttributes(decoder, buffer( "+RESP:GTINF,210102,A100004D9EF2AE,,41,,8,99,0,17.7,21,3.58,0,1,1,0,0,20161216135038,4,,,,,20161216135038,00AB$")); verifyAttributes(decoder, buffer( "+RESP:GTSTR,400201,862365030034957,GL500,0,0,2,23.1,5,2,0.2,0,36.0,0.623089,51.582744,20161129174625,0234,0015,03C3,3550,,,,20161129174625,0026$")); verifyNotNull(decoder, buffer( "+RESP:GTSTR,400201,862365030034957,GL500,0,1,2,21.8,100,0,,,,,,,0234,0015,03C3,3550,,,,20161129174009,0023$")); verifyAttributes(decoder, buffer( "+RESP:GTINF,210102,A10000499AEF9B,,41,,0,0,0,15.0,9,3.87,0,1,1,0,0,20161101140211,72,,,,,20161101140211,00A3$")); verifyAttributes(decoder, buffer( "+RESP:GTNMR,210102,A10000499AEF9B,,0,0,1,9,0.0,0,288.0,-76.902364,39.578828,20161101134145,,,,,00,73,20161101134145,009F$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,210102,A10000499AEF9B,,0,1,1,9,0.5,0,288.0,-76.902364,39.578828,20161101134124,,,,,00,73,20161101134123,009D$")); verifyAttributes(decoder, buffer( "+RESP:GTRTL,210102,A10000499AEF9B,,0,0,1,10,0.2,0,305.4,-76.902274,39.578517,20161101155001,,,,,00,73,20161101155001,00A6$")); verifyAttributes(decoder, buffer( "+RESP:GTINF,110100,358688000000158,,41,898600810906F8048812,18,99,0,33.23,1,4.19,1,1,1,0,0,20110714104934,100,,,,,20110714104934,0014$")); verifyAttributes(decoder, buffer( "+RESP:GTINF,080100,135790246811220,,16,898600810906F8048812,16,0,1,11870,,4.1,0,0,0,,20090214013254,,12340,,00,00,+0800,0,20090214093254,11F0$")); verifyAttributes(decoder, buffer( "+RESP:GTINF,040100,135790246811220,,16,898600810906F8048812,16,0,1,,0,4.4,0,0,0,0,20090214013254,13000,00,00,+0800,0,20090214093254,11F0$")); verifyAttributes(decoder, buffer( "+RESP:GTINF,060100,135790246811220,,16,898600810906F8048812,16,0,1,12000,,4.4,0,0,0,0,20090214013254,0,1300,2000,00,00,+0800,0,20090214093254,11F0$")); verifyAttributes(decoder, buffer( "+RESP:GTINF,1A0800,860599000773978,GL300,41,89701016426133851978,17,0,1,26.6,,3.90,1,1,0,0,0,20161003184043,69,1,44,,,20161004040811,022C$")); verifyAttributes(decoder, buffer( "+BUFF:GTINF,1A0800,860599000773978,GL300,41,89701016426133851978,23,0,1,204.7,,3.84,1,1,0,0,0,20161006072548,62,1,38,,,20161006082343,0C98$")); verifyPosition(decoder, buffer( "+RESP:GTFRI,360100,864251020141408,3VWGW6AJ0FM237324,gv500,,10,1,1,0.0,0,2258.4,-99.256948,19.555800,20160929214743,0334,0020,0084,65AC,00,0.0,,,,100,410000,0,nan,,20160929214743,13BA$")); verifyPosition(decoder, buffer( "+RESP:GTOBD,360201,864251020186064,4T1BE46KX7U018210,,0,19FFFF,4T1BE46KX7U018210,1,14283,983901C0,799,36,18,,33792,0,0,0,,,38,,6,53557,0,0.0,0,219.5,-76.661456,39.832588,20160507132153,20160507132154,0230$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,360201,864251020186064,1G1JC5444R7252367,,12802,10,1,0,0.0,0,219.5,-76.661456,39.832588,20160507132235,,,,,,20460.9,00080:03:37,,,100,210000,791,,56,20160507132239,0233$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,1F0101,135790246811220,1G1JC5444R7252367,,,00,2,1,4.3,92,70.0,121.354335,31.222073,20090214013254,0460,0000,18d8,6141,00,0,4.3,92,70.0,121.354335,31.222073,20090101000000,0460,0000,18d8,6141,00,2000.0,12345:12:34,,,80,210100,,,50,20090214093254,11F0$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,1F0101,135790246811220,1G1JC5444R7252367,,,00,1,1,4.3,92,70.0,121.354335,31.222073,20090214013254,0460,0000,18d8,6141,00,2000.0,12345:12:34,,92,80,210100,,,50,20090214093254,11F0$")); verifyPosition(decoder, buffer( "+RESP:GTSTT,060228,862894020178276,,21,0,0.0,0,411.3,-63.169745,-17.776330,20160319132220,0736,0003,6AD4,5BAA,00,20160319092223,1FBD$")); verifyPosition(decoder, buffer( "+RESP:GTNMR,210102,A10000458356CE,,0,1,1,9,0.0,8,190.7,-85.765865,42.894837,20160316123202,,,,,60,30,20160316123202,0137$")); verifyPosition(decoder, buffer( "+RESP:GTIDA,060228,862894020178276,,,01C68011010000C7,1,1,0,0.0,0,413.0,-63.169675,-17.776349,20160317222129,0736,0003,6AD4,32CF,00,34.9,,,,,20160317182130,1626$")); verifyPosition(decoder, buffer( "+RESP:GTIGN,060228,862894020180553,,9860,0,0.2,189,420.0,-63.158195,-17.800608,20160309022951,0736,0003,6AD4,3471,00,,881.2,20160308222956,129A$")); verifyPosition(decoder, buffer( "+BUFF:GTIGF,060228,862894020180553,,1958,0,0.0,240,390.3,-63.089213,-17.764712,20160309122854,0736,0003,6AB8,5A23,00,,936.8,20160309082858,1368$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,060228,862894020180553,,,10,1,1,20.0,147,329.7,-62.899703,-17.720434,20160309113548,0736,0003,6AAE,3381,00,913.3,,,,0,220101,,,,20160309073554,132B$")); verifyPositions(decoder, buffer( "+BUFF:GTFRI,060402,862894021808798,,,10,1,1,0.0,349,394.3,-63.287717,-17.662410,20160116234031,0736,0003,6ABA,8305,00,3326.8,,,,94,220100,,,,20160116194035,4D83")); verifyPositions(decoder, buffer( "+RESP:GTFRI,2C0204,867162020003125,GL300W,0,0,2,1,1.7,205,2867.0,-78.481127,-0.206828,20160215210433,0740,0000,7596,5891C,0.0,1,1.7,205,2867.0,-78.481127,-0.206828,20160215210503,0740,0000,7596,5891C,0.0,88,20160215210506,1E78$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,060228,862894020178276,,15153,10,1,1,0.0,0,431.7,-63.169571,-17.776235,20160210153458,0736,0003,6AD4,80EF,00,34.9,00117:31:26,13442,15163,0,210101,,,,20160210113503,38EE$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,110100,A5868800000015,,0,0,1,1,4.3,92,70.0,121.354335,31.222073,20110214013254,0460,0000,18d8,6141,00,80,20110214013254,000C")); verifyNotNull(decoder, buffer( "+RESP:GTFRI,210102,A10000458356CE,,0,1,1,15,1.4,0,190.6,-85.765763,42.894896,20160208164505,4126,210,0,18673,00,92,20160208164507,00A6")); verifyPositions(decoder, buffer( "+BUFF:GTFRI,060402,862894021808798,,,10,1,1,0.0,349,394.3,-63.287717,-17.662410,20160116234031,0736,0003,6ABA,8305,00,3326.8,,,,94,220100,,,,20160116194035,4D83")); verifyPosition(decoder, buffer( "+RESP:GTIDA,06020A,862170013895931,,,D2C4FBC5,1,1,1,0.8,0,22.2,117.198630,31.845229,20120802121626,0460,0000,5663,2BB9,00,0.0,,,,,20120802121627,008E$")); verifyAttributes(decoder, buffer( "+RESP:GTINF,1F0101,135790246811220,1G1JC5444R7252367,,16,898600810906F8048812,16,0,1,12000,,4.2,0,0,,,20090214013254,,,,,,+0800,0,20090214093254,11F0$")); verifyPositions(decoder, false, buffer( "+RESP:GTFRI,120113,555564055560555,,1,1,1,,,,,,,,0282,0380,f080,cabf,6900,79,20140824165629,0001$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,0F0106,862193020451183,,,10,1,1,0.0,163,,-57.513617,-25.368191,20150918182145,,,,,,21235.0,,,,0,210100,,,,20150918182149,00B8$")); verifyPosition(decoder, buffer( "+RESP:GTOBD,1F0109,864251020135483,,gv500,0,78FFFF,,1,12613,,,,,,,,,,,,,,1286,0,0.0,0,17.1,3.379630,6.529701,20150813074639,0621,0030,51C0,A2B3,00,0.0,20150813074641,A7E6$")); verifyPosition(decoder, buffer( "+RESP:GTOBD,1F0109,864251020135483,4T1BE46KX7U018210,gv500,0,78FFFF,4T1BE46KX7U018210,1,13411,981B81C0,787,3,43,,921,463,1,10,0300030103030304001200310351035203530354,20,55,,1286,0,6.5,74,21.6,3.379710,6.529714,20150813074824,0621,0030,51C0,A2B3,00,0.0,20150813074828,A7E9$")); verifyPosition(decoder, buffer( "+RESP:GTSTT,1A0401,860599000508846,,41,0,0.0,84,107.5,-76.657998,39.497203,20150623160622,0310,0260,B435,3B81,,20150623160622,0F54$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,1A0401,860599000508846,,0,0,1,1,134.8,154,278.7,-76.671089,39.778885,20150623154301,0310,0260,043F,7761,,99,20150623154314,0F24$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,1A0200,860599000165464,CRI001,0,0,1,2,,41,,-71.153137,42.301634,20150328020301,,,,,280.3,55,20150327220351,320C")); verifyPositions(decoder, buffer( "+RESP:GTFRI,02010D,867844001675407,,0,0,1,2,0.0,0,28.9,8.591011,56.476397,20140915213209,0238,0001,03CB,2871,,97,20140915213459,009A")); verifyNull(decoder, buffer( "+RESP:GTINF,359464030073766,8938003990320469804f,18,99,100,1,0,+2.00,0,20131018084015,00EE,0103090402")); verifyPositions(decoder, buffer( "+RESP:GTFRI,04040C,359231038939904,,,10,1,2,0.0,117,346.0,8.924243,50.798077,20130618122040,0262,0002,0299,109C,00,0.0,,,,,,,,,20130618122045,00F6")); verifyPosition(decoder, buffer( "+RESP:GTSTT,04040C,359231038939904,,42,0,0.0,117,346.0,8.924243,50.798077,20130618125152,0262,0002,0299,109C,00,20130618125154,017A")); verifyPositions(decoder, buffer( "+RESP:GTFRI,020102,000035988863964,,0,0,1,1,4.3,92,70.0,121.354335,31.222073,20090214013254,0460,0000,18d8,6141,00,,20090214093254,11F0")); verifyPositions(decoder, buffer( "+RESP:GTFRI,020102,135790246811220,,0,0,1,1,4.3,92,70.0,121.354335,31.222073,20090214013254,0460,0000,18d8,6141,00,,20090214093254,11F0")); verifyPositions(decoder, buffer( "+RESP:GTFRI,020102,135790246811220,,0,0,2,1,4.3,92,70.0,121.354335,31.222073,20090214013254,0460,0000,18d8,6141,00,0,4.3,92,70.0,121.354335,31.222073,20090101000000,0460,0000,18d8,6141,00,,20090214093254,11F0")); verifyPosition(decoder, buffer( "+RESP:GTDOG,020102,135790246811220,,0,0,1,1,4.3,92,70.0,121.354335,31.222073,20090214013254,0460,0000,18d8,6141,00,2000.0,20090214093254,11F0")); verifyPosition(decoder, buffer( "+RESP:GTLBC,020102,135790246811220,,+8613800000000,1,4.3,92,70.0,121.354335,31.222073,20090214013254,0460,0000,18d8,6141,00,,20090214093254,11F0")); verifyPosition(decoder, buffer( "+RESP:GTGCR,020102,135790246811220,,3,50,180,2,0.4,296,-5.4,121.391055,31.164473,20100714104934,0460,0000,1878,0873,00,,20100714104934,000C")); verifyPosition(decoder, buffer( "+RESP:GTFRI,07000D,868487001005941,,0,0,1,1,0.0,0,46.3,-77.039627,38.907573,20120731175232,0310,0260,B44B,EBC9,0015e96913a7,-58,,100,20120731175244,0114")); verifyPosition(decoder, buffer( "+RESP:GTHBM,0F0100,135790246811220,,,10,1,1,4.3,92,70.0,121.354335,31.222073,20090214013254,0460,0000,18d8,6141,00,2000.0,20090214093254,11F0$")); verifyPosition(decoder, buffer( "+RESP:GTHBM,0F0100,135790246811220,,,11,1,1,24.3,92,70.0,121.354335,31.222073,20090214013254,0460,0000,18d8,6141,00,2000.0,20090214093254,11F0$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,02010C,867844001274144,,0,0,1,1,18.0,233,118.1,7.615551,51.515600,20140106130516,0262,0007,79E6,B956,,72,20140106140524,09CE$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,02010C,867844001274649,,0,0,1,1,0.0,0,122.5,7.684216,51.524512,20140106233722,0262,0007,79EE,1D22,,93,20140107003805,03C4$")); verifyPositions(decoder, buffer( "+BUFF:GTFRI,210101,863286020016706,,,10,1,1,,,,49.903915,40.391669,20140818105815,,,,,,,,,,,210100,,,,,000C$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,240100,135790246811220,,,10,1,1,4.3,92,70.0,121.354335,31.222073,20090214013254,0460,0000,18d8,6141,00,2000.0,12345:12:34,,80,,,,,,20090214093254,11F0$")); verifyPositions(decoder, buffer( "+RESP:GTFRI,240100,135790246811220,,,10,2,1,4.3,92,70.0,121.354335,31.222073,20090214013254,0460,0000,18d8,6141,00,0,4.3,92,70.0,121.354335,31.222073,20090101000000,0460,0000,18d8,6141,00,2000.0,12345:12:34,,,80,,,,,20090214093254,11F0$")); verifyNotNull(decoder, buffer( "+RESP:GTSTT,280100,A1000043D20139,,42,0,0.1,321,228.6,-76.660884,39.832552,20150615120628,0310,0484,00600019,0A52,,20150615085741,0320$")); verifyNotNull(decoder, buffer( "+RESP:GTRTL,280100,A1000043D20139,,0,0,1,1,0.1,321,239.1,-76.661047,39.832501,20150615114455,0310,0484,00600019,0A52,,87,20150615074456,031E$")); verifyAttributes(decoder, buffer( "+BUFF:GTBPL,1A0800,860599000773978,GL300,3.55,0,0.0,0,257.1,60.565437,56.818277,20161006070553,,,,,204.7,20161006071028,0C75$")); verifyAttributes(decoder, buffer( "+RESP:GTTEM,1A0102,860599000000448,,3,33,0,5.8,0,33.4,117.201191,31.832502,20130109061410,0460,0000,5678,2079,,20130109061517,0091$")); verifyAttributes(decoder, buffer( "+RESP:GTJDR,0A0102,135790246811220,,0,4.3,92,70.0,121.354335,31.222073,20090214013254,0460,0000,18d8,6141,00,20090214093254,11F0$")); verifyAttributes(decoder, buffer( "+RESP:GTJDS,0A0102,135790246811220,,2,0,4.3,92,70.0,121.354335,31.222073,20090214013254,0460,0000,18d8,6141,00,20090214093254,11F0$")); verifyAttributes(decoder, buffer( "+RESP:GTSOS,020102,135790246811220,,0,0,1,1,4.3,92,70.0,121.354335,31.222073,20090214013254,0460,0000,18d8,6141,00,,20090214093254,11F0$")); verifyAttributes(decoder, buffer( "+RESP:GTVER,1A0800,860599000773978,GL300,GL300,0A03,0103,20161007041531,10F8$")); verifyNull(decoder, buffer( "+ACK:GTHBD,1A0401,135790246811220,,20100214093254,11F0")); verifyAttributes(decoder, buffer( "+ACK:GTRTO,1A0800,860599000773978,GL300,VER,FFFF,20161006053520,0C19")); verifyAttributes(decoder, buffer( "+ACK:GTJDC,0A0102,135790246811220,,0016,20090214093254,11F0")); verifyAttributes(decoder, buffer( "+ACK:GTGEO,1A0102,135790246811220,,0,0008,20100310172830,11F0")); } }
/* * 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.flink.runtime.operators.testutils; import org.apache.flink.api.common.ExecutionConfig; import org.apache.flink.api.common.JobID; import org.apache.flink.api.common.TaskInfo; import org.apache.flink.api.common.operators.MailboxExecutor; import org.apache.flink.configuration.Configuration; import org.apache.flink.core.fs.Path; import org.apache.flink.runtime.accumulators.AccumulatorRegistry; import org.apache.flink.runtime.broadcast.BroadcastVariableManager; import org.apache.flink.runtime.checkpoint.CheckpointException; import org.apache.flink.runtime.checkpoint.CheckpointMetrics; import org.apache.flink.runtime.checkpoint.TaskStateSnapshot; import org.apache.flink.runtime.execution.Environment; import org.apache.flink.runtime.executiongraph.ExecutionAttemptID; import org.apache.flink.runtime.externalresource.ExternalResourceInfoProvider; import org.apache.flink.runtime.io.disk.iomanager.IOManager; import org.apache.flink.runtime.io.network.TaskEventDispatcher; import org.apache.flink.runtime.io.network.api.writer.RecordCollectingResultPartitionWriter; import org.apache.flink.runtime.io.network.api.writer.ResultPartitionWriter; import org.apache.flink.runtime.io.network.partition.consumer.IndexedInputGate; import org.apache.flink.runtime.io.network.partition.consumer.IteratorWrappingTestSingleInputGate; import org.apache.flink.runtime.jobgraph.JobVertexID; import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider; import org.apache.flink.runtime.jobgraph.tasks.TaskOperatorEventGateway; import org.apache.flink.runtime.mailbox.SyncMailboxExecutor; import org.apache.flink.runtime.memory.MemoryManager; import org.apache.flink.runtime.metrics.groups.TaskMetricGroup; import org.apache.flink.runtime.query.KvStateRegistry; import org.apache.flink.runtime.query.TaskKvStateRegistry; import org.apache.flink.runtime.state.CheckpointStorageAccess; import org.apache.flink.runtime.state.TaskStateManager; import org.apache.flink.runtime.taskexecutor.GlobalAggregateManager; import org.apache.flink.runtime.taskmanager.NoOpTaskOperatorEventGateway; import org.apache.flink.runtime.taskmanager.TaskManagerRuntimeInfo; import org.apache.flink.types.Record; import org.apache.flink.util.MutableObjectIterator; import org.apache.flink.util.Preconditions; import org.apache.flink.util.UserCodeClassLoader; import org.apache.flink.util.concurrent.Executors; import com.sun.istack.NotNull; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import static org.apache.flink.util.Preconditions.checkArgument; import static org.apache.flink.util.Preconditions.checkNotNull; import static org.apache.flink.util.Preconditions.checkState; import static org.junit.Assert.fail; /** IMPORTANT! Remember to close environment after usage! */ public class MockEnvironment implements Environment, AutoCloseable { private final TaskInfo taskInfo; private final ExecutionConfig executionConfig; private final MemoryManager memManager; private final IOManager ioManager; private final TaskStateManager taskStateManager; private final GlobalAggregateManager aggregateManager; private final InputSplitProvider inputSplitProvider; private final Configuration jobConfiguration; private final Configuration taskConfiguration; private final List<IndexedInputGate> inputs; private final List<ResultPartitionWriter> outputs; private final JobID jobID; private final JobVertexID jobVertexID; private final ExecutionAttemptID executionAttemptID; private final TaskManagerRuntimeInfo taskManagerRuntimeInfo; private final BroadcastVariableManager bcVarManager = new BroadcastVariableManager(); private final AccumulatorRegistry accumulatorRegistry; private final TaskKvStateRegistry taskKvStateRegistry; private final KvStateRegistry kvStateRegistry; private final int bufferSize; private final UserCodeClassLoader userCodeClassLoader; private final TaskEventDispatcher taskEventDispatcher = new TaskEventDispatcher(); private Optional<Class<? extends Throwable>> expectedExternalFailureCause = Optional.empty(); private Optional<? extends Throwable> actualExternalFailureCause = Optional.empty(); private final TaskMetricGroup taskMetricGroup; private final ExternalResourceInfoProvider externalResourceInfoProvider; private MailboxExecutor mainMailboxExecutor; private ExecutorService asyncOperationsThreadPool; private CheckpointStorageAccess checkpointStorageAccess; public static MockEnvironmentBuilder builder() { return new MockEnvironmentBuilder(); } protected MockEnvironment( JobID jobID, JobVertexID jobVertexID, String taskName, MockInputSplitProvider inputSplitProvider, int bufferSize, Configuration taskConfiguration, ExecutionConfig executionConfig, IOManager ioManager, TaskStateManager taskStateManager, GlobalAggregateManager aggregateManager, int maxParallelism, int parallelism, int subtaskIndex, UserCodeClassLoader userCodeClassLoader, TaskMetricGroup taskMetricGroup, TaskManagerRuntimeInfo taskManagerRuntimeInfo, MemoryManager memManager, ExternalResourceInfoProvider externalResourceInfoProvider) { this.jobID = jobID; this.jobVertexID = jobVertexID; this.taskInfo = new TaskInfo(taskName, maxParallelism, subtaskIndex, parallelism, 0); this.jobConfiguration = new Configuration(); this.taskConfiguration = taskConfiguration; this.inputs = new LinkedList<>(); this.outputs = new LinkedList<ResultPartitionWriter>(); this.executionAttemptID = new ExecutionAttemptID(); this.memManager = memManager; this.ioManager = ioManager; this.taskManagerRuntimeInfo = taskManagerRuntimeInfo; this.executionConfig = executionConfig; this.inputSplitProvider = inputSplitProvider; this.bufferSize = bufferSize; this.accumulatorRegistry = new AccumulatorRegistry(jobID, getExecutionId()); this.kvStateRegistry = new KvStateRegistry(); this.taskKvStateRegistry = kvStateRegistry.createTaskRegistry(jobID, getJobVertexId()); this.userCodeClassLoader = Preconditions.checkNotNull(userCodeClassLoader); this.taskStateManager = Preconditions.checkNotNull(taskStateManager); this.aggregateManager = Preconditions.checkNotNull(aggregateManager); this.taskMetricGroup = taskMetricGroup; this.externalResourceInfoProvider = Preconditions.checkNotNull(externalResourceInfoProvider); this.mainMailboxExecutor = new SyncMailboxExecutor(); this.asyncOperationsThreadPool = Executors.newDirectExecutorService(); } public IteratorWrappingTestSingleInputGate<Record> addInput( MutableObjectIterator<Record> inputIterator) { try { final IteratorWrappingTestSingleInputGate<Record> reader = new IteratorWrappingTestSingleInputGate<Record>( bufferSize, inputs.size(), inputIterator, Record.class); inputs.add(reader.getInputGate()); return reader; } catch (Throwable t) { throw new RuntimeException("Error setting up mock readers: " + t.getMessage(), t); } } public void addInputs(List<IndexedInputGate> gates) { inputs.addAll(gates); } public void addOutput(final List<Record> outputList) { try { outputs.add(new RecordCollectingResultPartitionWriter(outputList)); } catch (Throwable t) { t.printStackTrace(); fail(t.getMessage()); } } public void addOutputs(List<ResultPartitionWriter> writers) { outputs.addAll(writers); } @Override public Configuration getTaskConfiguration() { return this.taskConfiguration; } @Override public MemoryManager getMemoryManager() { return this.memManager; } @Override public IOManager getIOManager() { return this.ioManager; } @Override public ExecutionConfig getExecutionConfig() { return this.executionConfig; } @Override public JobID getJobID() { return this.jobID; } @Override public Configuration getJobConfiguration() { return this.jobConfiguration; } @Override public TaskManagerRuntimeInfo getTaskManagerInfo() { return this.taskManagerRuntimeInfo; } @Override public TaskMetricGroup getMetricGroup() { return taskMetricGroup; } @Override public InputSplitProvider getInputSplitProvider() { return this.inputSplitProvider; } @Override public TaskInfo getTaskInfo() { return taskInfo; } public KvStateRegistry getKvStateRegistry() { return kvStateRegistry; } @Override public UserCodeClassLoader getUserCodeClassLoader() { return userCodeClassLoader; } @Override public Map<String, Future<Path>> getDistributedCacheEntries() { return Collections.emptyMap(); } @Override public ResultPartitionWriter getWriter(int index) { return outputs.get(index); } @Override public ResultPartitionWriter[] getAllWriters() { return outputs.toArray(new ResultPartitionWriter[outputs.size()]); } @Override public IndexedInputGate getInputGate(int index) { return inputs.get(index); } @Override public IndexedInputGate[] getAllInputGates() { return inputs.toArray(new IndexedInputGate[0]); } @Override public TaskEventDispatcher getTaskEventDispatcher() { return taskEventDispatcher; } @Override public JobVertexID getJobVertexId() { return jobVertexID; } @Override public ExecutionAttemptID getExecutionId() { return executionAttemptID; } @Override public BroadcastVariableManager getBroadcastVariableManager() { return this.bcVarManager; } @Override public TaskStateManager getTaskStateManager() { return taskStateManager; } @Override public GlobalAggregateManager getGlobalAggregateManager() { return aggregateManager; } @Override public AccumulatorRegistry getAccumulatorRegistry() { return this.accumulatorRegistry; } @Override public TaskKvStateRegistry getTaskKvStateRegistry() { return taskKvStateRegistry; } @Override public ExternalResourceInfoProvider getExternalResourceInfoProvider() { return externalResourceInfoProvider; } @Override public void acknowledgeCheckpoint(long checkpointId, CheckpointMetrics checkpointMetrics) { throw new UnsupportedOperationException(); } @Override public void acknowledgeCheckpoint( long checkpointId, CheckpointMetrics checkpointMetrics, TaskStateSnapshot subtaskState) { throw new UnsupportedOperationException(); } @Override public void declineCheckpoint(long checkpointId, CheckpointException cause) { throw new UnsupportedOperationException(cause); } @Override public TaskOperatorEventGateway getOperatorCoordinatorEventGateway() { return new NoOpTaskOperatorEventGateway(); } @Override public void failExternally(Throwable cause) { if (!expectedExternalFailureCause.isPresent()) { throw new UnsupportedOperationException( "MockEnvironment does not support external task failure."); } checkArgument(expectedExternalFailureCause.get().isInstance(checkNotNull(cause))); checkState(!actualExternalFailureCause.isPresent()); actualExternalFailureCause = Optional.of(cause); } @Override public void close() throws Exception { // close() method should be idempotent and calling memManager.verifyEmpty() will throw after // it was shutdown. if (!memManager.isShutdown()) { checkState( memManager.verifyEmpty(), "Memory Manager managed memory was not completely freed."); } memManager.shutdown(); ioManager.close(); } @Override public void setMainMailboxExecutor(@NotNull MailboxExecutor mainMailboxExecutor) { this.mainMailboxExecutor = mainMailboxExecutor; } @Override public MailboxExecutor getMainMailboxExecutor() { return mainMailboxExecutor; } @Override public void setAsyncOperationsThreadPool(@NotNull ExecutorService executorService) { this.asyncOperationsThreadPool = executorService; } @Override public ExecutorService getAsyncOperationsThreadPool() { return asyncOperationsThreadPool; } @Override public void setCheckpointStorageAccess( @NotNull CheckpointStorageAccess checkpointStorageAccess) { this.checkpointStorageAccess = checkpointStorageAccess; } @Override public CheckpointStorageAccess getCheckpointStorageAccess() { return checkNotNull(checkpointStorageAccess); } public void setExpectedExternalFailureCause(Class<? extends Throwable> expectedThrowableClass) { this.expectedExternalFailureCause = Optional.of(expectedThrowableClass); } public Optional<? extends Throwable> getActualExternalFailureCause() { return actualExternalFailureCause; } }
/* * 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.camel.component.salesforce.internal.processor; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.Map; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.XStreamException; import com.thoughtworks.xstream.mapper.CachingMapper; import com.thoughtworks.xstream.mapper.CannotResolveClassException; import org.apache.camel.AsyncCallback; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.component.salesforce.SalesforceEndpoint; import org.apache.camel.component.salesforce.api.SalesforceException; import org.apache.camel.component.salesforce.api.dto.AbstractDTOBase; import org.apache.camel.component.salesforce.api.dto.CreateSObjectResult; import org.apache.camel.component.salesforce.api.dto.GlobalObjects; import org.apache.camel.component.salesforce.api.dto.RestResources; import org.apache.camel.component.salesforce.api.dto.SObjectBasicInfo; import org.apache.camel.component.salesforce.api.dto.SObjectDescription; import org.apache.camel.component.salesforce.api.dto.SearchResults; import org.apache.camel.component.salesforce.api.dto.Versions; import org.apache.camel.component.salesforce.api.dto.approval.ApprovalResult; import org.apache.camel.component.salesforce.api.utils.XStreamUtils; import org.eclipse.jetty.util.StringUtil; import static org.apache.camel.component.salesforce.SalesforceEndpointConfig.SOBJECT_NAME; public class XmlRestProcessor extends AbstractRestProcessor { // although XStream is generally thread safe, because of the way we use aliases // for GET_BASIC_INFO and GET_DESCRIPTION, we need to use a ThreadLocal // not very efficient when both JSON and XML are used together with a single Thread pool // but this will do for now private static ThreadLocal<XStream> xStream = new ThreadLocal<XStream>() { @Override protected XStream initialValue() { return XStreamUtils.createXStream(); } }; private static final String RESPONSE_ALIAS = XmlRestProcessor.class.getName() + ".responseAlias"; public XmlRestProcessor(SalesforceEndpoint endpoint) throws SalesforceException { super(endpoint); } @Override protected void processRequest(Exchange exchange) throws SalesforceException { switch (operationName) { case GET_VERSIONS: exchange.setProperty(RESPONSE_CLASS, Versions.class); break; case GET_RESOURCES: exchange.setProperty(RESPONSE_CLASS, RestResources.class); break; case GET_GLOBAL_OBJECTS: // handle in built response types exchange.setProperty(RESPONSE_CLASS, GlobalObjects.class); break; case GET_BASIC_INFO: // handle in built response types exchange.setProperty(RESPONSE_CLASS, SObjectBasicInfo.class); // need to add alias for Salesforce XML that uses SObject name as root element exchange.setProperty(RESPONSE_ALIAS, getParameter(SOBJECT_NAME, exchange, USE_BODY, NOT_OPTIONAL)); break; case GET_DESCRIPTION: // handle in built response types exchange.setProperty(RESPONSE_CLASS, SObjectDescription.class); // need to add alias for Salesforce XML that uses SObject name as root element exchange.setProperty(RESPONSE_ALIAS, getParameter(SOBJECT_NAME, exchange, USE_BODY, NOT_OPTIONAL)); break; case GET_SOBJECT: // need to add alias for Salesforce XML that uses SObject name as root element exchange.setProperty(RESPONSE_ALIAS, getParameter(SOBJECT_NAME, exchange, IGNORE_BODY, NOT_OPTIONAL)); break; case CREATE_SOBJECT: // handle known response type exchange.setProperty(RESPONSE_CLASS, CreateSObjectResult.class); break; case GET_SOBJECT_WITH_ID: // need to add alias for Salesforce XML that uses SObject name as root element exchange.setProperty(RESPONSE_ALIAS, getParameter(SOBJECT_NAME, exchange, IGNORE_BODY, NOT_OPTIONAL)); break; case UPSERT_SOBJECT: // handle known response type exchange.setProperty(RESPONSE_CLASS, CreateSObjectResult.class); break; case QUERY: case QUERY_ALL: case QUERY_MORE: // need to add alias for Salesforce XML that uses SObject name as root element exchange.setProperty(RESPONSE_ALIAS, "QueryResult"); break; case SEARCH: // handle known response type exchange.setProperty(RESPONSE_CLASS, SearchResults.class); break; case APEX_CALL: // need to add alias for Salesforce XML that uses SObject name as root element exchange.setProperty(RESPONSE_ALIAS, "response"); break; case APPROVAL: exchange.setProperty(RESPONSE_CLASS, ApprovalResult.class); break; case APPROVALS: throw new SalesforceException("Fetching of approvals (as of 18.11.2016) with XML format results in HTTP status 500." + " To fetch approvals please use JSON format.", 0); default: // ignore, some operations do not require alias or class exchange properties } } protected InputStream getRequestStream(Exchange exchange) throws SalesforceException { try { // get request stream from In message Message in = exchange.getIn(); InputStream request = in.getBody(InputStream.class); if (request == null) { AbstractDTOBase dto = in.getBody(AbstractDTOBase.class); if (dto != null) { // marshall the DTO request = getRequestStream(in, dto); } else { // if all else fails, get body as String final String body = in.getBody(String.class); if (null == body) { String msg = "Unsupported request message body " + (in.getBody() == null ? null : in.getBody().getClass()); throw new SalesforceException(msg, null); } else { request = new ByteArrayInputStream(body.getBytes(StringUtil.__UTF8)); } } } return request; } catch (XStreamException e) { String msg = "Error marshaling request: " + e.getMessage(); throw new SalesforceException(msg, e); } catch (UnsupportedEncodingException e) { String msg = "Error marshaling request: " + e.getMessage(); throw new SalesforceException(msg, e); } } @Override protected InputStream getRequestStream(final Message in, final Object object) throws SalesforceException { final XStream localXStream = xStream.get(); // first process annotations on the class, for things like alias, etc. localXStream.processAnnotations(object.getClass()); final ByteArrayOutputStream out = new ByteArrayOutputStream(); // make sure we write the XML with the right encoding try { localXStream.toXML(object, new OutputStreamWriter(out, StringUtil.__UTF8)); } catch (UnsupportedEncodingException e) { String msg = "Error marshaling request: " + e.getMessage(); throw new SalesforceException(msg, e); } return new ByteArrayInputStream(out.toByteArray()); } @Override protected void processResponse(final Exchange exchange, final InputStream responseEntity, final Map<String, String> headers, final SalesforceException exception, final AsyncCallback callback) { final XStream localXStream = xStream.get(); try { final Message out = exchange.getOut(); final Message in = exchange.getIn(); out.copyFromWithNewBody(in, null); out.getHeaders().putAll(headers); if (exception != null) { if (shouldReport(exception)) { exchange.setException(exception); } } else if (responseEntity != null) { // do we need to un-marshal a response final Class<?> responseClass = exchange.getProperty(RESPONSE_CLASS, Class.class); Object response; if (!rawPayload && responseClass != null) { // its ok to call this multiple times, as xstream ignores duplicate calls localXStream.processAnnotations(responseClass); final String responseAlias = exchange.getProperty(RESPONSE_ALIAS, String.class); if (responseAlias != null) { // extremely dirty, need to flush entire cache if its holding on to an old alias!!! final CachingMapper mapper = (CachingMapper) localXStream.getMapper(); try { if (mapper.realClass(responseAlias) != responseClass) { mapper.flushCache(); } } catch (CannotResolveClassException ignore) { // recent XStream versions add a ClassNotFoundException to cache mapper.flushCache(); } localXStream.alias(responseAlias, responseClass); } response = responseClass.newInstance(); localXStream.fromXML(responseEntity, response); } else { // return the response as a stream, for getBlobField response = responseEntity; } out.setBody(response); } } catch (XStreamException e) { String msg = "Error parsing XML response: " + e.getMessage(); exchange.setException(new SalesforceException(msg, e)); } catch (Exception e) { String msg = "Error creating XML response: " + e.getMessage(); exchange.setException(new SalesforceException(msg, e)); } finally { // cleanup temporary exchange headers exchange.removeProperty(RESPONSE_CLASS); exchange.removeProperty(RESPONSE_ALIAS); // consume response entity if (responseEntity != null) { try { responseEntity.close(); } catch (IOException ignored) { } } // notify callback that exchange is done callback.done(false); } } }
/******************************************************************************* * 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.tests.bullet; import com.badlogic.gdx.Application.ApplicationType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.environment.DirectionalShadowLight; import com.badlogic.gdx.graphics.g3d.loader.ObjLoader; import com.badlogic.gdx.graphics.g3d.utils.DepthShaderProvider; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.Ray; import com.badlogic.gdx.physics.bullet.Bullet; import com.badlogic.gdx.physics.bullet.dynamics.btRigidBody; import com.badlogic.gdx.physics.bullet.linearmath.LinearMath; import com.badlogic.gdx.physics.bullet.linearmath.btIDebugDraw.DebugDrawModes; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; /** @author xoppa */ public class BaseBulletTest extends BulletTest { // Set this to the path of the lib to use it on desktop instead of default lib. private final static String customDesktopLib = null;//"D:\\Xoppa\\code\\libgdx\\extensions\\gdx-bullet\\jni\\vs\\gdxBullet\\x64\\Debug\\gdxBullet.dll"; private static boolean initialized = false; public static boolean shadows = true; public static void init () { if (initialized) return; // Need to initialize bullet before using it. if (Gdx.app.getType() == ApplicationType.Desktop && customDesktopLib != null) { System.load(customDesktopLib); } else Bullet.init(); Gdx.app.log("Bullet", "Version = " + LinearMath.btGetVersion()); initialized = true; } public Environment environment; public DirectionalLight light; public ModelBatch shadowBatch; public BulletWorld world; public ObjLoader objLoader = new ObjLoader(); public ModelBuilder modelBuilder = new ModelBuilder(); public ModelBatch modelBatch; public Array<Disposable> disposables = new Array<Disposable>(); private int debugMode = DebugDrawModes.DBG_NoDebug; protected final static Vector3 tmpV1 = new Vector3(), tmpV2 = new Vector3(); public BulletWorld createWorld () { return new BulletWorld(); } @Override public void create () { init(); environment = new Environment(); environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.3f, 0.3f, 0.3f, 1.f)); light = shadows ? new DirectionalShadowLight(1024, 1024, 20f, 20f, 1f, 300f) : new DirectionalLight(); light.set(0.8f, 0.8f, 0.8f, -0.5f, -1f, 0.7f); environment.add(light); if (shadows) environment.shadowMap = (DirectionalShadowLight)light; shadowBatch = new ModelBatch(new DepthShaderProvider()); modelBatch = new ModelBatch(); world = createWorld(); world.performanceCounter = performanceCounter; final float width = Gdx.graphics.getWidth(); final float height = Gdx.graphics.getHeight(); if (width > height) camera = new PerspectiveCamera(67f, 3f * width / height, 3f); else camera = new PerspectiveCamera(67f, 3f, 3f * height / width); camera.position.set(10f, 10f, 10f); camera.lookAt(0, 0, 0); camera.update(); // Create some simple models final Model groundModel = modelBuilder.createRect( 20f, 0f, -20f, -20f, 0f, -20f, -20f, 0f, 20f, 20f, 0f, 20f, 0, 1, 0, new Material(ColorAttribute.createDiffuse(Color.WHITE), ColorAttribute.createSpecular(Color.WHITE), FloatAttribute .createShininess(16f)), Usage.Position | Usage.Normal); disposables.add(groundModel); final Model boxModel = modelBuilder.createBox(1f, 1f, 1f, new Material(ColorAttribute.createDiffuse(Color.WHITE), ColorAttribute.createSpecular(Color.WHITE), FloatAttribute.createShininess(64f)), Usage.Position | Usage.Normal); disposables.add(boxModel); // Add the constructors world.addConstructor("ground", new BulletConstructor(groundModel, 0f)); // mass = 0: static body world.addConstructor("box", new BulletConstructor(boxModel, 1f)); // mass = 1kg: dynamic body world.addConstructor("staticbox", new BulletConstructor(boxModel, 0f)); // mass = 0: static body } @Override public void dispose () { world.dispose(); world = null; for (Disposable disposable : disposables) disposable.dispose(); disposables.clear(); modelBatch.dispose(); modelBatch = null; shadowBatch.dispose(); shadowBatch = null; if (shadows) ((DirectionalShadowLight)light).dispose(); light = null; super.dispose(); } @Override public void render () { render(true); } public void render (boolean update) { fpsCounter.put(Gdx.graphics.getFramesPerSecond()); if (update) update(); beginRender(true); renderWorld(); Gdx.gl.glDisable(GL20.GL_DEPTH_TEST); if (debugMode != DebugDrawModes.DBG_NoDebug) world.setDebugMode(debugMode); Gdx.gl.glEnable(GL20.GL_DEPTH_TEST); performance.setLength(0); performance.append("FPS: ").append(fpsCounter.value).append(", Bullet: ") .append((int)(performanceCounter.load.value * 100f)).append("%"); } protected void beginRender (boolean lighting) { Gdx.gl.glViewport(0, 0, Gdx.graphics.getBackBufferWidth(), Gdx.graphics.getBackBufferHeight()); Gdx.gl.glClearColor(0, 0, 0, 0); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); camera.update(); } protected void renderWorld () { if (shadows) { ((DirectionalShadowLight)light).begin(Vector3.Zero, camera.direction); shadowBatch.begin(((DirectionalShadowLight)light).getCamera()); world.render(shadowBatch, null); shadowBatch.end(); ((DirectionalShadowLight)light).end(); } modelBatch.begin(camera); world.render(modelBatch, environment); modelBatch.end(); } public void update () { world.update(); } public BulletEntity shoot (final float x, final float y) { return shoot(x, y, 30f); } public BulletEntity shoot (final float x, final float y, final float impulse) { return shoot("box", x, y, impulse); } public BulletEntity shoot (final String what, final float x, final float y, final float impulse) { // Shoot a box Ray ray = camera.getPickRay(x, y); BulletEntity entity = world.add(what, ray.origin.x, ray.origin.y, ray.origin.z); entity.setColor(0.5f + 0.5f * (float)Math.random(), 0.5f + 0.5f * (float)Math.random(), 0.5f + 0.5f * (float)Math.random(), 1f); ((btRigidBody)entity.body).applyCentralImpulse(ray.direction.scl(impulse)); return entity; } public void setDebugMode (final int mode) { world.setDebugMode(debugMode = mode); } public void toggleDebugMode () { if (world.getDebugMode() == DebugDrawModes.DBG_NoDebug) setDebugMode(DebugDrawModes.DBG_DrawWireframe | DebugDrawModes.DBG_DrawFeaturesText | DebugDrawModes.DBG_DrawText | DebugDrawModes.DBG_DrawContactPoints); else if (world.renderMeshes) world.renderMeshes = false; else { world.renderMeshes = true; setDebugMode(DebugDrawModes.DBG_NoDebug); } } @Override public boolean longPress (float x, float y) { toggleDebugMode(); return true; } @Override public boolean keyUp (int keycode) { if (keycode == Keys.ENTER) { toggleDebugMode(); return true; } return super.keyUp(keycode); } }
/* * Copyright 2016 Crown Copyright * * 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 stroom.legacy.model_6_1; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Locale; /** * Helper class for resources. */ @Deprecated public final class StreamUtil { /** * Buffer size to use. */ public static final int BUFFER_SIZE = 8192; // TODO 2016-04-20: Replace all references to "UTF-8" (throughout the // code-base) with a reference to StandardCharsets.UTF_8. Possibly remove // the default charset name just leaving default charset. public static final String DEFAULT_CHARSET_NAME = "UTF-8"; public static final Charset DEFAULT_CHARSET = Charset.forName(DEFAULT_CHARSET_NAME); public static final Locale DEFAULT_LOCALE = Locale.ENGLISH; private static final ByteSlice ZERO_BYTES = new ByteSlice(new byte[0]); private StreamUtil() { // NA Utility } /** * Convert a resource to a string. */ public static String streamToString(final InputStream stream) { return streamToString(stream, DEFAULT_CHARSET); } /** * Convert a resource to a string. */ public static String streamToString(final InputStream stream, final boolean close) { return streamToString(stream, DEFAULT_CHARSET, close); } /** * Convert a resource to a string. */ public static String streamToString(final InputStream stream, final Charset charset) { return streamToString(stream, charset, true); } /** * Convert a resource to a string. */ public static String streamToString(final InputStream stream, final Charset charset, final boolean close) { if (stream == null) { return null; } final MyByteArrayOutputStream baos = doStreamToBuffer(stream, close); return baos.toString(charset); } public static byte[] streamToBytes(final InputStream stream) { return doStreamToBuffer(stream, true).toByteArray(); } public static ByteArrayOutputStream streamToBuffer(final InputStream stream) { return doStreamToBuffer(stream, true); } public static ByteArrayOutputStream streamToBuffer(final InputStream stream, final boolean close) { return doStreamToBuffer(stream, close); } private static MyByteArrayOutputStream doStreamToBuffer(final InputStream stream, final boolean close) { if (stream == null) { return null; } final MyByteArrayOutputStream byteArrayOutputStream = new MyByteArrayOutputStream(); try { final byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = stream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, len); } if (close) { stream.close(); } return byteArrayOutputStream; } catch (final IOException ioEx) { // Wrap it throw new RuntimeException(ioEx); } } /** * Takes a string and writes it to a file. */ public static void stringToFile(final String string, final Path file) { stringToFile(string, file, DEFAULT_CHARSET); } /** * Takes a string and writes it to a file. */ public static void stringToFile(final String string, final Path file, final Charset charset) { try { if (Files.isRegularFile(file)) { FileUtil.deleteFile(file); } Files.createDirectories(file.getParent()); Files.write(file, string.getBytes(charset)); } catch (final IOException ioEx) { // Wrap it throw new RuntimeException(ioEx); } } /** * Takes a string and writes it to an output stream. */ public static void stringToStream(final String string, final OutputStream outputStream) { stringToStream(string, outputStream, DEFAULT_CHARSET); } /** * Takes a string and writes it to an output stream. */ public static void stringToStream(final String string, final OutputStream outputStream, final Charset charset) { try { outputStream.write(string.getBytes(charset)); outputStream.flush(); outputStream.close(); } catch (final IOException ioEx) { // Wrap it throw new RuntimeException(ioEx); } } public static String fileToString(final Path file) { return fileToString(file, DEFAULT_CHARSET); } /** * Reads a file and returns it as a string. */ public static String fileToString(final Path file, final Charset charset) { try { final byte[] bytes = Files.readAllBytes(file); return new String(bytes, charset); } catch (final IOException ioEx) { // Wrap it throw new RuntimeException(ioEx); } } // /** // * Reads a file and returns it as a stream. // */ // public static InputStream fileToStream(final Path file) { // try (final InputStream is = new BufferedInputStream(Files.newInputStream(file)) ){ // return new BufferedInputStream(Files.newInputStream(file)); // } catch (final IOException ioEx) { // // Wrap it // throw new RuntimeException(ioEx); // } // } /** * Take a stream to a file. * * @param inputStream to read and close * @param outputFileName to (over)write and close */ public static void streamToFile(final InputStream inputStream, final String outputFileName) { streamToFile(inputStream, Paths.get(outputFileName)); } public static void streamToFile(final InputStream inputStream, final Path file) { try { if (Files.isRegularFile(file)) { FileUtil.deleteFile(file); } Files.createDirectories(file.getParent()); try (final OutputStream fos = Files.newOutputStream(file)) { streamToStream(inputStream, fos); } } catch (final IOException ioEx) { // Wrap it throw new RuntimeException(ioEx); } } /** * Copy file to file. * * @param fromFile the Path to copy (readable, non-null file) * @param toFile the Path to copy to (non-null, parent dir exists) * @throws IOException */ public static void copyFile(final Path fromFile, final Path toFile) throws IOException { Files.copy(fromFile, toFile); // try (final InputStream in = Files.newInputStream(fromFile); final OutputStream out = Files.newOutputStream(toFile)) { // streamToStream(in, out); // } } /** * Take a stream to another stream (AND CLOSE BOTH). */ public static void streamToStream(final InputStream inputStream, final OutputStream outputStream) { streamToStream(inputStream, outputStream, true); } /** * Take a stream to another stream. */ public static long streamToStream(final InputStream inputStream, final OutputStream outputStream, final boolean close) { long bytesWritten = 0; try { final byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); bytesWritten += len; } if (close) { outputStream.close(); inputStream.close(); } return bytesWritten; } catch (final IOException ioEx) { // Wrap it throw new RuntimeException(ioEx); } } /** * Convert a string to a stream. * * @return the stream or null */ public static InputStream stringToStream(final String string) { return stringToStream(string, DEFAULT_CHARSET); } /** * Convert a string to a stream. * * @param string to convert * @return the stream or null */ public static InputStream stringToStream(final String string, final Charset charset) { if (string != null) { return new ByteArrayInputStream(string.getBytes(charset)); } return null; } /** * Try a read a full buffer from a stream. * * @param stream to read from * @param buffer to read into * @throws IOException if error */ public static int eagerRead(final InputStream stream, final byte[] buffer) throws IOException { int read = 0; int offset = 0; int remaining = buffer.length; while (remaining > 0 && (read = stream.read(buffer, offset, remaining)) != -1) { remaining = remaining - read; offset = offset + read; } // Did not read anything ... must be finished if (offset == 0) { return -1; } // Length read return offset; } public static long skip(final InputStream inputStream, final long totalBytesToSkip) throws IOException { long bytesToSkip = totalBytesToSkip; while (bytesToSkip > 0) { final long skip = inputStream.skip(bytesToSkip); if (skip < 0) { break; } bytesToSkip -= skip; } return totalBytesToSkip - bytesToSkip; } /** * Read an exact number of bytes into a buffer. Throws an exception if the * number of bytes are not available. * * @param stream to read from * @param buffer to read into * @throws IOException if error */ public static void fillBuffer(final InputStream stream, final byte[] buffer) throws IOException { fillBuffer(stream, buffer, 0, buffer.length); } /** * Read an exact number of bytes into a buffer. Throws an exception if the * number of bytes are not available. * * @param stream to read from * @param buffer to read into * @param offset to use * @param len length * @throws IOException if error */ public static void fillBuffer(final InputStream stream, final byte[] buffer, final int offset, final int len) throws IOException { final int realLen = stream.read(buffer, offset, len); if (realLen == -1) { throw new IOException("Unable to fill buffer"); } if (realLen != len) { // Try Again fillBuffer(stream, buffer, offset + realLen, len - realLen); } } /** * Wrap a stream and don't let it close. */ public static OutputStream ignoreClose(final OutputStream outputStream) { return new FilterOutputStream(outputStream) { @Override public void close() throws IOException { flush(); // Ignore Close } }; } @SuppressWarnings(value = "DM_DEFAULT_ENCODING") public static String exceptionCallStack(final Throwable throwable) { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); final PrintWriter printWriter = new PrintWriter(byteArrayOutputStream); throwable.printStackTrace(printWriter); printWriter.close(); return new String(byteArrayOutputStream.toByteArray(), StreamUtil.DEFAULT_CHARSET); } public static void close(final OutputStream outputStream) { try { if (outputStream != null) { outputStream.close(); } } catch (final Exception ex) { throw new RuntimeException(ex); } } public static void close(final InputStream inputStream) { try { if (inputStream != null) { inputStream.close(); } } catch (final Exception ex) { throw new RuntimeException(ex); } } public static ByteSlice getByteSlice(final String string) { if (string == null) { return ZERO_BYTES; } return new ByteSlice(string.getBytes(DEFAULT_CHARSET)); } /** * A wrapper on ByteArrayOutputStream to add direct use of charset without * charset name. */ private static class MyByteArrayOutputStream extends ByteArrayOutputStream { public synchronized String toString(final Charset charset) { return new String(buf, 0, count, charset); } } }
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.drools.games.adventures; import net.miginfocom.layout.ConstraintParser; import net.miginfocom.swing.MigLayout; import org.drools.games.adventures.model.Character; import org.drools.games.adventures.model.DropCommand; import org.drools.games.adventures.model.GiveCommand; import org.drools.games.adventures.model.LookCommand; import org.drools.games.adventures.model.MoveCommand; import org.drools.games.adventures.model.PickupCommand; import org.drools.games.adventures.model.Room; import org.drools.games.adventures.model.Thing; import org.drools.games.adventures.model.UseCommand; import org.kie.api.runtime.Channel; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.event.InternalFrameEvent; import javax.swing.event.InternalFrameListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionAdapter; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Vector; public class AdventureFrame extends JFrame { private static final Font BUTT_FONT = new Font( "monospaced", Font.PLAIN, 12 ); private JPanel contentPane; private JTextArea outputTextArea; private JComboBox characterSelectCombo; private JTextArea localEventsTextArea; private JTable exitsTable; private JTable thingsTable; private JTable inventoryTable; private JFormattedTextField cmdTextField; //private JTextArea globalEventsTextArea; private GameEngine gameEngine; private UserSession session; private List cmd; //private ACLMessage msg; /** * Create the frame. */ public AdventureFrame(UserSession session, final GameEngine gameEngine, int onClose) { this.session = session; this.gameEngine = gameEngine; setDefaultCloseOperation( onClose ); setBounds( 100, 100, 1100, 787 ); contentPane = new JPanel(); contentPane.setBorder( new EmptyBorder( 5, 5, 5, 5 ) ); setContentPane( contentPane ); contentPane.setLayout( new BoxLayout( contentPane, BoxLayout.Y_AXIS ) ); JToolBar toolBar_1 = new JToolBar(); toolBar_1.setAlignmentX( Component.LEFT_ALIGNMENT ); contentPane.add( toolBar_1 ); JToggleButton newFrame = new JToggleButton( "New Window" ); toolBar_1.add( newFrame ); newFrame.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { TextAdventure.createFrame( gameEngine, JFrame.DISPOSE_ON_CLOSE ); } } ); JSplitPane splitPane = new JSplitPane(); splitPane.setResizeWeight( 0.4 ); contentPane.add( splitPane ); Component leftPanel = createEventsAndInvetoryPanel(); splitPane.setLeftComponent( leftPanel ); JPanel test = new JPanel(); splitPane.setRightComponent( test ); test.setLayout( new MigLayout( "", "[][][]", "[][grow, fill][][][][][fill][]" ) ); createpOutputPanel( test ); createCharacterPanel( test ); createBuildActionsPanel( test ); createSendCommandPanel( test ); } public UserSession getSession() { return session; } public void setSession(UserSession session) { this.session = session; } public GameEngine getGameEngine() { return gameEngine; } public void setGameEngine(GameEngine gameEngine) { this.gameEngine = gameEngine; } public JTextArea getOutputTextArea() { return outputTextArea; } public JComboBox getCharacterSelectCombo() { return characterSelectCombo; } public JTextArea getLocalEventsTextArea() { return localEventsTextArea; } public JTable getExitsTable() { return exitsTable; } public JTable getThingsTable() { return thingsTable; } public JTable getInventoryTable() { return inventoryTable; } private Component createEventsAndInvetoryPanel() { JSplitPane leftSplitPanel = new JSplitPane(); leftSplitPanel.setOrientation( JSplitPane.VERTICAL_SPLIT ); leftSplitPanel.setDividerLocation( 400 ); //Component eventsPanel = createEventsPanel(); Component eventsPanel = createLocalEventsPanel(); leftSplitPanel.setLeftComponent( eventsPanel ); Component inventoryPanel = createInventoryPanel(); leftSplitPanel.setRightComponent( inventoryPanel ); return leftSplitPanel; } private Component createEventsPanel() { JSplitPane splitPanel = new JSplitPane(); splitPanel.setResizeWeight( 0.4 ); splitPanel.setOrientation( JSplitPane.VERTICAL_SPLIT ); //splitPanel.setRightComponent( createGlobalEventsPanel() ); splitPanel.setLeftComponent( createLocalEventsPanel() ); return splitPanel; } private Component createGlobalEventsPanel() { JPanel globalEventsPanel = new JPanel(); globalEventsPanel.setLayout( new BoxLayout( globalEventsPanel, BoxLayout.Y_AXIS ) ); JLabel globalEventsLabel = new JLabel( "Global Events" ); globalEventsPanel.add( globalEventsLabel ); JScrollPane pane1 = createTextAreaScroll( "", 20, 50, true, true ); //globalEventsTextArea = (JTextArea) ((JViewport) pane1.getComponents()[0]).getComponents()[0]; globalEventsPanel.add( pane1 ); return globalEventsPanel; } private Component createLocalEventsPanel() { JPanel localEventsPanel = new JPanel(); localEventsPanel.setLayout( new BoxLayout( localEventsPanel, BoxLayout.Y_AXIS ) ); JLabel localEventsLabel = new JLabel( "Events" ); localEventsPanel.add( localEventsLabel ); // JScrollPane pane2 = createTextAreaScroll( "", // 20, // 50, // true, // true ); JTextArea ta = new JTextArea( "", 20, 50 ); ta.setFont( UIManager.getFont( "TextField.font" ) ); ta.setWrapStyleWord( true ); ta.setLineWrap( true ); JScrollPane scroll = new JScrollPane( ta, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED ); localEventsTextArea = (JTextArea) ((JViewport) scroll.getComponents()[0]).getComponents()[0]; localEventsPanel.add( scroll ); return localEventsPanel; } private Component createInventoryPanel() { inventoryTable = new JTable(); inventoryTable.setBorder( null ); inventoryTable.setModel( new NonEditableTableMode( new Object[][]{ }, new String[]{ "Inventory" } ) ); inventoryTable.addMouseListener( new MouseListener() { public void mouseReleased(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseClicked(MouseEvent e) { if ( cmd == null ) { return; } int row = inventoryTable.rowAtPoint( e.getPoint() ); int col = inventoryTable.columnAtPoint( e.getPoint() ); Thing t = (Thing) inventoryTable.getModel().getValueAt( row, col ); cmdTextField.setText( cmdTextField.getText() + t.getName() + " " ); cmd.add( t ); } } ); JScrollPane inventoryPanel = new JScrollPane( inventoryTable ); return inventoryPanel; } private void createpOutputPanel(JPanel parent) { parent.add( createLabel( "Output" ), "wrap, spanx 3" ); // JScrollPane pane = createTextAreaScroll( "", // 20, // 45, // true, // true ); JTextArea ta = new JTextArea( "", 20, 50 ); ta.setFont( UIManager.getFont( "TextField.font" ) ); ta.setWrapStyleWord( true ); ta.setLineWrap( true ); JScrollPane scroll = new JScrollPane( ta, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED ); outputTextArea = (JTextArea) ((JViewport) scroll.getComponents()[0]).getComponents()[0]; parent.add( scroll, "wrap, span 3" ); } private void createCharacterPanel(JPanel parent) { parent.add( createLabel( "Character" ), "wrap, spanx 3" ); characterSelectCombo = new JComboBox(); characterSelectCombo.setModel( new DefaultComboBoxModel( new Object[]{null, null} ) ); parent.add( characterSelectCombo, "top, left" ); Map<String, Character> characterMap = ( Map<String, Character> ) gameEngine.getData().get("characters"); Character[] characters = characterMap.values().toArray( new Character[characterMap.size()] ); characterSelectCombo.setModel( new DefaultComboBoxModel( characters ) ); characterSelectCombo.setSelectedItem( characterMap.get("hero")); characterSelectCombo.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { Character c = (Character) characterSelectCombo.getSelectedObjects()[0]; org.kie.api.runtime.rule.FactHandle fh = gameEngine.getKieSession().getFactHandle(session); session.setCharacter(c); gameEngine.getKieSession().update(fh, session); cmd = new ArrayList(); cmd.add( LookCommand.class ); cmd.add( characterSelectCombo.getSelectedObjects()[0] ); gameEngine.receiveMessage( session, cmd ); cmd = null; } } ); JTable characterPropertiesTable = new JTable(); characterPropertiesTable.setPreferredScrollableViewportSize( new Dimension( 240, 200 ) ); characterPropertiesTable.setBorder( null ); characterPropertiesTable.setModel( new NonEditableTableMode( new Object[][]{ {"strength", "100"}, {"health", "100"}, {"coiins", "100"}, {"speed", "100"}, {"mana", "100"}, }, new String[]{ "property", "value" } ) ); JScrollPane characterPropertiesPanel = new JScrollPane( characterPropertiesTable ); parent.add( characterPropertiesPanel, "top, left, wrap, spanx 2" ); } private void createBuildActionsPanel(JPanel parent) { parent.add( createLabel( "Actions" ), "wrap, spanx 3" ); JPanel actionsPanel = new JPanel(); actionsPanel.setBorder( null ); actionsPanel.setLayout( new BoxLayout( actionsPanel, BoxLayout.Y_AXIS ) ); JButton moveBtn = new JButton( "Move" ); moveBtn.setToolTipText("Select one Room from the Exits, then press Send"); actionsPanel.add( moveBtn ); // msg = new ACLMessage(); // msg.setPerformative( Performative.REQUEST ); moveBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { cmdTextField.setText( "Move " ); cmd = new ArrayList(); cmd.add(MoveCommand.class ); cmd.add( characterSelectCombo.getSelectedObjects()[0] ); } } ); JButton pickupBtn = new JButton( "Pick Up" ); pickupBtn.setToolTipText("Select one from the Items list, then press Send"); actionsPanel.add( pickupBtn ); pickupBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { cmdTextField.setText( "Pickup " ); cmd = new ArrayList(); cmd.add(PickupCommand.class); cmd.add( characterSelectCombo.getSelectedObjects()[0] ); } } ); JButton dropBtn = new JButton( "Drop" ); dropBtn.setToolTipText("Select one from the Inventory, then press Send"); actionsPanel.add( dropBtn ); dropBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { cmdTextField.setText( "Drop " ); cmd = new ArrayList(); cmd.add(DropCommand.class); cmd.add( characterSelectCombo.getSelectedObjects()[0] ); } } ); JButton giveBtn = new JButton( "Give" ); giveBtn.setToolTipText("Select one from the Inventory, then Select the target Character, then press Send"); actionsPanel.add( giveBtn ); giveBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { cmdTextField.setText( "Give " ); cmd = new ArrayList(); cmd.add(GiveCommand.class); cmd.add( characterSelectCombo.getSelectedObjects()[0] ); } } ); JButton useBtn = new JButton( "Use" ); useBtn.setToolTipText("Select one from the Inventory, then Select the target Thing or Room"); actionsPanel.add( useBtn ); useBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { cmdTextField.setText( "Use " ); cmd = new ArrayList(); cmd.add(UseCommand.class); cmd.add( characterSelectCombo.getSelectedObjects()[0] ); } } ); JButton lookBtn = new JButton( "Look" ); giveBtn.setToolTipText("Just press Send"); actionsPanel.add( lookBtn ); lookBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { cmdTextField.setText( "Look " ); cmd = new ArrayList(); cmd.add( LookCommand.class ); cmd.add( characterSelectCombo.getSelectedObjects()[0] ); } } ); parent.add( actionsPanel, "top, left" ); thingsTable = new JTable(); thingsTable.setPreferredScrollableViewportSize( new Dimension( 245, 250 ) ); thingsTable.setBorder( null ); thingsTable.setModel( new NonEditableTableMode( new Object[][]{ }, new String[]{ "Things" } ) ); thingsTable.addMouseListener( new MouseListener() { public void mouseReleased(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseClicked(MouseEvent e) { if ( cmd == null ) { return; } int row = thingsTable.rowAtPoint( e.getPoint() ); int col = thingsTable.columnAtPoint( e.getPoint() ); Thing t = (Thing) thingsTable.getModel().getValueAt( row, col ); cmdTextField.setText( cmdTextField.getText() + t.getName() + " " ); cmd.add( t ); } } ); JScrollPane itemsPanel = new JScrollPane( thingsTable ); parent.add( itemsPanel, "top, left" ); exitsTable = new JTable(); exitsTable.setPreferredScrollableViewportSize( new Dimension( 245, 250 ) ); exitsTable.setBorder( null ); exitsTable.setModel( new NonEditableTableMode( new Object[][]{ }, new String[]{ "Exits" } ) ); exitsTable.addMouseListener( new MouseListener() { public void mouseReleased(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseClicked(MouseEvent e) { if ( cmd == null ) { return; } int row = exitsTable.rowAtPoint( e.getPoint() ); int col = exitsTable.columnAtPoint( e.getPoint() ); Room r = (Room) exitsTable.getModel().getValueAt( row, col ); cmdTextField.setText( cmdTextField.getText() + r.getName() + " " ); cmd.add( r ); } } ); JScrollPane exitsPanel = new JScrollPane( exitsTable ); parent.add( exitsPanel, "top, left, wrap" ); } public void createSendCommandPanel(JPanel parent) { cmdTextField = new JFormattedTextField(); cmdTextField.setText( "" ); parent.add( cmdTextField, "growx, spanx 3, wrap" ); JToggleButton sendBtn = new JToggleButton( "send" ); parent.add( sendBtn ); sendBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { //msg.setContent( cmd ); gameEngine.receiveMessage( session, cmd ); cmd = null; cmdTextField.setText( "" ); } } ); } private JLabel createLabel(String text) { return createLabel( text, SwingConstants.LEADING ); } private JLabel createLabel(String text, int align) { final JLabel b = new JLabel( text, align ); //configureActiveComponet(b); return b; } private JScrollPane createTextAreaScroll(String text, int rows, int cols, boolean hasVerScroll, boolean hasHorScroll) { JTextArea ta = new JTextArea( text, rows, cols ); ta.setFont( UIManager.getFont( "TextField.font" ) ); ta.setWrapStyleWord( true ); ta.setLineWrap( true ); JScrollPane scroll = new JScrollPane( ta, hasVerScroll ? ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED : ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, hasHorScroll ? ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED : ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ); return scroll; } private class ConstraintListener extends MouseAdapter { public void mousePressed(MouseEvent e) { if ( e.isPopupTrigger() ) react( e ); } public void mouseReleased(MouseEvent e) { if ( e.isPopupTrigger() ) react( e ); } public void react(MouseEvent e) { JComponent c = (JComponent) e.getSource(); LayoutManager lm = c.getParent().getLayout(); if ( lm instanceof MigLayout == false ) lm = c.getLayout(); if ( lm instanceof MigLayout ) { MigLayout layout = (MigLayout) lm; boolean isComp = layout.isManagingComponent( c ); Object compConstr = isComp ? layout.getComponentConstraints( c ) : null; if ( isComp && compConstr == null ) compConstr = ""; Object rowsConstr = isComp ? null : layout.getRowConstraints(); Object colsConstr = isComp ? null : layout.getColumnConstraints(); Object layoutConstr = isComp ? null : layout.getLayoutConstraints(); ConstraintsDialog cDlg = new ConstraintsDialog( AdventureFrame.this, // layoutConstr instanceof LC ? IDEUtil.getConstraintString((LC) layoutConstr, false) : (String) layoutConstr, // rowsConstr instanceof AC ? IDEUtil.getConstraintString((AC) rowsConstr, false, false) : (String) rowsConstr, // colsConstr instanceof AC ? IDEUtil.getConstraintString((AC) colsConstr, false, false) : (String) colsConstr, // compConstr instanceof CC ? IDEUtil.getConstraintString((CC) compConstr, false) : (String) compConstr); (String) layoutConstr, (String) rowsConstr, (String) colsConstr, (String) compConstr ); cDlg.pack(); cDlg.setLocationRelativeTo( c ); if ( cDlg.showDialog() ) { try { if ( isComp ) { String constrStr = cDlg.componentConstrTF.getText().trim(); layout.setComponentConstraints( c, constrStr ); if ( c instanceof JButton ) { c.setFont( BUTT_FONT ); ((JButton) c).setText( constrStr.length() == 0 ? "<Empty>" : constrStr ); } } else { layout.setLayoutConstraints( cDlg.layoutConstrTF.getText() ); layout.setRowConstraints( cDlg.rowsConstrTF.getText() ); layout.setColumnConstraints( cDlg.colsConstrTF.getText() ); } } catch ( Exception ex ) { StringWriter sw = new StringWriter(); ex.printStackTrace( new PrintWriter( sw ) ); JOptionPane.showMessageDialog( SwingUtilities.getWindowAncestor( c ), sw.toString(), "Error parsing Constraint!", JOptionPane.ERROR_MESSAGE ); return; } c.invalidate(); c.getParent().validate(); } } } } private static class ToolTipListener extends MouseMotionAdapter { public void mouseMoved(MouseEvent e) { JComponent c = (JComponent) e.getSource(); LayoutManager lm = c.getParent().getLayout(); if ( lm instanceof MigLayout ) { Object constr = ((MigLayout) lm).getComponentConstraints( c ); if ( constr instanceof String ) c.setToolTipText( (constr != null ? ("\"" + constr + "\"") : "null") ); } } } private static class ConstraintsDialog extends JDialog implements ActionListener, KeyEventDispatcher { private static final Color ERROR_COLOR = new Color( 255, 180, 180 ); private final JPanel mainPanel = new JPanel( new MigLayout( "fillx,flowy,ins dialog", "[fill]", "2[]2" ) ); final JTextField layoutConstrTF; final JTextField rowsConstrTF; final JTextField colsConstrTF; final JTextField componentConstrTF; private final JButton okButt = new JButton( "OK" ); private final JButton cancelButt = new JButton( "Cancel" ); private boolean okPressed = false; public ConstraintsDialog(Frame owner, String layoutConstr, String rowsConstr, String colsConstr, String compConstr) { super( owner, (compConstr != null ? "Edit Component Constraints" : "Edit Container Constraints"), true ); layoutConstrTF = createConstraintField( layoutConstr ); rowsConstrTF = createConstraintField( rowsConstr ); colsConstrTF = createConstraintField( colsConstr ); componentConstrTF = createConstraintField( compConstr ); if ( componentConstrTF != null ) { mainPanel.add( new JLabel( "Component Constraints" ) ); mainPanel.add( componentConstrTF ); } if ( layoutConstrTF != null ) { mainPanel.add( new JLabel( "Layout Constraints" ) ); mainPanel.add( layoutConstrTF ); } if ( colsConstrTF != null ) { mainPanel.add( new JLabel( "Column Constraints" ), "gaptop unrel" ); mainPanel.add( colsConstrTF ); } if ( rowsConstrTF != null ) { mainPanel.add( new JLabel( "Row Constraints" ), "gaptop unrel" ); mainPanel.add( rowsConstrTF ); } mainPanel.add( okButt, "tag ok,split,flowx,gaptop 15" ); mainPanel.add( cancelButt, "tag cancel,gaptop 15" ); setContentPane( mainPanel ); okButt.addActionListener( this ); cancelButt.addActionListener( this ); } public void addNotify() { super.addNotify(); KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher( this ); } public void removeNotify() { KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher( this ); super.removeNotify(); } public boolean dispatchKeyEvent(KeyEvent e) { if ( e.getKeyCode() == KeyEvent.VK_ESCAPE ) dispose(); return false; } public void actionPerformed(ActionEvent e) { if ( e.getSource() == okButt ) okPressed = true; dispose(); } private JTextField createConstraintField(String text) { if ( text == null ) return null; final JTextField tf = new JTextField( text, 50 ); tf.setFont( new Font( "monospaced", Font.PLAIN, 12 ) ); tf.addKeyListener( new KeyAdapter() { public void keyPressed(KeyEvent e) { if ( e.getKeyCode() == KeyEvent.VK_ENTER ) { okButt.doClick(); return; } javax.swing.Timer timer = new Timer( 50, new ActionListener() { public void actionPerformed(ActionEvent e) { String constr = tf.getText(); try { if ( tf == layoutConstrTF ) { ConstraintParser.parseLayoutConstraint( constr ); } else if ( tf == rowsConstrTF ) { ConstraintParser.parseRowConstraints( constr ); } else if ( tf == colsConstrTF ) { ConstraintParser.parseColumnConstraints( constr ); } else if ( tf == componentConstrTF ) { ConstraintParser.parseComponentConstraint( constr ); } tf.setBackground( Color.WHITE ); okButt.setEnabled( true ); } catch ( Exception ex ) { tf.setBackground( ERROR_COLOR ); okButt.setEnabled( false ); } } } ); timer.setRepeats( false ); timer.start(); } } ); return tf; } private boolean showDialog() { setVisible( true ); return okPressed; } } // public void receiveMessage(List cmd) { // Performative p = null; // // switch ( p ) { // case REQUEST : // //Performatives r = ( Performatives ) p ; // } // } public void handleRequestGive() { final JOptionPane pane = new JOptionPane( "xxx msg" ); pane.setWantsInput( true ); pane.setInputValue( "" ); pane.setOptions( new String[]{"Yes", "No"} ); JInternalFrame internalFrame = pane.createInternalFrame( contentPane, "xxx title" ); internalFrame.setVisible( true ); pane.show(); internalFrame.addInternalFrameListener( new InternalFrameListener() { public void internalFrameOpened(InternalFrameEvent e) { } public void internalFrameIconified(InternalFrameEvent e) { } public void internalFrameDeiconified(InternalFrameEvent e) { } public void internalFrameDeactivated(InternalFrameEvent e) { } public void internalFrameClosing(InternalFrameEvent e) { } public void internalFrameClosed(InternalFrameEvent e) { System.out.println( pane.getInputValue() + ":" + pane.getValue() ); } public void internalFrameActivated(InternalFrameEvent e) { } } ); } public static class JTextAreaChannel implements Channel { private JTextArea textArea; public JTextAreaChannel(JTextArea textArea) { this.textArea = textArea; } public void send(Object object) { //textArea.insert( object.toString() + "\n", 0 ); textArea.append( object.toString() + "\n" ); JScrollPane scrollPane = (JScrollPane) ((JViewport) textArea.getParent()).getParent(); // Can't get this to work :( // JScrollBar verticalScrollBar = scrollPane.getVerticalScrollBar(); // JScrollBar horizontalScrollBar = scrollPane.getHorizontalScrollBar(); // verticalScrollBar.setValue(verticalScrollBar.getMinimum()); // horizontalScrollBar.setValue(horizontalScrollBar.getMinimum()); } } // public static class JComboBoxChannel // implements // Channel { // private JComboBox jcomboBox; // // public JComboBoxChannel(JComboBox jcomboBox) { // this.jcomboBox = jcomboBox; // } // // public void send(Object object) { // List list = (List) object; // jcomboBox.setModel( new DefaultComboBoxModel( list.toArray() ) ); // //jcomboBox.setModel( new DefaultComboBoxModel( new Object[] { "xxxxx", "yyyyyy" } ) ) ; // } // } public static class JTableChannel implements Channel { private JTable jTable; public JTableChannel(JTable jTable) { this.jTable = jTable; String name = jTable.getColumnName(0); jTable.getColumn( name ).setCellRenderer(new DefaultTableCellRenderer() { public void setValue(Object value) { if ( value == null ) { return; } else if ( value instanceof Thing ) { setText(((Thing) value).getName()); } else { setText( value.toString() ); } } }); } public void send(Object object) { List<Thing> things = (List<Thing>) object; addRows( things ); } public void addRows(List list) { DefaultTableModel model = (DefaultTableModel) jTable.getModel(); if ( model.getRowCount() < list.size() ) { Object[][] exits = new Object[list.size()][]; for ( int i = 0, length = model.getRowCount(); i < length; i++ ) { model.setValueAt( list.get( i ), i, 0 ); } for ( int i = model.getRowCount(), length = exits.length; i < length; i++ ) { if ( list.get( i ) == null ) { continue; } model.addRow( new Object[]{list.get( i )} ); } } else { Object[][] exits = new Object[list.size()][]; for ( int i = 0; i < exits.length; i++ ) { if ( list.get( i ) == null ) { continue; } model.setValueAt( list.get( i ), i, 0 ); } int i = exits.length; while ( model.getRowCount() > exits.length ) { model.removeRow( i ); } } } } public static class NonEditableTableMode extends DefaultTableModel { public NonEditableTableMode() { } public NonEditableTableMode(int rowCount, int columnCount) { super(rowCount, columnCount); } public NonEditableTableMode(Vector columnNames, int rowCount) { super(columnNames, rowCount); } public NonEditableTableMode(Object[] columnNames, int rowCount) { super(columnNames, rowCount); } public NonEditableTableMode(Vector data, Vector columnNames) { super(data, columnNames); } public NonEditableTableMode(Object[][] data, Object[] columnNames) { super(data, columnNames); } @Override public boolean isCellEditable(int row, int column) { //all cells false return false; } } }
package cc.makeblock.makeblock; import java.lang.reflect.Array; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import cc.makeblock.modules.MeButton; import cc.makeblock.modules.MeCarController; import cc.makeblock.modules.MeDcMotor; import cc.makeblock.modules.MeDigiSeg; import cc.makeblock.modules.MeGripper; import cc.makeblock.modules.MeJoystick; import cc.makeblock.modules.MeLightSensor; import cc.makeblock.modules.MeLimitSwitch; import cc.makeblock.modules.MeLineFollower; import cc.makeblock.modules.MeModule; import cc.makeblock.modules.MePIRSensor; import cc.makeblock.modules.MePotential; import cc.makeblock.modules.MeRgbLed; import cc.makeblock.modules.MeServoMotor; import cc.makeblock.modules.MeSoundSensor; import cc.makeblock.modules.MeTemperature; import cc.makeblock.modules.MeUltrasonic; public class MeLayout { static final String dbg = "Layout"; public String name; public String createTime; public String updateTime; public int type=0; public ArrayList<MeModule> moduleList; public MeLayout(JSONObject json){ try { name = json.getString("name"); if(json.has("type")){ type = json.getInt("type"); } createTime = json.getString("createTime"); updateTime = json.getString("updateTime"); JSONArray moduleListJArray = json.getJSONArray("moduleList"); moduleList = new ArrayList<MeModule>(); for (int i=0;i<moduleListJArray.length();i++){ JSONObject jobj = (JSONObject) moduleListJArray.get(i); int modtype = jobj.getInt("type"); MeModule mod=null; switch(modtype){ case MeModule.DEV_ULTRASOINIC: mod = new MeUltrasonic(jobj); break; case MeModule.DEV_TEMPERATURE: mod = new MeTemperature(jobj); break; case MeModule.DEV_LIGHTSENSOR: mod = new MeLightSensor(jobj); break; case MeModule.DEV_SOUNDSENSOR: mod = new MeSoundSensor(jobj); break; case MeModule.DEV_LINEFOLLOWER: mod = new MeLineFollower(jobj); break; case MeModule.DEV_POTENTIALMETER: mod = new MePotential(jobj); break; case MeModule.DEV_LIMITSWITCH: mod = new MeLimitSwitch(jobj); break; case MeModule.DEV_BUTTON: mod = new MeButton(jobj); break; case MeModule.DEV_PIRMOTION: mod = new MePIRSensor(jobj); break; case MeModule.DEV_DCMOTOR: mod = new MeGripper(jobj); break; case MeModule.DEV_SERVO: mod = new MeServoMotor(jobj); break; case MeModule.DEV_JOYSTICK: mod = new MeJoystick(jobj); break; case MeModule.DEV_RGBLED: mod = new MeRgbLed(jobj); break; case MeModule.DEV_SEVSEG: mod = new MeDigiSeg(jobj); break; case MeModule.DEV_CAR_CONTROLLER: mod = new MeCarController(jobj); break; // case MeModule.DEV_GRIPPER_CONTROLLER: // mod = new MeGripper(jobj); // break; default: Log.i(dbg, "unknow module from json "+modtype); break; } if(mod!=null){ mod.setScaleType(type); moduleList.add(mod); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void setName(String v){ name = v; } public String getTime(){ Date date = new Date(); DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); return sdf.format(date); } public MeLayout(String name){ this.name = name; createTime = getTime(); updateTime = createTime; moduleList = new ArrayList<MeModule>(); } public JSONObject toJson(){ JSONObject json = new JSONObject(); try { json.put("name", name); json.put("createTime", createTime); json.put("updateTime", updateTime); JSONArray moduleListJArray = new JSONArray(); // jarray sequence == arraylist sequence for(int i=0;i<moduleList.size();i++){ MeModule mod = moduleList.get(i); moduleListJArray.put(mod.toJson()); } json.put("moduleList",moduleListJArray); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return json; } public MeModule addModule(int type, int port, int slot, int x, int y){ MeModule mod; updateTime = getTime(); switch(type){ case MeModule.DEV_ULTRASOINIC: mod = new MeUltrasonic(port, slot); mod.xPosition = x; mod.yPosition = y; break; case MeModule.DEV_TEMPERATURE: mod = new MeTemperature(port, slot); mod.xPosition = x; mod.yPosition = y; break; case MeModule.DEV_LIGHTSENSOR: mod = new MeLightSensor(port, slot); mod.xPosition = x; mod.yPosition = y; break; case MeModule.DEV_SOUNDSENSOR: mod = new MeSoundSensor(port, slot); mod.xPosition = x; mod.yPosition = y; break; case MeModule.DEV_LINEFOLLOWER: mod = new MeLineFollower(port, slot); mod.xPosition = x; mod.yPosition = y; break; case MeModule.DEV_POTENTIALMETER: mod = new MePotential(port, slot); mod.xPosition = x; mod.yPosition = y; break; case MeModule.DEV_LIMITSWITCH: mod = new MeLimitSwitch(port, slot); mod.xPosition = x; mod.yPosition = y; break; case MeModule.DEV_BUTTON: mod = new MeButton(port, slot); mod.xPosition = x; mod.yPosition = y; break; case MeModule.DEV_PIRMOTION: mod = new MePIRSensor(port, slot); mod.xPosition = x; mod.yPosition = y; break; case MeModule.DEV_GRIPPER_CONTROLLER: case MeModule.DEV_DCMOTOR: mod = new MeGripper(port, slot); mod.xPosition = x; mod.yPosition = y; break; case MeModule.DEV_SERVO: mod = new MeServoMotor(port, slot); mod.xPosition = x; mod.yPosition = y; break; case MeModule.DEV_JOYSTICK: mod = new MeJoystick(port, slot); mod.xPosition = x; mod.yPosition = y; break; case MeModule.DEV_RGBLED: mod = new MeRgbLed(port, slot); mod.xPosition = x; mod.yPosition = y; break; case MeModule.DEV_SEVSEG: mod = new MeDigiSeg(port, slot); mod.xPosition = x; mod.yPosition = y; break; // case MeModule.DEV_GRIPPER_CONTROLLER:{ // // mod = new MeGripper(port, slot); // mod.xPosition = x; // mod.yPosition = y; // } // break; default: Log.i(dbg, "unknow module "+type); mod = new MeModule(updateTime, MeModule.DEV_VERSION, 0, 0); break; } moduleList.add(mod); return mod; } public String toString(){ return this.toJson().toString(); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.index.mapper; import org.apache.lucene.document.Field; import org.apache.lucene.document.InetAddressPoint; import org.apache.lucene.document.SortedSetDocValuesField; import org.apache.lucene.document.StoredField; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.XPointValues; import org.apache.lucene.search.MatchNoDocsQuery; import org.apache.lucene.search.Query; import org.apache.lucene.util.BytesRef; import org.elasticsearch.Version; import org.elasticsearch.action.fieldstats.FieldStats; import org.elasticsearch.common.Explicit; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.network.InetAddresses; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.fielddata.IndexFieldData; import org.elasticsearch.index.fielddata.plain.DocValuesIndexFieldData; import org.elasticsearch.index.mapper.LegacyNumberFieldMapper.Defaults; import org.elasticsearch.index.query.QueryShardContext; import org.elasticsearch.search.DocValueFormat; import org.joda.time.DateTimeZone; import java.io.IOException; import java.net.InetAddress; import java.util.Iterator; import java.util.List; import java.util.Map; /** A {@link FieldMapper} for ip addresses. */ public class IpFieldMapper extends FieldMapper { public static final String CONTENT_TYPE = "ip"; public static class Builder extends FieldMapper.Builder<Builder, IpFieldMapper> { private Boolean ignoreMalformed; public Builder(String name) { super(name, new IpFieldType(), new IpFieldType()); builder = this; } public Builder ignoreMalformed(boolean ignoreMalformed) { this.ignoreMalformed = ignoreMalformed; return builder; } protected Explicit<Boolean> ignoreMalformed(BuilderContext context) { if (ignoreMalformed != null) { return new Explicit<>(ignoreMalformed, true); } if (context.indexSettings() != null) { return new Explicit<>(IGNORE_MALFORMED_SETTING.get(context.indexSettings()), false); } return Defaults.IGNORE_MALFORMED; } @Override public IpFieldMapper build(BuilderContext context) { setupFieldType(context); return new IpFieldMapper(name, fieldType, defaultFieldType, ignoreMalformed(context), includeInAll, context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo); } } public static class TypeParser implements Mapper.TypeParser { public TypeParser() { } @Override public Mapper.Builder<?,?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { if (parserContext.indexVersionCreated().before(Version.V_5_0_0_alpha2)) { return new LegacyIpFieldMapper.TypeParser().parse(name, node, parserContext); } Builder builder = new Builder(name); TypeParsers.parseField(builder, name, node, parserContext); for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, Object> entry = iterator.next(); String propName = entry.getKey(); Object propNode = entry.getValue(); if (propName.equals("null_value")) { if (propNode == null) { throw new MapperParsingException("Property [null_value] cannot be null."); } builder.nullValue(InetAddresses.forString(propNode.toString())); iterator.remove(); } else if (propName.equals("ignore_malformed")) { builder.ignoreMalformed(TypeParsers.nodeBooleanValue("ignore_malformed", propNode, parserContext)); iterator.remove(); } else if (TypeParsers.parseMultiField(builder, name, parserContext, propName, propNode)) { iterator.remove(); } } return builder; } } public static final class IpFieldType extends MappedFieldType { IpFieldType() { super(); setTokenized(false); setHasDocValues(true); } IpFieldType(IpFieldType other) { super(other); } @Override public MappedFieldType clone() { return new IpFieldType(this); } @Override public String typeName() { return CONTENT_TYPE; } private InetAddress parse(Object value) { if (value instanceof InetAddress) { return (InetAddress) value; } else { if (value instanceof BytesRef) { value = ((BytesRef) value).utf8ToString(); } return InetAddresses.forString(value.toString()); } } @Override public Query termQuery(Object value, @Nullable QueryShardContext context) { failIfNotIndexed(); if (value instanceof InetAddress) { return InetAddressPoint.newExactQuery(name(), (InetAddress) value); } else { if (value instanceof BytesRef) { value = ((BytesRef) value).utf8ToString(); } String term = value.toString(); if (term.contains("/")) { String[] fields = term.split("/"); if (fields.length == 2) { InetAddress address = InetAddresses.forString(fields[0]); int prefixLength = Integer.parseInt(fields[1]); return InetAddressPoint.newPrefixQuery(name(), address, prefixLength); } else { throw new IllegalArgumentException("Expected [ip/prefix] but was [" + term + "]"); } } InetAddress address = InetAddresses.forString(term); return InetAddressPoint.newExactQuery(name(), address); } } @Override public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, QueryShardContext context) { failIfNotIndexed(); InetAddress lower; if (lowerTerm == null) { lower = InetAddressPoint.MIN_VALUE; } else { lower = parse(lowerTerm); if (includeLower == false) { if (lower.equals(InetAddressPoint.MAX_VALUE)) { return new MatchNoDocsQuery(); } lower = InetAddressPoint.nextUp(lower); } } InetAddress upper; if (upperTerm == null) { upper = InetAddressPoint.MAX_VALUE; } else { upper = parse(upperTerm); if (includeUpper == false) { if (upper.equals(InetAddressPoint.MIN_VALUE)) { return new MatchNoDocsQuery(); } upper = InetAddressPoint.nextDown(upper); } } return InetAddressPoint.newRangeQuery(name(), lower, upper); } @Override public FieldStats.Ip stats(IndexReader reader) throws IOException { String field = name(); long size = XPointValues.size(reader, field); if (size == 0) { return null; } int docCount = XPointValues.getDocCount(reader, field); byte[] min = XPointValues.getMinPackedValue(reader, field); byte[] max = XPointValues.getMaxPackedValue(reader, field); return new FieldStats.Ip(reader.maxDoc(), docCount, -1L, size, isSearchable(), isAggregatable(), InetAddressPoint.decode(min), InetAddressPoint.decode(max)); } @Override public IndexFieldData.Builder fielddataBuilder() { failIfNoDocValues(); return new DocValuesIndexFieldData.Builder(); } @Override public Object valueForDisplay(Object value) { if (value == null) { return null; } return DocValueFormat.IP.format((BytesRef) value); } @Override public DocValueFormat docValueFormat(@Nullable String format, DateTimeZone timeZone) { if (format != null) { throw new IllegalArgumentException("Field [" + name() + "] of type [" + typeName() + "] does not support custom formats"); } if (timeZone != null) { throw new IllegalArgumentException("Field [" + name() + "] of type [" + typeName() + "] does not support custom time zones"); } return DocValueFormat.IP; } } private Boolean includeInAll; private Explicit<Boolean> ignoreMalformed; private IpFieldMapper( String simpleName, MappedFieldType fieldType, MappedFieldType defaultFieldType, Explicit<Boolean> ignoreMalformed, Boolean includeInAll, Settings indexSettings, MultiFields multiFields, CopyTo copyTo) { super(simpleName, fieldType, defaultFieldType, indexSettings, multiFields, copyTo); this.ignoreMalformed = ignoreMalformed; this.includeInAll = includeInAll; } @Override public IpFieldType fieldType() { return (IpFieldType) super.fieldType(); } @Override protected String contentType() { return fieldType.typeName(); } @Override protected IpFieldMapper clone() { return (IpFieldMapper) super.clone(); } @Override protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException { Object addressAsObject; if (context.externalValueSet()) { addressAsObject = context.externalValue(); } else { addressAsObject = context.parser().textOrNull(); } if (addressAsObject == null) { addressAsObject = fieldType().nullValue(); } if (addressAsObject == null) { return; } String addressAsString = addressAsObject.toString(); InetAddress address; if (addressAsObject instanceof InetAddress) { address = (InetAddress) addressAsObject; } else { try { address = InetAddresses.forString(addressAsString); } catch (IllegalArgumentException e) { if (ignoreMalformed.value()) { return; } else { throw e; } } } if (context.includeInAll(includeInAll, this)) { context.allEntries().addText(fieldType().name(), addressAsString, fieldType().boost()); } if (fieldType().indexOptions() != IndexOptions.NONE) { fields.add(new InetAddressPoint(fieldType().name(), address)); } if (fieldType().hasDocValues()) { fields.add(new SortedSetDocValuesField(fieldType().name(), new BytesRef(InetAddressPoint.encode(address)))); } if (fieldType().stored()) { fields.add(new StoredField(fieldType().name(), new BytesRef(InetAddressPoint.encode(address)))); } } @Override protected void doMerge(Mapper mergeWith, boolean updateAllTypes) { super.doMerge(mergeWith, updateAllTypes); IpFieldMapper other = (IpFieldMapper) mergeWith; this.includeInAll = other.includeInAll; if (other.ignoreMalformed.explicit()) { this.ignoreMalformed = other.ignoreMalformed; } } @Override protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException { super.doXContentBody(builder, includeDefaults, params); if (includeDefaults || fieldType().nullValue() != null) { Object nullValue = fieldType().nullValue(); if (nullValue != null) { nullValue = InetAddresses.toAddrString((InetAddress) nullValue); } builder.field("null_value", nullValue); } if (includeDefaults || ignoreMalformed.explicit()) { builder.field("ignore_malformed", ignoreMalformed.value()); } if (includeInAll != null) { builder.field("include_in_all", includeInAll); } else if (includeDefaults) { builder.field("include_in_all", false); } } }
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.builder.png; import com.android.annotations.NonNull; import com.android.annotations.Nullable; import com.android.builder.tasks.BooleanLatch; import com.android.builder.tasks.Job; import com.android.utils.GrabProcessOutput; import com.android.utils.ILogger; import com.google.common.base.Objects; import com.google.common.base.Strings; import java.io.File; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * interface to the aapt long running process. */ public class AaptProcess { private static final int DEFAULT_SLAVE_APPT_TIMEOUT_IN_SECONDS = 5; private static final int SLAVE_AAPT_TIMEOUT_IN_SECONDS = System.getenv("SLAVE_AAPT_TIMEOUT") == null ? DEFAULT_SLAVE_APPT_TIMEOUT_IN_SECONDS : Integer.parseInt(System.getenv("SLAVE_AAPT_TIMEOUT")); private final Process mProcess; private final ILogger mLogger; private final ProcessOutputFacade mProcessOutputFacade = new ProcessOutputFacade(); private final List<String> mMessages = new ArrayList<String>(); private final AtomicBoolean mReady = new AtomicBoolean(false); private final BooleanLatch mReadyLatch = new BooleanLatch(); private final OutputStreamWriter mWriter; private AaptProcess(@NonNull Process process, @NonNull ILogger iLogger) throws InterruptedException { mProcess = process; mLogger = iLogger; GrabProcessOutput.grabProcessOutput(process, GrabProcessOutput.Wait.ASYNC, mProcessOutputFacade); mWriter = new OutputStreamWriter(mProcess.getOutputStream()); } /** * Notifies the slave process of a new crunching request, do not block on completion, the * notification will be issued through the job parameter's * {@link com.android.builder.tasks.Job#finished()} or * {@link com.android.builder.tasks.Job#error()} * functions. * * @param in the source file to crunch * @param out where to place the crunched file * @param job the job to notify when the crunching is finished successfully or not. * @throws IOException */ public void crunch(@NonNull File in, @NonNull File out, @NonNull Job<AaptProcess> job) throws IOException { mLogger.verbose("Process(" + mProcess.hashCode() + ")" + in.getName() + "job: " + job.toString()); if (!mReady.get()) { throw new RuntimeException("AAPT process not ready to receive commands"); } NotifierProcessOutput notifier = new NotifierProcessOutput(job, mProcessOutputFacade, mLogger); mProcessOutputFacade.setNotifier(notifier); mWriter.write("s\n"); mWriter.write(in.getAbsolutePath()); mWriter.write("\n"); mWriter.write(out.getAbsolutePath()); mWriter.write("\n"); mWriter.flush(); mLogger.verbose("Processed(" + mProcess.hashCode() + ")" + in.getName() + "job: " + job.toString()); mMessages.add("Process(" + mProcess.hashCode() + ") processed " + in.getName() + "job: " + job.toString()); } public void waitForReady() throws InterruptedException { if (!mReadyLatch.await(TimeUnit.NANOSECONDS.convert( SLAVE_AAPT_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS))) { throw new RuntimeException("Timed out while waiting for slave aapt process, " + "try setting environment variable SLAVE_AAPT_TIMEOUT to a value bigger than " + SLAVE_AAPT_TIMEOUT_IN_SECONDS + " seconds"); } mLogger.info("Slave %1$s is ready", hashCode()); } @Override public String toString() { return Objects.toStringHelper(this) .add("ready", mReady.get()) .add("process", mProcess.hashCode()) .toString(); } /** * Shutdowns the slave process and release all resources. * * @throws IOException * @throws InterruptedException */ public void shutdown() throws IOException, InterruptedException { mReady.set(false); mWriter.write("quit\n"); mWriter.flush(); mProcess.waitFor(); mLogger.verbose("Process (%1$s) processed %2$s files", mProcess.hashCode(), mMessages.size()); for (String message : mMessages) { mLogger.verbose(message); } } public static class Builder { private final String mAaptLocation; private final ILogger mLogger; public Builder(@NonNull String aaptPath, @NonNull ILogger iLogger) { mAaptLocation = aaptPath; mLogger = iLogger; } public AaptProcess start() throws IOException, InterruptedException { String[] command = new String[] { mAaptLocation, "m", }; mLogger.verbose("Trying to start %1$s", command[0]); Process process = new ProcessBuilder(command).start(); mLogger.verbose("Started %1$d", process.hashCode()); return new AaptProcess(process, mLogger); } } private class ProcessOutputFacade implements GrabProcessOutput.IProcessOutput { @Nullable NotifierProcessOutput notifier = null; AtomicBoolean ready = new AtomicBoolean(false); synchronized void setNotifier(@NonNull NotifierProcessOutput notifierProcessOutput) { if (notifier != null) { throw new RuntimeException("Notifier already set, threading issue"); } notifier = notifierProcessOutput; } synchronized void reset() { notifier = null; } @Nullable synchronized NotifierProcessOutput getNotifier() { return notifier; } @Override public synchronized void out(@Nullable String line) { // an empty message or aapt startup message are ignored. if (Strings.isNullOrEmpty(line)) { return; } if (line.equals("Ready")) { AaptProcess.this.mReady.set(true); AaptProcess.this.mReadyLatch.signal(); return; } NotifierProcessOutput delegate = getNotifier(); mLogger.verbose("AAPT out(%1$s): %2$s", mProcess.hashCode(), line); if (delegate != null) { mLogger.verbose("AAPT out(%1$s): -> %2$s", mProcess.hashCode(), delegate.mJob); delegate.out(line); } else { mLogger.error(null, "AAPT out(%1$s) : No Delegate set : lost message:%2$s", mProcess.hashCode(), line); } } @Override public synchronized void err(@Nullable String line) { if (Strings.isNullOrEmpty(line)) { return; } NotifierProcessOutput delegate = getNotifier(); if (delegate != null) { mLogger.verbose("AAPT err(%1$s): %2$s -> %3$s", mProcess.hashCode(), line, delegate.mJob); delegate.err(line); } else { if (!mReady.get()) { if (line.equals("ERROR: Unknown command 'm'")) { throw new RuntimeException("Invalid aapt version, version 21 or above is required"); } mLogger.error(null, "AAPT err(%1$s): %2$s", mProcess.hashCode(), line); } else { mLogger.error(null, "AAPT err(%1$s) : No Delegate set : lost message:%2$s", mProcess.hashCode(), line); } } } Process getProcess() { return mProcess; } } private static class NotifierProcessOutput implements GrabProcessOutput.IProcessOutput { @NonNull private final Job<AaptProcess> mJob; @NonNull private final ProcessOutputFacade mOwner; @NonNull private final ILogger mLogger; NotifierProcessOutput( @NonNull Job<AaptProcess> job, @NonNull ProcessOutputFacade owner, @NonNull ILogger iLogger) { mOwner = owner; mJob = job; mLogger = iLogger; } @Override public void out(@Nullable String line) { if (line != null) { mLogger.verbose("AAPT notify(%1$s): %2$s", mJob, line); if (line.equalsIgnoreCase("Done")) { mOwner.reset(); mJob.finished(); } else if (line.equalsIgnoreCase("Error")) { mOwner.reset(); mJob.error(); } else { mLogger.verbose("AAPT(%1$s) discarded: %2$s", mJob, line); } } } @Override public void err(@Nullable String line) { if (line != null) { mLogger.verbose("AAPT warning(%1$s), Job(%2$s): %3$s", mOwner.getProcess().hashCode(), mJob, line); mLogger.warning("AAPT: %3$s", mOwner.getProcess().hashCode(), mJob, line); } } } }
/** * * 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.bookkeeper.bookie.storage.ldb; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.common.collect.Lists; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import java.io.File; import java.io.IOException; import java.util.List; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.bookie.Bookie.NoEntryException; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.bookie.EntryLocation; import org.apache.bookkeeper.bookie.EntryLogger; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.conf.TestBKConfiguration; import org.apache.bookkeeper.proto.BookieProtocol; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Unit test for {@link DbLedgerStorage}. */ public class DbLedgerStorageTest { private DbLedgerStorage storage; private File tmpDir; @Before public void setup() throws Exception { tmpDir = File.createTempFile("bkTest", ".dir"); tmpDir.delete(); tmpDir.mkdir(); File curDir = Bookie.getCurrentDirectory(tmpDir); Bookie.checkDirectoryStructure(curDir); int gcWaitTime = 1000; ServerConfiguration conf = TestBKConfiguration.newServerConfiguration(); conf.setGcWaitTime(gcWaitTime); conf.setLedgerStorageClass(DbLedgerStorage.class.getName()); conf.setLedgerDirNames(new String[] { tmpDir.toString() }); Bookie bookie = new Bookie(conf); storage = (DbLedgerStorage) bookie.getLedgerStorage(); } @After public void teardown() throws Exception { storage.shutdown(); tmpDir.delete(); } @Test public void simple() throws Exception { assertEquals(false, storage.ledgerExists(3)); try { storage.isFenced(3); fail("should have failed"); } catch (Bookie.NoLedgerException nle) { // OK } assertEquals(false, storage.ledgerExists(3)); try { storage.setFenced(3); fail("should have failed"); } catch (Bookie.NoLedgerException nle) { // OK } storage.setMasterKey(3, "key".getBytes()); try { storage.setMasterKey(3, "other-key".getBytes()); fail("should have failed"); } catch (IOException ioe) { assertTrue(ioe.getCause() instanceof BookieException.BookieIllegalOpException); } // setting the same key is NOOP storage.setMasterKey(3, "key".getBytes()); assertEquals(true, storage.ledgerExists(3)); assertEquals(true, storage.setFenced(3)); assertEquals(true, storage.isFenced(3)); assertEquals(false, storage.setFenced(3)); storage.setMasterKey(4, "key".getBytes()); assertEquals(false, storage.isFenced(4)); assertEquals(true, storage.ledgerExists(4)); assertEquals("key", new String(storage.readMasterKey(4))); assertEquals(Lists.newArrayList(4L, 3L), Lists.newArrayList(storage.getActiveLedgersInRange(0, 100))); assertEquals(Lists.newArrayList(4L, 3L), Lists.newArrayList(storage.getActiveLedgersInRange(3, 100))); assertEquals(Lists.newArrayList(3L), Lists.newArrayList(storage.getActiveLedgersInRange(0, 4))); // Add / read entries ByteBuf entry = Unpooled.buffer(1024); entry.writeLong(4); // ledger id entry.writeLong(1); // entry id entry.writeLong(0); // lac entry.writeBytes("entry-1".getBytes()); assertEquals(false, ((DbLedgerStorage) storage).isFlushRequired()); assertEquals(1, storage.addEntry(entry)); assertEquals(true, ((DbLedgerStorage) storage).isFlushRequired()); // Read from write cache ByteBuf res = storage.getEntry(4, 1); assertEquals(entry, res); storage.flush(); assertEquals(false, ((DbLedgerStorage) storage).isFlushRequired()); // Read from db res = storage.getEntry(4, 1); assertEquals(entry, res); try { storage.getEntry(4, 2); fail("Should have thrown exception"); } catch (NoEntryException e) { // ok } ByteBuf entry2 = Unpooled.buffer(1024); entry2.writeLong(4); // ledger id entry2.writeLong(2); // entry id entry2.writeLong(1); // lac entry2.writeBytes("entry-2".getBytes()); storage.addEntry(entry2); // Read last entry in ledger res = storage.getEntry(4, BookieProtocol.LAST_ADD_CONFIRMED); assertEquals(entry2, res); // Read last add confirmed in ledger assertEquals(1L, storage.getLastAddConfirmed(4)); ByteBuf entry3 = Unpooled.buffer(1024); entry3.writeLong(4); // ledger id entry3.writeLong(3); // entry id entry3.writeLong(2); // lac entry3.writeBytes("entry-3".getBytes()); storage.addEntry(entry3); ByteBuf entry4 = Unpooled.buffer(1024); entry4.writeLong(4); // ledger id entry4.writeLong(4); // entry id entry4.writeLong(3); // lac entry4.writeBytes("entry-4".getBytes()); storage.addEntry(entry4); res = storage.getEntry(4, 4); assertEquals(entry4, res); assertEquals(3, storage.getLastAddConfirmed(4)); // Delete assertEquals(true, storage.ledgerExists(4)); storage.deleteLedger(4); assertEquals(false, storage.ledgerExists(4)); // Should not throw exception event if the ledger was deleted storage.getEntry(4, 4); assertEquals(3, storage.getLastAddConfirmed(4)); storage.addEntry(Unpooled.wrappedBuffer(entry2)); res = storage.getEntry(4, BookieProtocol.LAST_ADD_CONFIRMED); assertEquals(entry4, res); assertEquals(3, storage.getLastAddConfirmed(4)); // Get last entry from storage storage.flush(); try { storage.getEntry(4, 4); fail("Should have thrown exception since the ledger was deleted"); } catch (NoEntryException e) { // ok } } @Test public void testBookieCompaction() throws Exception { storage.setMasterKey(4, "key".getBytes()); ByteBuf entry3 = Unpooled.buffer(1024); entry3.writeLong(4); // ledger id entry3.writeLong(3); // entry id entry3.writeBytes("entry-3".getBytes()); storage.addEntry(entry3); // Simulate bookie compaction SingleDirectoryDbLedgerStorage singleDirStorage = ((DbLedgerStorage) storage).getLedgerStorageList().get(0); EntryLogger entryLogger = singleDirStorage.getEntryLogger(); // Rewrite entry-3 ByteBuf newEntry3 = Unpooled.buffer(1024); newEntry3.writeLong(4); // ledger id newEntry3.writeLong(3); // entry id newEntry3.writeBytes("new-entry-3".getBytes()); long location = entryLogger.addEntry(4L, newEntry3, false); List<EntryLocation> locations = Lists.newArrayList(new EntryLocation(4, 3, location)); singleDirStorage.updateEntriesLocations(locations); ByteBuf res = storage.getEntry(4, 3); System.out.println("res: " + ByteBufUtil.hexDump(res)); System.out.println("newEntry3: " + ByteBufUtil.hexDump(newEntry3)); assertEquals(newEntry3, res); } @Test public void doubleDirectory() throws Exception { int gcWaitTime = 1000; File firstDir = new File(tmpDir, "dir1"); File secondDir = new File(tmpDir, "dir2"); ServerConfiguration conf = TestBKConfiguration.newServerConfiguration(); conf.setGcWaitTime(gcWaitTime); conf.setLedgerStorageClass(DbLedgerStorage.class.getName()); conf.setLedgerDirNames(new String[] { firstDir.getCanonicalPath(), secondDir.getCanonicalPath() }); // Should not fail Bookie bookie = new Bookie(conf); assertEquals(2, ((DbLedgerStorage) bookie.getLedgerStorage()).getLedgerStorageList().size()); bookie.shutdown(); } @Test public void testRewritingEntries() throws Exception { storage.setMasterKey(1, "key".getBytes()); try { storage.getEntry(1, -1); fail("Should throw exception"); } catch (Bookie.NoEntryException e) { // ok } ByteBuf entry1 = Unpooled.buffer(1024); entry1.writeLong(1); // ledger id entry1.writeLong(1); // entry id entry1.writeBytes("entry-1".getBytes()); storage.addEntry(entry1); storage.flush(); ByteBuf newEntry1 = Unpooled.buffer(1024); newEntry1.writeLong(1); // ledger id newEntry1.writeLong(1); // entry id newEntry1.writeBytes("new-entry-1".getBytes()); storage.addEntry(newEntry1); storage.flush(); ByteBuf response = storage.getEntry(1, 1); assertEquals(newEntry1, response); } @Test public void testEntriesOutOfOrder() throws Exception { storage.setMasterKey(1, "key".getBytes()); ByteBuf entry2 = Unpooled.buffer(1024); entry2.writeLong(1); // ledger id entry2.writeLong(2); // entry id entry2.writeBytes("entry-2".getBytes()); storage.addEntry(entry2); try { storage.getEntry(1, 1); fail("Entry doesn't exist"); } catch (NoEntryException e) { // Ok, entry doesn't exist } ByteBuf res = storage.getEntry(1, 2); assertEquals(entry2, res); ByteBuf entry1 = Unpooled.buffer(1024); entry1.writeLong(1); // ledger id entry1.writeLong(1); // entry id entry1.writeBytes("entry-1".getBytes()); storage.addEntry(entry1); res = storage.getEntry(1, 1); assertEquals(entry1, res); res = storage.getEntry(1, 2); assertEquals(entry2, res); storage.flush(); res = storage.getEntry(1, 1); assertEquals(entry1, res); res = storage.getEntry(1, 2); assertEquals(entry2, res); } @Test public void testEntriesOutOfOrderWithFlush() throws Exception { storage.setMasterKey(1, "key".getBytes()); ByteBuf entry2 = Unpooled.buffer(1024); entry2.writeLong(1); // ledger id entry2.writeLong(2); // entry id entry2.writeBytes("entry-2".getBytes()); storage.addEntry(entry2); try { storage.getEntry(1, 1); fail("Entry doesn't exist"); } catch (NoEntryException e) { // Ok, entry doesn't exist } ByteBuf res = storage.getEntry(1, 2); assertEquals(entry2, res); res.release(); storage.flush(); try { storage.getEntry(1, 1); fail("Entry doesn't exist"); } catch (NoEntryException e) { // Ok, entry doesn't exist } res = storage.getEntry(1, 2); assertEquals(entry2, res); res.release(); ByteBuf entry1 = Unpooled.buffer(1024); entry1.writeLong(1); // ledger id entry1.writeLong(1); // entry id entry1.writeBytes("entry-1".getBytes()); storage.addEntry(entry1); res = storage.getEntry(1, 1); assertEquals(entry1, res); res.release(); res = storage.getEntry(1, 2); assertEquals(entry2, res); res.release(); storage.flush(); res = storage.getEntry(1, 1); assertEquals(entry1, res); res.release(); res = storage.getEntry(1, 2); assertEquals(entry2, res); res.release(); } @Test public void testAddEntriesAfterDelete() throws Exception { storage.setMasterKey(1, "key".getBytes()); ByteBuf entry0 = Unpooled.buffer(1024); entry0.writeLong(1); // ledger id entry0.writeLong(0); // entry id entry0.writeBytes("entry-0".getBytes()); ByteBuf entry1 = Unpooled.buffer(1024); entry1.writeLong(1); // ledger id entry1.writeLong(1); // entry id entry1.writeBytes("entry-1".getBytes()); storage.addEntry(entry0); storage.addEntry(entry1); storage.flush(); storage.deleteLedger(1); storage.setMasterKey(1, "key".getBytes()); entry0 = Unpooled.buffer(1024); entry0.writeLong(1); // ledger id entry0.writeLong(0); // entry id entry0.writeBytes("entry-0".getBytes()); entry1 = Unpooled.buffer(1024); entry1.writeLong(1); // ledger id entry1.writeLong(1); // entry id entry1.writeBytes("entry-1".getBytes()); storage.addEntry(entry0); storage.addEntry(entry1); assertEquals(entry0, storage.getEntry(1, 0)); assertEquals(entry1, storage.getEntry(1, 1)); storage.flush(); } }
/* * Copyright 2016-present Open Networking Laboratory * * 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.onosproject.openstacknetworking.impl; import com.google.common.base.Strings; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.apache.felix.scr.annotations.Service; import org.onlab.packet.IpAddress; import org.onlab.packet.MacAddress; import org.onlab.packet.VlanId; import org.onlab.util.Tools; import org.onosproject.core.CoreService; import org.onosproject.mastership.MastershipService; import org.onosproject.net.ConnectPoint; import org.onosproject.net.DefaultAnnotations; import org.onosproject.net.Device; import org.onosproject.net.Host; import org.onosproject.net.HostId; import org.onosproject.net.HostLocation; import org.onosproject.net.Port; import org.onosproject.net.device.DeviceEvent; import org.onosproject.net.device.DeviceListener; import org.onosproject.net.device.DeviceService; import org.onosproject.net.host.DefaultHostDescription; import org.onosproject.net.host.HostDescription; import org.onosproject.net.host.HostProvider; import org.onosproject.net.host.HostProviderRegistry; import org.onosproject.net.host.HostProviderService; import org.onosproject.net.host.HostService; import org.onosproject.net.provider.AbstractProvider; import org.onosproject.net.provider.ProviderId; import org.onosproject.openstacknetworking.api.OpenstackNetworkService; import org.onosproject.openstacknode.api.OpenstackNode; import org.onosproject.openstacknode.api.OpenstackNodeEvent; import org.onosproject.openstacknode.api.OpenstackNodeListener; import org.onosproject.openstacknode.api.OpenstackNodeService; import org.openstack4j.model.network.Network; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors; import static org.onlab.util.Tools.groupedThreads; import static org.onosproject.net.AnnotationKeys.PORT_NAME; import static org.onosproject.openstacknetworking.api.Constants.*; import static org.onosproject.openstacknetworking.impl.HostBasedInstancePort.ANNOTATION_CREATE_TIME; import static org.onosproject.openstacknetworking.impl.HostBasedInstancePort.ANNOTATION_NETWORK_ID; import static org.onosproject.openstacknetworking.impl.HostBasedInstancePort.ANNOTATION_PORT_ID; @Service @Component(immediate = true) public final class OpenstackSwitchingHostProvider extends AbstractProvider implements HostProvider { private final Logger log = LoggerFactory.getLogger(getClass()); private static final String PORT_NAME_PREFIX_VM = "tap"; private static final String ERR_ADD_HOST = "Failed to add host: "; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected CoreService coreService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected DeviceService deviceService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected HostProviderRegistry hostProviderRegistry; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected HostService hostService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected MastershipService mastershipService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected OpenstackNetworkService osNetworkService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected OpenstackNodeService osNodeService; private final ExecutorService deviceEventExecutor = Executors.newSingleThreadExecutor(groupedThreads("openstacknetworking", "device-event")); private final ExecutorService configEventExecutor = Executors.newSingleThreadExecutor(groupedThreads("openstacknetworking", "config-event")); private final InternalDeviceListener internalDeviceListener = new InternalDeviceListener(); private final InternalOpenstackNodeListener internalNodeListener = new InternalOpenstackNodeListener(); private HostProviderService hostProvider; /** * Creates OpenStack switching host provider. */ public OpenstackSwitchingHostProvider() { super(new ProviderId("sona", OPENSTACK_NETWORKING_APP_ID)); } @Activate protected void activate() { coreService.registerApplication(OPENSTACK_NETWORKING_APP_ID); deviceService.addListener(internalDeviceListener); osNodeService.addListener(internalNodeListener); hostProvider = hostProviderRegistry.register(this); log.info("Started"); } @Deactivate protected void deactivate() { hostProviderRegistry.unregister(this); osNodeService.removeListener(internalNodeListener); deviceService.removeListener(internalDeviceListener); deviceEventExecutor.shutdown(); configEventExecutor.shutdown(); log.info("Stopped"); } @Override public void triggerProbe(Host host) { // no probe is required } private void processPortAdded(Port port) { // TODO check the node state is COMPLETE org.openstack4j.model.network.Port osPort = osNetworkService.port(port); if (osPort == null) { log.warn(ERR_ADD_HOST + "OpenStack port for {} not found", port); return; } Network osNet = osNetworkService.network(osPort.getNetworkId()); if (osNet == null) { log.warn(ERR_ADD_HOST + "OpenStack network {} not found", osPort.getNetworkId()); return; } if (osPort.getFixedIps().isEmpty()) { log.warn(ERR_ADD_HOST + "no fixed IP for port {}", osPort.getId()); return; } MacAddress macAddr = MacAddress.valueOf(osPort.getMacAddress()); Set<IpAddress> fixedIps = osPort.getFixedIps().stream() .map(ip -> IpAddress.valueOf(ip.getIpAddress())) .collect(Collectors.toSet()); ConnectPoint connectPoint = new ConnectPoint(port.element().id(), port.number()); DefaultAnnotations.Builder annotations = DefaultAnnotations.builder() .set(ANNOTATION_NETWORK_ID, osPort.getNetworkId()) .set(ANNOTATION_PORT_ID, osPort.getId()) .set(ANNOTATION_CREATE_TIME, String.valueOf(System.currentTimeMillis())); HostDescription hostDesc = new DefaultHostDescription( macAddr, VlanId.NONE, new HostLocation(connectPoint, System.currentTimeMillis()), fixedIps, annotations.build()); HostId hostId = HostId.hostId(macAddr); hostProvider.hostDetected(hostId, hostDesc, false); } private void processPortRemoved(Port port) { ConnectPoint connectPoint = new ConnectPoint(port.element().id(), port.number()); hostService.getConnectedHosts(connectPoint).forEach(host -> { hostProvider.hostVanished(host.id()); }); } private class InternalDeviceListener implements DeviceListener { @Override public boolean isRelevant(DeviceEvent event) { Device device = event.subject(); if (!mastershipService.isLocalMaster(device.id())) { // do not allow to proceed without mastership return false; } Port port = event.port(); if (port == null) { return false; } String portName = port.annotations().value(PORT_NAME); if (Strings.isNullOrEmpty(portName) || !portName.startsWith(PORT_NAME_PREFIX_VM)) { // handles Nova created port event only return false; } return true; } @Override public void event(DeviceEvent event) { switch (event.type()) { case PORT_UPDATED: if (!event.port().isEnabled()) { deviceEventExecutor.execute(() -> { log.debug("Instance port {} is removed from {}", event.port().annotations().value(PORT_NAME), event.subject().id()); processPortRemoved(event.port()); }); } else if (event.port().isEnabled()) { deviceEventExecutor.execute(() -> { log.debug("Instance Port {} is detected from {}", event.port().annotations().value(PORT_NAME), event.subject().id()); processPortAdded(event.port()); }); } break; case PORT_ADDED: deviceEventExecutor.execute(() -> { log.debug("Instance port {} is detected from {}", event.port().annotations().value(PORT_NAME), event.subject().id()); processPortAdded(event.port()); }); break; case PORT_REMOVED: deviceEventExecutor.execute(() -> { log.debug("Instance port {} is removed from {}", event.port().annotations().value(PORT_NAME), event.subject().id()); processPortRemoved(event.port()); }); default: break; } } } private class InternalOpenstackNodeListener implements OpenstackNodeListener { @Override public void event(OpenstackNodeEvent event) { OpenstackNode osNode = event.subject(); // TODO check leadership of the node and make only the leader process switch (event.type()) { case OPENSTACK_NODE_COMPLETE: deviceEventExecutor.execute(() -> { log.info("COMPLETE node {} is detected", osNode.hostname()); processCompleteNode(event.subject()); }); break; case OPENSTACK_NODE_INCOMPLETE: log.warn("{} is changed to INCOMPLETE state", osNode); break; case OPENSTACK_NODE_CREATED: case OPENSTACK_NODE_UPDATED: case OPENSTACK_NODE_REMOVED: default: break; } } private void processCompleteNode(OpenstackNode osNode) { deviceService.getPorts(osNode.intgBridge()).stream() .filter(port -> port.annotations().value(PORT_NAME) .startsWith(PORT_NAME_PREFIX_VM) && port.isEnabled()) .forEach(port -> { log.debug("Instance port {} is detected from {}", port.annotations().value(PORT_NAME), osNode.hostname()); processPortAdded(port); }); Tools.stream(hostService.getHosts()) .filter(host -> deviceService.getPort( host.location().deviceId(), host.location().port()) == null) .forEach(host -> { log.info("Remove stale host {}", host.id()); hostProvider.hostVanished(host.id()); }); } } }
/* * 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.wicket.model; import java.io.Serializable; import java.text.MessageFormat; import java.util.Calendar; import java.util.Locale; import org.apache.wicket.Component; import org.apache.wicket.Session; import org.apache.wicket.WicketTestCase; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.basic.Label; import org.junit.Before; import org.junit.Test; /** * Test cases for the {@link StringResourceModel}. * * @author Chris Turner */ public class StringResourceModelTest extends WicketTestCase { private WebPage page; private WeatherStation ws; private IModel<WeatherStation> wsModel; /** * @throws Exception */ @Before public void before() throws Exception { page = new TestPage(); ws = new WeatherStation(); wsModel = new Model<WeatherStation>(ws); } /** */ @Test public void getSimpleResource() { StringResourceModel model = new StringResourceModel("simple.text", page, null); assertEquals("Text should be as expected", "Simple text", model.getString()); assertEquals("Text should be as expected", "Simple text", model.getObject()); } /** */ @Test public void getWrappedOnAssignmentResource() { Label label1 = new Label("resourceModelWithComponent", new StringResourceModel( "wrappedOnAssignment.text", page, null)); page.add(label1); assertEquals("Text should be as expected", "Non-wrapped text", label1.getDefaultModelObject()); Label label2 = new Label("resourceModelWithoutComponent", new StringResourceModel( "wrappedOnAssignment.text", (Component)null, null)); page.add(label2); assertEquals("Text should be as expected", "Wrapped text", label2.getDefaultModelObject()); } /** */ @Test(expected = IllegalArgumentException.class) public void nullResourceKey() { new StringResourceModel(null, page, null); } /** */ @Test public void getSimpleResourceWithKeySubstitution() { StringResourceModel model = new StringResourceModel("weather.${currentStatus}", page, wsModel); assertEquals("Text should be as expected", "It's sunny, wear sunscreen", model.getString()); ws.setCurrentStatus("raining"); assertEquals("Text should be as expected", "It's raining, take an umbrella", model.getString()); } /** */ @Test public void getSimpleResourceWithKeySubstitutionForNonString() { // German uses comma (,) as decimal separator Session.get().setLocale(Locale.GERMAN); StringResourceModel model = new StringResourceModel("weather.${currentTemperature}", page, wsModel); assertEquals("Text should be as expected", "Twenty-five dot seven", model.getString()); } /** */ @Test public void getPropertySubstitutedResource() { tester.getSession().setLocale(Locale.ENGLISH); StringResourceModel model = new StringResourceModel("weather.message", page, wsModel); assertEquals( "Text should be as expected", "Weather station \"Europe's main weather station\" reports that the temperature is 25.7 \u00B0C", model.getString()); ws.setCurrentTemperature(11.5); assertEquals( "Text should be as expected", "Weather station \"Europe's main weather station\" reports that the temperature is 11.5 \u00B0C", model.getString()); } /** */ @Test public void substitutedPropertyAndParameterResource() { StringResourceModel model = new StringResourceModel("weather.mixed", page, wsModel, new PropertyModel<Double>(wsModel, "currentTemperature"), new PropertyModel<String>( wsModel, "units")); MessageFormat format = new MessageFormat( "Weather station \"Europe''s main weather station\" reports that the temperature is {0} {1}", tester.getSession().getLocale()); ws.setCurrentTemperature(25.7); String expected = format.format(new Object[] { 25.7, "\u00B0C" }); assertEquals("Text should be as expected", expected, model.getString()); ws.setCurrentTemperature(11.5); expected = format.format(new Object[] { 11.5, "\u00B0C" }); assertEquals("Text should be as expected", expected, model.getString()); } /** */ @Test public void substitutionParametersResource() { Calendar cal = Calendar.getInstance(); cal.set(2004, Calendar.OCTOBER, 15, 13, 21); MessageFormat format = new MessageFormat( "The report for {0,date,medium}, shows the temperature as {2,number,###.##} {3} and the weather to be {1}", page.getLocale()); StringResourceModel model = new StringResourceModel("weather.detail", page, wsModel, cal.getTime(), "${currentStatus}", new PropertyModel<Double>(wsModel, "currentTemperature"), new PropertyModel<String>(wsModel, "units")); String expected = format.format(new Object[] { cal.getTime(), "sunny", 25.7, "\u00B0C" }); assertEquals("Text should be as expected", expected, model.getString()); ws.setCurrentStatus("raining"); ws.setCurrentTemperature(11.568); expected = format.format(new Object[] { cal.getTime(), "raining", 11.568, "\u00B0C" }); assertEquals("Text should be as expected", expected, model.getString()); } /** */ @Test public void substitutionParametersResourceWithSingleQuote() { tester.getSession().setLocale(Locale.ENGLISH); StringResourceModel model = new StringResourceModel("with.quote", page, null, 10, 20); assertEquals("2010.00", model.getString()); } /** */ @Test public void textResourceWithSubstitutionAndSingleQuote() { tester.getSession().setLocale(Locale.ENGLISH); StringResourceModel model = new StringResourceModel("with.quote.and.no.substitution", page, null, (Object[])null); assertEquals("Let's play in the rain!", model.getString()); model = new StringResourceModel("with.quote.substitution", page, null, new Object[] { "rain!" }); assertEquals("Let's play in the rain!", model.getString()); } /** */ @Test(expected = UnsupportedOperationException.class) public void setObject() { StringResourceModel model = new StringResourceModel("simple.text", page, null); model.setObject("Some value"); } /** */ @Test public void detachAttachDetachableModel() { IModel<WeatherStation> wsDetachModel = new LoadableDetachableModel<WeatherStation>() { private static final long serialVersionUID = 1L; @Override protected WeatherStation load() { return new WeatherStation(); } }; StringResourceModel model = new StringResourceModel("simple.text", page, wsDetachModel); model.getObject(); assertNotNull(model.getLocalizer()); model.detach(); } /** * https://issues.apache.org/jira/browse/WICKET-4323 */ @Test public void detachSubstituteModelFromAssignmentWrapper() { IModel<WeatherStation> nullOnDetachModel = new Model<WeatherStation>() { private static final long serialVersionUID = 1L; @Override public void detach() { setObject(null); } }; nullOnDetachModel.setObject(ws); Label label1 = new Label("resourceModelWithComponent", new StringResourceModel( "wrappedOnAssignment.text", page, nullOnDetachModel)); page.add(label1); label1.getDefaultModelObject(); label1.detach(); assertNull(nullOnDetachModel.getObject()); nullOnDetachModel.setObject(ws); Label label2 = new Label("resourceModelWithoutComponent", new StringResourceModel( "wrappedOnAssignment.text", nullOnDetachModel)); page.add(label2); label2.getDefaultModelObject(); label2.detach(); assertNull(nullOnDetachModel.getObject()); } /** * https://issues.apache.org/jira/browse/WICKET-5176 */ @Test public void detachEvenNotAttached() { Wicket5176Model wrappedModel = new Wicket5176Model(); StringResourceModel stringResourceModel = new StringResourceModel("test", (Component) null, wrappedModel); assertFalse(stringResourceModel.isAttached()); assertTrue(wrappedModel.isAttached()); stringResourceModel.detach(); assertFalse(wrappedModel.isAttached()); } private static class Wicket5176Model implements IModel { private boolean attached = true; @Override public Object getObject() { return null; } @Override public void setObject(Object object) { } @Override public void detach() { attached = false; } private boolean isAttached() { return attached; } } /** * Inner class used for testing. */ public static class WeatherStation implements Serializable { private static final long serialVersionUID = 1L; private final String name = "Europe's main weather station"; private String currentStatus = "sunny"; private double currentTemperature = 25.7; /** * @return status */ public String getCurrentStatus() { return currentStatus; } /** * @param currentStatus */ public void setCurrentStatus(String currentStatus) { this.currentStatus = currentStatus; } /** * @return current temp */ public double getCurrentTemperature() { return currentTemperature; } /** * @param currentTemperature */ public void setCurrentTemperature(double currentTemperature) { this.currentTemperature = currentTemperature; } /** * @return units */ public String getUnits() { return "\u00B0C"; } /** * @return name */ public String getName() { return name; } } /** * Test page. */ public static class TestPage extends WebPage { private static final long serialVersionUID = 1L; /** * Construct. */ public TestPage() { } } }
/* * 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.facebook.presto.operator.aggregation; import com.facebook.presto.array.BlockBigArray; import com.facebook.presto.array.BooleanBigArray; import com.facebook.presto.array.ByteBigArray; import com.facebook.presto.array.DoubleBigArray; import com.facebook.presto.array.LongBigArray; import com.facebook.presto.array.SliceBigArray; import com.facebook.presto.bytecode.DynamicClassLoader; import com.facebook.presto.operator.aggregation.state.LongState; import com.facebook.presto.operator.aggregation.state.NullableLongState; import com.facebook.presto.operator.aggregation.state.StateCompiler; import com.facebook.presto.operator.aggregation.state.VarianceState; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.block.BlockBuilder; import com.facebook.presto.spi.block.BlockBuilderStatus; import com.facebook.presto.spi.block.InterleavedBlockBuilder; import com.facebook.presto.spi.function.AccumulatorState; import com.facebook.presto.spi.function.AccumulatorStateFactory; import com.facebook.presto.spi.function.AccumulatorStateSerializer; import com.facebook.presto.spi.function.GroupedAccumulatorState; import com.facebook.presto.spi.type.Type; import com.facebook.presto.type.ArrayType; import com.facebook.presto.type.RowType; import com.facebook.presto.util.Reflection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.airlift.slice.Slice; import org.openjdk.jol.info.ClassLayout; import org.testng.annotations.Test; import java.lang.invoke.MethodHandle; import java.lang.reflect.Field; import java.util.Map; import java.util.Optional; import static com.facebook.presto.block.BlockAssertions.createLongsBlock; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; import static com.facebook.presto.spi.type.TinyintType.TINYINT; import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static com.facebook.presto.util.StructuralTestUtil.mapType; import static io.airlift.slice.Slices.utf8Slice; import static io.airlift.slice.Slices.wrappedDoubleArray; import static org.testng.Assert.assertEquals; public class TestStateCompiler { private static final int SLICE_INSTANCE_SIZE = ClassLayout.parseClass(Slice.class).instanceSize(); @Test public void testPrimitiveNullableLongSerialization() { AccumulatorStateFactory<NullableLongState> factory = StateCompiler.generateStateFactory(NullableLongState.class); AccumulatorStateSerializer<NullableLongState> serializer = StateCompiler.generateStateSerializer(NullableLongState.class); NullableLongState state = factory.createSingleState(); NullableLongState deserializedState = factory.createSingleState(); state.setLong(2); state.setNull(false); BlockBuilder builder = BIGINT.createBlockBuilder(new BlockBuilderStatus(), 2); serializer.serialize(state, builder); state.setNull(true); serializer.serialize(state, builder); Block block = builder.build(); assertEquals(block.isNull(0), false); assertEquals(BIGINT.getLong(block, 0), state.getLong()); serializer.deserialize(block, 0, deserializedState); assertEquals(deserializedState.getLong(), state.getLong()); assertEquals(block.isNull(1), true); } @Test public void testPrimitiveLongSerialization() { AccumulatorStateFactory<LongState> factory = StateCompiler.generateStateFactory(LongState.class); AccumulatorStateSerializer<LongState> serializer = StateCompiler.generateStateSerializer(LongState.class); LongState state = factory.createSingleState(); LongState deserializedState = factory.createSingleState(); state.setLong(2); BlockBuilder builder = BIGINT.createBlockBuilder(new BlockBuilderStatus(), 1); serializer.serialize(state, builder); Block block = builder.build(); assertEquals(BIGINT.getLong(block, 0), state.getLong()); serializer.deserialize(block, 0, deserializedState); assertEquals(deserializedState.getLong(), state.getLong()); } @Test public void testGetSerializedType() { AccumulatorStateSerializer<LongState> serializer = StateCompiler.generateStateSerializer(LongState.class); assertEquals(serializer.getSerializedType(), BIGINT); } @Test public void testPrimitiveBooleanSerialization() { AccumulatorStateFactory<BooleanState> factory = StateCompiler.generateStateFactory(BooleanState.class); AccumulatorStateSerializer<BooleanState> serializer = StateCompiler.generateStateSerializer(BooleanState.class); BooleanState state = factory.createSingleState(); BooleanState deserializedState = factory.createSingleState(); state.setBoolean(true); BlockBuilder builder = BOOLEAN.createBlockBuilder(new BlockBuilderStatus(), 1); serializer.serialize(state, builder); Block block = builder.build(); serializer.deserialize(block, 0, deserializedState); assertEquals(deserializedState.isBoolean(), state.isBoolean()); } @Test public void testPrimitiveByteSerialization() { AccumulatorStateFactory<ByteState> factory = StateCompiler.generateStateFactory(ByteState.class); AccumulatorStateSerializer<ByteState> serializer = StateCompiler.generateStateSerializer(ByteState.class); ByteState state = factory.createSingleState(); ByteState deserializedState = factory.createSingleState(); state.setByte((byte) 3); BlockBuilder builder = TINYINT.createBlockBuilder(new BlockBuilderStatus(), 1); serializer.serialize(state, builder); Block block = builder.build(); serializer.deserialize(block, 0, deserializedState); assertEquals(deserializedState.getByte(), state.getByte()); } @Test public void testNonPrimitiveSerialization() { AccumulatorStateFactory<SliceState> factory = StateCompiler.generateStateFactory(SliceState.class); AccumulatorStateSerializer<SliceState> serializer = StateCompiler.generateStateSerializer(SliceState.class); SliceState state = factory.createSingleState(); SliceState deserializedState = factory.createSingleState(); state.setSlice(null); BlockBuilder nullBlockBuilder = VARCHAR.createBlockBuilder(new BlockBuilderStatus(), 1); serializer.serialize(state, nullBlockBuilder); Block nullBlock = nullBlockBuilder.build(); serializer.deserialize(nullBlock, 0, deserializedState); assertEquals(deserializedState.getSlice(), state.getSlice()); state.setSlice(utf8Slice("test")); BlockBuilder builder = VARCHAR.createBlockBuilder(new BlockBuilderStatus(), 1); serializer.serialize(state, builder); Block block = builder.build(); serializer.deserialize(block, 0, deserializedState); assertEquals(deserializedState.getSlice(), state.getSlice()); } @Test public void testVarianceStateSerialization() { AccumulatorStateFactory<VarianceState> factory = StateCompiler.generateStateFactory(VarianceState.class); AccumulatorStateSerializer<VarianceState> serializer = StateCompiler.generateStateSerializer(VarianceState.class); VarianceState singleState = factory.createSingleState(); VarianceState deserializedState = factory.createSingleState(); singleState.setMean(1); singleState.setCount(2); singleState.setM2(3); BlockBuilder builder = new RowType(ImmutableList.of(BIGINT, DOUBLE, DOUBLE), Optional.empty()).createBlockBuilder(new BlockBuilderStatus(), 1); serializer.serialize(singleState, builder); Block block = builder.build(); serializer.deserialize(block, 0, deserializedState); assertEquals(deserializedState.getCount(), singleState.getCount()); assertEquals(deserializedState.getMean(), singleState.getMean()); assertEquals(deserializedState.getM2(), singleState.getM2()); } @Test public void testComplexSerialization() { Type arrayType = new ArrayType(BIGINT); Type mapType = mapType(BIGINT, VARCHAR); Map<String, Type> fieldMap = ImmutableMap.of("Block", arrayType, "AnotherBlock", mapType); AccumulatorStateFactory<TestComplexState> factory = StateCompiler.generateStateFactory(TestComplexState.class, fieldMap, new DynamicClassLoader(TestComplexState.class.getClassLoader())); AccumulatorStateSerializer<TestComplexState> serializer = StateCompiler.generateStateSerializer(TestComplexState.class, fieldMap, new DynamicClassLoader(TestComplexState.class.getClassLoader())); TestComplexState singleState = factory.createSingleState(); TestComplexState deserializedState = factory.createSingleState(); singleState.setBoolean(true); singleState.setLong(1); singleState.setDouble(2.0); singleState.setByte((byte) 3); singleState.setSlice(utf8Slice("test")); singleState.setAnotherSlice(wrappedDoubleArray(1.0, 2.0, 3.0)); singleState.setYetAnotherSlice(null); Block array = createLongsBlock(45); singleState.setBlock(array); BlockBuilder mapBlockBuilder = new InterleavedBlockBuilder(ImmutableList.of(BIGINT, VARCHAR), new BlockBuilderStatus(), 1); BIGINT.writeLong(mapBlockBuilder, 123L); VARCHAR.writeSlice(mapBlockBuilder, utf8Slice("testBlock")); Block map = mapBlockBuilder.build(); singleState.setAnotherBlock(map); BlockBuilder builder = new RowType(ImmutableList.of(BOOLEAN, TINYINT, DOUBLE, BIGINT, mapType, VARBINARY, arrayType, VARBINARY, VARBINARY), Optional.empty()) .createBlockBuilder(new BlockBuilderStatus(), 1); serializer.serialize(singleState, builder); Block block = builder.build(); serializer.deserialize(block, 0, deserializedState); assertEquals(deserializedState.getBoolean(), singleState.getBoolean()); assertEquals(deserializedState.getLong(), singleState.getLong()); assertEquals(deserializedState.getDouble(), singleState.getDouble()); assertEquals(deserializedState.getByte(), singleState.getByte()); assertEquals(deserializedState.getSlice(), singleState.getSlice()); assertEquals(deserializedState.getAnotherSlice(), singleState.getAnotherSlice()); assertEquals(deserializedState.getYetAnotherSlice(), singleState.getYetAnotherSlice()); assertEquals(deserializedState.getBlock().getLong(0, 0), singleState.getBlock().getLong(0, 0)); assertEquals(deserializedState.getAnotherBlock().getLong(0, 0), singleState.getAnotherBlock().getLong(0, 0)); assertEquals(deserializedState.getAnotherBlock().getSlice(1, 0, 9), singleState.getAnotherBlock().getSlice(1, 0, 9)); } //see SliceBigArray::getSize private long getSize(Slice slice) { return slice.length() + SLICE_INSTANCE_SIZE; } private long getComplexStateRetainedSize(TestComplexState state) { long retainedSize = ClassLayout.parseClass(state.getClass()).instanceSize(); Field[] fields = state.getClass().getDeclaredFields(); try { for (Field field : fields) { Class type = field.getType(); field.setAccessible(true); if (type == BlockBigArray.class || type == BooleanBigArray.class || type == SliceBigArray.class || type == ByteBigArray.class || type == DoubleBigArray.class || type == LongBigArray.class) { MethodHandle sizeOf = Reflection.methodHandle(type, "sizeOf", null); retainedSize += (long) sizeOf.invokeWithArguments(field.get(state)); } } } catch (Throwable t) { throw new RuntimeException(t); } return retainedSize; } @Test public void testComplexStateEstimatedSize() { Map<String, Type> fieldMap = ImmutableMap.of("Block", new ArrayType(BIGINT), "AnotherBlock", mapType(BIGINT, VARCHAR)); AccumulatorStateFactory<TestComplexState> factory = StateCompiler.generateStateFactory(TestComplexState.class, fieldMap, new DynamicClassLoader(TestComplexState.class.getClassLoader())); TestComplexState groupedState = factory.createGroupedState(); long initialRetainedSize = getComplexStateRetainedSize(groupedState); assertEquals(groupedState.getEstimatedSize(), initialRetainedSize); for (int i = 0; i < 1000; i++) { long retainedSize = 0; ((GroupedAccumulatorState) groupedState).setGroupId(i); groupedState.setBoolean(true); groupedState.setLong(1); groupedState.setDouble(2.0); groupedState.setByte((byte) 3); Slice slice = utf8Slice("test"); retainedSize += getSize(slice); groupedState.setSlice(slice); slice = wrappedDoubleArray(1.0, 2.0, 3.0); retainedSize += getSize(slice); groupedState.setAnotherSlice(slice); groupedState.setYetAnotherSlice(null); Block array = createLongsBlock(45); retainedSize += array.getRetainedSizeInBytes(); groupedState.setBlock(array); BlockBuilder mapBlockBuilder = new InterleavedBlockBuilder(ImmutableList.of(BIGINT, VARCHAR), new BlockBuilderStatus(), 1); BIGINT.writeLong(mapBlockBuilder, 123L); VARCHAR.writeSlice(mapBlockBuilder, utf8Slice("testBlock")); Block map = mapBlockBuilder.build(); retainedSize += map.getRetainedSizeInBytes(); groupedState.setAnotherBlock(map); assertEquals(groupedState.getEstimatedSize(), initialRetainedSize + retainedSize * (i + 1)); } for (int i = 0; i < 1000; i++) { long retainedSize = 0; ((GroupedAccumulatorState) groupedState).setGroupId(i); groupedState.setBoolean(true); groupedState.setLong(1); groupedState.setDouble(2.0); groupedState.setByte((byte) 3); Slice slice = utf8Slice("test"); retainedSize += getSize(slice); groupedState.setSlice(slice); slice = wrappedDoubleArray(1.0, 2.0, 3.0); retainedSize += getSize(slice); groupedState.setAnotherSlice(slice); groupedState.setYetAnotherSlice(null); Block array = createLongsBlock(45); retainedSize += array.getRetainedSizeInBytes(); groupedState.setBlock(array); BlockBuilder mapBlockBuilder = new InterleavedBlockBuilder(ImmutableList.of(BIGINT, VARCHAR), new BlockBuilderStatus(), 1); BIGINT.writeLong(mapBlockBuilder, 123L); VARCHAR.writeSlice(mapBlockBuilder, utf8Slice("testBlock")); Block map = mapBlockBuilder.build(); retainedSize += map.getRetainedSizeInBytes(); groupedState.setAnotherBlock(map); assertEquals(groupedState.getEstimatedSize(), initialRetainedSize + retainedSize * 1000); } } public interface TestComplexState extends AccumulatorState { double getDouble(); void setDouble(double value); boolean getBoolean(); void setBoolean(boolean value); long getLong(); void setLong(long value); byte getByte(); void setByte(byte value); Slice getSlice(); void setSlice(Slice slice); Slice getAnotherSlice(); void setAnotherSlice(Slice slice); Slice getYetAnotherSlice(); void setYetAnotherSlice(Slice slice); Block getBlock(); void setBlock(Block block); Block getAnotherBlock(); void setAnotherBlock(Block block); } public interface BooleanState extends AccumulatorState { boolean isBoolean(); void setBoolean(boolean value); } public interface ByteState extends AccumulatorState { byte getByte(); void setByte(byte value); } public interface SliceState extends AccumulatorState { Slice getSlice(); void setSlice(Slice slice); } }
/* * Copyright 2000-2013 JetBrains s.r.o. * Copyright 2014-2014 AS3Boyan * Copyright 2014-2014 Elias Ku * Copyright 2020 Eric Bishton * * 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.intellij.plugins.haxe.actions; import com.intellij.codeInsight.TargetElementUtil; import com.intellij.plugins.haxe.HaxeCodeInsightFixtureTestCase; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import java.util.Collection; /** * @author: Fedor.Korotkov */ public class HaxeGoToDeclarationActionTest extends HaxeCodeInsightFixtureTestCase { @Override protected String getBasePath() { return "/goto/"; } protected void setUp() throws Exception { useHaxeToolkit(); super.setUp(); } protected void doTest(PsiFile file, int expectedSize) { doTest(new PsiFile[]{file}, expectedSize); } protected void doTest(PsiFile[] files, int expectedSize) { assertNotNull(files); final PsiFile myFile = files[0]; assertNotNull(myFile); final TargetElementUtil util = TargetElementUtil.getInstance(); assertNotNull(util); final PsiReference found = myFile.findReferenceAt(myFixture.getCaretOffset()); assertNotNull(found); final Collection<PsiElement> elements = util.getTargetCandidates(found); assertNotNull(elements); assertEquals(expectedSize, elements.size()); } public void testVarDeclaration() { doTest(myFixture.configureByFiles("VarDeclaration.hx", "com/bar/Foo.hx"), 1); } public void testFunctionParameter() { doTest(myFixture.configureByFiles("FunctionParameter.hx", "com/bar/Foo.hx"), 1); } public void testInterfaceParameter() { doTest(myFixture.configureByFiles("InterfaceDeclaration.hx", "com/bar/IBar.hx"), 1); } public void testForDeclaration1() { doTest(myFixture.configureByFiles("ForDeclaration1.hx"), 1); } public void testForDeclaration2() { doTest(myFixture.configureByFiles("ForDeclaration2.hx"), 1); } public void testLocalVarDeclaration1() { doTest(myFixture.configureByFiles("LocalVarDeclaration1.hx"), 1); } public void testLocalVarDeclaration2() { doTest(myFixture.configureByFiles("LocalVarDeclaration2.hx"), 1); } public void testFunctionParameter1() { doTest(myFixture.configureByFiles("FunctionParameter1.hx"), 1); } public void testFunctionParameter2() { doTest(myFixture.configureByFiles("FunctionParameter2.hx"), 1); } public void testFunctionParameter3() { doTest(myFixture.configureByFiles("FunctionParameter3.hx"), 1); } public void testReference() { doTest(myFixture.configureByFiles("Reference.hx"), 1); } public void testThisExpression() { doTest(myFixture.configureByFiles("ThisExpression.hx"), 1); } public void testThisShadowing() { doTest(myFixture.configureByFiles("ThisShadowing.hx"), 0); } public void testStaticClassMember1() { doTest(myFixture.configureByFiles("StaticClassMember1.hx", "com/bar/Foo.hx"), 1); } public void testStaticClassMember2() { doTest(myFixture.configureByFiles("StaticClassMember2.hx", "com/bar/Foo.hx"), 1); } public void testFunctionCall() { doTest(myFixture.configureByFiles("FunctionCall.hx", "com/utils/MathUtil.hx"), 1); } public void testUsingUtil1() { doTest(myFixture.configureByFiles("UsingUtil1.hx", "com/utils/MathUtil.hx"), 1); } public void testUsingUtil2() { doTest(myFixture.configureByFiles("UsingUtil2.hx", "com/utils/MathUtil.hx"), 0); } public void testUsingUtil3() { doTest(myFixture.configureByFiles("UsingUtil3.hx", "com/utils/StringUtil.hx", "com/utils/Tools.hx", "com/utils/MathUtil.hx"), 1); } public void testSamePackage() { doTest(myFixture.configureByFiles("com/bar/Baz.hx", "com/bar/Foo.hx"), 1); } public void testExternClass1() { doTest(myFixture.configureByFiles("ExternClass1.hx", "com/bar/Foo.hx"), 1); } public void testExternClass2() { doTest(myFixture.configureByFiles("ExternClass2.hx"), 1); } public void testSuperField() { doTest(myFixture.configureByFiles("SuperField.hx", "com/bar/Foo.hx"), 1); } public void testReferenceExpression1() { doTest(myFixture.configureByFiles("ReferenceExpression1.hx", "com/bar/Foo.hx", "com/bar/Baz.hx"), 1); } public void testReferenceExpression2() { doTest(myFixture.configureByFiles("ReferenceExpression2.hx", "com/bar/Foo.hx", "com/bar/Baz.hx"), 1); } public void testReferenceExpression3() { doTest(myFixture.configureByFiles("ReferenceExpression3.hx", "com/bar/Foo.hx", "com/bar/Baz.hx"), 1); } public void testReferenceExpression4() { doTest(myFixture.configureByFiles("ReferenceExpression4.hx", "com/bar/Foo.hx", "com/bar/Baz.hx", "com/bar/IBar.hx", "com/bar/SuperClass.hx"), 1); } public void testReferenceExpression5() { doTest(myFixture.configureByFiles("ReferenceExpression5.hx", "com/bar/Foo.hx"), 1); } public void testReferenceExpression6() { doTest(myFixture.configureByFiles("ReferenceExpression6.hx"), 0); } public void testReferenceExpression7() { doTest(myFixture.configureByFiles("ReferenceExpression7.hx"), 0); } public void testReferenceExpression8() { doTest(myFixture.configureByFiles("ReferenceExpression8.hx"), 0); } public void testReferenceExpression9() { doTest(myFixture.configureByFiles("ReferenceExpression9.hx"), 0); } public void testReferenceExpression10() { doTest(myFixture.configureByFiles("ReferenceExpression10.hx", "com/bar/Foo.hx"), 1); } public void testRegularExpression() { doTest(myFixture.configureByFiles("RegularExpression.hx"), 1); } public void testStringLiteral() { assertNotNull(myFixture); doTest(myFixture.configureByFiles("StringLiteral.hx"), 1); } public void testArrayLiteral() { doTest(myFixture.configureByFiles("ArrayLiteral.hx"), 1); } public void testAssign1() { doTest(myFixture.configureByFiles("Assign1.hx", "com/bar/Foo.hx", "com/bar/Baz.hx"), 1); } public void testAssign2() { doTest(myFixture.configureByFiles("Assign2.hx", "com/bar/Foo.hx", "com/bar/Baz.hx"), 1); } public void testNewExpression1() { doTest(myFixture.configureByFiles("NewExpression1.hx", "com/bar/Foo.hx"), 1); } public void testNewExpression2() { doTest(myFixture.configureByFiles("NewExpression2.hx", "com/bar/Foo.hx"), 1); } public void testCallFunction() { doTest(myFixture.configureByFiles("CallFunction.hx"), 1); } public void testGeneric1() { doTest(myFixture.configureByFiles("Generic1.hx"), 1); } public void testGeneric2() { doTest(myFixture.configureByFiles("Generic2.hx"), 1); } public void testGeneric3() { doTest(myFixture.configureByFiles("Generic3.hx"), 1); } public void testGeneric4() { doTest(myFixture.configureByFiles("Generic4.hx"), 1); } public void testGeneric5() { doTest(myFixture.configureByFiles("Generic5.hx"), 1); } public void testGeneric6() { doTest(myFixture.configureByFiles("Generic6.hx"), 1); } public void testGeneric7() { doTest(myFixture.configureByFiles("Generic7.hx"), 1); } public void testGeneric8() { doTest(myFixture.configureByFiles("Generic8.hx"), 1); } public void testTypeDef1() { doTest(myFixture.configureByFiles("TypeDef1.hx"), 1); } public void testTypeDef2() { doTest(myFixture.configureByFiles("TypeDef2.hx"), 1); } public void testTypeDef3() { doTest(myFixture.configureByFiles("TypeDef3.hx"), 1); } public void testTypeDef4() { doTest(myFixture.configureByFiles("TypeDef4.hx"), 1); } public void testTypeDef5() { doTest(myFixture.configureByFiles("TypeDef5.hx", "com/bar/Foo.hx"), 1); } public void testTypeDef6() { doTest(myFixture.configureByFiles("TypeDef6.hx"), 1); } public void testArrayAccess1() { doTest(myFixture.configureByFiles("ArrayAccess1.hx"), 1); } public void testArrayAccess2() { doTest(myFixture.configureByFiles("ArrayAccess2.hx"), 1); } public void testArrayIteration1() { doTest(myFixture.configureByFiles("ArrayIteration1.hx"), 1); } public void testArrayIteration2() { doTest(myFixture.configureByFiles("ArrayIteration2.hx"), 1); } public void testArrayIteration3() { doTest(myFixture.configureByFiles("ArrayIteration3.hx"), 1); } public void testHelperClass1() { doTest(myFixture.configureByFiles("HelperClass1.hx", "com/utils/MathUtil.hx"), 1); } public void testHelperClass2() { doTest(myFixture.configureByFiles("HelperClass2.hx", "com/utils/MathUtil.hx"), 1); } public void testHelperClass3() { doTest(myFixture.configureByFiles("HelperClass3.hx", "com/utils/MathUtil.hx"), 1); } public void testHelperClass4() { doTest(myFixture.configureByFiles("HelperClass4.hx", "com/utils/MathUtil.hx"), 1); } public void testCastExpression1() { doTest(myFixture.configureByFiles("CastExpression1.hx"), 1); } public void testTypeCheckExpression1() { doTest(myFixture.configureByFiles("TypeCheckExpression1.hx"), 1); } }
/* * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.xml.internal.ws.spi.db; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import javax.xml.bind.JAXBException; import javax.xml.bind.attachment.AttachmentMarshaller; import javax.xml.bind.attachment.AttachmentUnmarshaller; import javax.xml.namespace.NamespaceContext; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.Result; import javax.xml.transform.Source; import org.w3c.dom.Node; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; //import com.sun.xml.internal.ws.spi.db.BindingContext; //import com.sun.xml.internal.ws.spi.db.RepeatedElementBridge; //import com.sun.xml.internal.ws.spi.db.XMLBridge; //import com.sun.xml.internal.ws.spi.db.DatabindingException; //import com.sun.xml.internal.ws.spi.db.TypeInfo; //import com.sun.xml.internal.ws.spi.db.WrapperComposite; /** * WrapperBridge handles RPC-Literal body and Document-Literal wrappers without static * wrapper classes. * * @author shih-chang.chen@oracle.com */ public class WrapperBridge<T> implements XMLBridge<T> { BindingContext parent; TypeInfo typeInfo; static final String WrapperPrefix = "w"; static final String WrapperPrefixColon = WrapperPrefix + ":"; public WrapperBridge(BindingContext p, TypeInfo ti) { this.parent = p; this.typeInfo = ti; } @Override public BindingContext context() { return parent; } @Override public TypeInfo getTypeInfo() { return typeInfo; } @Override public final void marshal(T object, ContentHandler contentHandler, AttachmentMarshaller am) throws JAXBException { WrapperComposite w = (WrapperComposite) object; Attributes att = new Attributes() { @Override public int getLength() { return 0; } @Override public String getURI(int index) { return null; } @Override public String getLocalName(int index) { return null; } @Override public String getQName(int index) { return null; } @Override public String getType(int index) { return null; } @Override public String getValue(int index) { return null; } @Override public int getIndex(String uri, String localName) { return 0; } @Override public int getIndex(String qName) { return 0; } @Override public String getType(String uri, String localName) { return null; } @Override public String getType(String qName) { return null; } @Override public String getValue(String uri, String localName) { return null; } @Override public String getValue(String qName) { return null; } }; try { contentHandler.startPrefixMapping(WrapperPrefix, typeInfo.tagName.getNamespaceURI()); contentHandler.startElement(typeInfo.tagName.getNamespaceURI(), typeInfo.tagName.getLocalPart(), WrapperPrefixColon + typeInfo.tagName.getLocalPart(), att); } catch (SAXException e) { throw new JAXBException(e); } if (w.bridges != null) for (int i = 0; i < w.bridges.length; i++) { if (w.bridges[i] instanceof RepeatedElementBridge) { RepeatedElementBridge rbridge = (RepeatedElementBridge) w.bridges[i]; for (Iterator itr = rbridge.collectionHandler().iterator(w.values[i]); itr.hasNext();) { rbridge.marshal(itr.next(), contentHandler, am); } } else { w.bridges[i].marshal(w.values[i], contentHandler, am); } } try { contentHandler.endElement(typeInfo.tagName.getNamespaceURI(), typeInfo.tagName.getLocalPart(), null); contentHandler.endPrefixMapping(WrapperPrefix); } catch (SAXException e) { throw new JAXBException(e); } // bridge.marshal(object, contentHandler, am); } @Override public void marshal(T object, Node output) throws JAXBException { throw new UnsupportedOperationException(); // bridge.marshal(object, output); // bridge.marshal((T) convert(object), output); } @Override public void marshal(T object, OutputStream output, NamespaceContext nsContext, AttachmentMarshaller am) throws JAXBException { // bridge.marshal((T) convert(object), output, nsContext, am); } @Override public final void marshal(T object, Result result) throws JAXBException { throw new UnsupportedOperationException(); // bridge.marshal(object, result); } @Override public final void marshal(T object, XMLStreamWriter output, AttachmentMarshaller am) throws JAXBException { WrapperComposite w = (WrapperComposite) object; try { // output.writeStartElement(typeInfo.tagName.getNamespaceURI(), typeInfo.tagName.getLocalPart()); // System.out.println(typeInfo.tagName.getNamespaceURI()); //The prefix is to workaround an eclipselink bug String prefix = output.getPrefix(typeInfo.tagName.getNamespaceURI()); if (prefix == null) prefix = WrapperPrefix; output.writeStartElement(prefix, typeInfo.tagName.getLocalPart(), typeInfo.tagName.getNamespaceURI()); output.writeNamespace(prefix, typeInfo.tagName.getNamespaceURI()); // output.writeStartElement("", typeInfo.tagName.getLocalPart(), typeInfo.tagName.getNamespaceURI()); // output.writeDefaultNamespace(typeInfo.tagName.getNamespaceURI()); // System.out.println("======== " + output.getPrefix(typeInfo.tagName.getNamespaceURI())); // System.out.println("======== " + output.getNamespaceContext().getPrefix(typeInfo.tagName.getNamespaceURI())); // System.out.println("======== " + output.getNamespaceContext().getNamespaceURI("")); } catch (XMLStreamException e) { e.printStackTrace(); throw new DatabindingException(e); } if (w.bridges != null) for (int i = 0; i < w.bridges.length; i++) { if (w.bridges[i] instanceof RepeatedElementBridge) { RepeatedElementBridge rbridge = (RepeatedElementBridge) w.bridges[i]; for (Iterator itr = rbridge.collectionHandler().iterator(w.values[i]); itr.hasNext();) { rbridge.marshal(itr.next(), output, am); } } else { w.bridges[i].marshal(w.values[i], output, am); } } try { output.writeEndElement(); } catch (XMLStreamException e) { throw new DatabindingException(e); } } @Override public final T unmarshal(InputStream in) throws JAXBException { //EndpointArgumentsBuilder.RpcLit.readRequest throw new UnsupportedOperationException(); // return bridge.unmarshal(in); } @Override public final T unmarshal(Node n, AttachmentUnmarshaller au) throws JAXBException { //EndpointArgumentsBuilder.RpcLit.readRequest throw new UnsupportedOperationException(); // return bridge.unmarshal(n, au); } @Override public final T unmarshal(Source in, AttachmentUnmarshaller au) throws JAXBException { //EndpointArgumentsBuilder.RpcLit.readRequest throw new UnsupportedOperationException(); // return bridge.unmarshal(in, au); } @Override public final T unmarshal(XMLStreamReader in, AttachmentUnmarshaller au) throws JAXBException { //EndpointArgumentsBuilder.RpcLit.readRequest throw new UnsupportedOperationException(); // return bridge.unmarshal(in, au); } @Override public boolean supportOutputStream() { return false; } }
/* * ****************************************************************************** * Copyright (c) 2013-2014 Gabriele Mariotti. * * 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 it.gmariotti.cardslib.library.internal; import android.content.Context; import android.database.Cursor; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.HashMap; import it.gmariotti.cardslib.library.R; import it.gmariotti.cardslib.library.internal.base.BaseCardCursorAdapter; import it.gmariotti.cardslib.library.view.CardGridView; import it.gmariotti.cardslib.library.view.base.CardViewWrapper; /** * Cursor Adapter for {@link Card} model * <p/> * <p/> * </p> * * @author Gabriele Mariotti (gabri.mariotti@gmail.com) */ public abstract class CardGridCursorAdapter extends BaseCardCursorAdapter { protected static String TAG = "CardGridCursorAdapter"; /** * {@link it.gmariotti.cardslib.library.view.CardGridView} */ protected CardGridView mCardGridView; /** * Internal Map with all Cards. * It uses the card id value as key. */ protected HashMap<String /* id */, Card> mInternalObjects; /** * Recycle */ private boolean recycle = false; // ------------------------------------------------------------- // Constructors // ------------------------------------------------------------- public CardGridCursorAdapter(Context context) { super(context, null, 0); } protected CardGridCursorAdapter(Context context, Cursor c, boolean autoRequery) { super(context, c, autoRequery); } protected CardGridCursorAdapter(Context context, Cursor c, int flags) { super(context, c, flags); } // ------------------------------------------------------------- // Views // ------------------------------------------------------------- @Override public View getView(int position, View convertView, ViewGroup parent) { //Check for recycle if (convertView == null) { recycle = false; } else { recycle = true; } return super.getView(position, convertView, parent); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { int layout = mRowLayoutId; LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); return mInflater.inflate(layout, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { CardViewWrapper mCardView; Card mCard; mCard = (Card) getCardFromCursor(cursor); if (mCard != null) { mCardView = (CardViewWrapper) view.findViewById(R.id.list_cardId); if (mCardView != null) { //It is important to set recycle value for inner layout elements mCardView.setForceReplaceInnerLayout(Card.equalsInnerLayout(mCardView.getCard(), mCard)); //It is important to set recycle value for performance issue mCardView.setRecycle(recycle); //Save original swipeable to prevent cardSwipeListener (listView requires another cardSwipeListener) boolean origianlSwipeable = mCard.isSwipeable(); mCard.setSwipeable(false); mCardView.setCard(mCard); //Set originalValue //mCard.setSwipeable(origianlSwipeable); if (origianlSwipeable) Log.d(TAG, "Swipe action not enabled in this type of view"); //If card has an expandable button override animation if (mCard.getCardHeader() != null && mCard.getCardHeader().isButtonExpandVisible()) { //setupExpandCollapseListAnimation(mCardView); Log.d(TAG, "Expand action not enabled in this type of view"); } //Setup swipeable animation setupSwipeableAnimation(mCard, mCardView); } } } /** * Sets SwipeAnimation on List * * @param card {@link Card} * @param cardView {@link it.gmariotti.cardslib.library.view.CardView} */ protected void setupSwipeableAnimation(final Card card, CardViewWrapper cardView) { cardView.setOnTouchListener(null); } // ------------------------------------------------------------- // Getters and Setters // ------------------------------------------------------------- /** * @return {@link it.gmariotti.cardslib.library.view.CardGridView} */ public CardGridView getCardGridView() { return mCardGridView; } /** * Sets the {@link it.gmariotti.cardslib.library.view.CardListView} * * @param cardGridView cardGridView */ public void setCardGridView(CardGridView cardGridView) { this.mCardGridView = cardGridView; } /** * Indicates if the undo message is enabled after a swipe action * * @return <code>true</code> if the undo message is enabled */ /*public boolean isEnableUndo() { return mEnableUndo; }*/ /** * Enables an undo message after a swipe action * * @param enableUndo <code>true</code> to enable an undo message */ /* public void setEnableUndo(boolean enableUndo) { mEnableUndo = enableUndo; if (enableUndo) { mInternalObjects = new HashMap<String, Card>(); for (int i=0;i<getCount();i++) { Card card = getItem(i); mInternalObjects.put(card.getId(), card); } //Create a UndoController if (mUndoBarController==null){ View undobar = ((Activity)mContext).findViewById(R.id.list_card_undobar); if (undobar != null) { mUndoBarController = new UndoBarController(undobar, this); } } }else{ mUndoBarController=null; } }*/ /** * Return the UndoBarController for undo action * * @return {@link it.gmariotti.cardslib.library.view.listener.UndoBarController} */ /* public UndoBarController getUndoBarController() { return mUndoBarController; }*/ }
/* * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.lang.reflect.InvocationTargetException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.UIManager.LookAndFeelInfo; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.WindowConstants; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.filechooser.FileSystemView; import java.util.ArrayList; import javax.swing.plaf.FileChooserUI; import javax.swing.plaf.basic.BasicFileChooserUI; import java.io.File; import static javax.swing.JFileChooser.*; /** * * A demo which makes extensive use of the file chooser. * * @author Jeff Dinkins */ @SuppressWarnings("serial") public class FileChooserDemo extends JPanel implements ActionListener { public static final String NIMBUS_LAF_NAME = "Nimbus"; private static JFrame frame; private final List<SupportedLaF> supportedLaFs = new ArrayList<SupportedLaF>(); private static SupportedLaF nimbusLaF; private static class SupportedLaF { private final String name; private final LookAndFeel laf; SupportedLaF(String name, LookAndFeel laf) { this.name = name; this.laf = laf; } @Override public String toString() { return name; } } private JButton showButton; private JCheckBox showAllFilesFilterCheckBox; private JCheckBox showImageFilesFilterCheckBox; private JCheckBox showFullDescriptionCheckBox; private JCheckBox useFileViewCheckBox; private JCheckBox useFileSystemViewCheckBox; private JCheckBox accessoryCheckBox; private JCheckBox setHiddenCheckBox; private JCheckBox useEmbedInWizardCheckBox; private JCheckBox useControlsCheckBox; private JCheckBox enableDragCheckBox; private JRadioButton singleSelectionRadioButton; private JRadioButton multiSelectionRadioButton; private JRadioButton openRadioButton; private JRadioButton saveRadioButton; private JRadioButton customButton; private JComboBox lafComboBox; private JRadioButton justFilesRadioButton; private JRadioButton justDirectoriesRadioButton; private JRadioButton bothFilesAndDirectoriesRadioButton; private JTextField customField; private final ExampleFileView fileView; private final ExampleFileSystemView fileSystemView; private final static Dimension hpad10 = new Dimension(10, 1); private final static Dimension vpad20 = new Dimension(1, 20); private final static Dimension vpad7 = new Dimension(1, 7); private final static Dimension vpad4 = new Dimension(1, 4); private final static Insets insets = new Insets(5, 10, 0, 10); private final FilePreviewer previewer; private final JFileChooser chooser; @SuppressWarnings("LeakingThisInConstructor") public FileChooserDemo() { UIManager.LookAndFeelInfo[] installedLafs = UIManager. getInstalledLookAndFeels(); for (UIManager.LookAndFeelInfo lafInfo : installedLafs) { try { Class<?> lnfClass = Class.forName(lafInfo.getClassName()); LookAndFeel laf = (LookAndFeel) (lnfClass.newInstance()); if (laf.isSupportedLookAndFeel()) { String name = lafInfo.getName(); SupportedLaF supportedLaF = new SupportedLaF(name, laf); supportedLaFs.add(supportedLaF); if (NIMBUS_LAF_NAME.equals(name)) { nimbusLaF = supportedLaF; } } } catch (Exception ignored) { // If ANYTHING weird happens, don't add this L&F } } setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); chooser = new JFileChooser(); previewer = new FilePreviewer(chooser); // Create Custom FileView fileView = new ExampleFileView(); fileView.putIcon("jpg", new ImageIcon(getClass().getResource( "/resources/images/jpgIcon.jpg"))); fileView.putIcon("gif", new ImageIcon(getClass().getResource( "/resources/images/gifIcon.gif"))); // Create Custom FileSystemView fileSystemView = new ExampleFileSystemView(); // create a radio listener to listen to option changes OptionListener optionListener = new OptionListener(); // Create options openRadioButton = new JRadioButton("Open"); openRadioButton.setSelected(true); openRadioButton.addActionListener(optionListener); saveRadioButton = new JRadioButton("Save"); saveRadioButton.addActionListener(optionListener); customButton = new JRadioButton("Custom"); customButton.addActionListener(optionListener); customField = new JTextField(8) { @Override public Dimension getMaximumSize() { return new Dimension(getPreferredSize().width, getPreferredSize().height); } }; customField.setText("Doit"); customField.setAlignmentY(JComponent.TOP_ALIGNMENT); customField.setEnabled(false); customField.addActionListener(optionListener); ButtonGroup group1 = new ButtonGroup(); group1.add(openRadioButton); group1.add(saveRadioButton); group1.add(customButton); // filter buttons showAllFilesFilterCheckBox = new JCheckBox("Show \"All Files\" Filter"); showAllFilesFilterCheckBox.addActionListener(optionListener); showAllFilesFilterCheckBox.setSelected(true); showImageFilesFilterCheckBox = new JCheckBox("Show JPG and GIF Filters"); showImageFilesFilterCheckBox.addActionListener(optionListener); showImageFilesFilterCheckBox.setSelected(false); accessoryCheckBox = new JCheckBox("Show Preview"); accessoryCheckBox.addActionListener(optionListener); accessoryCheckBox.setSelected(false); // more options setHiddenCheckBox = new JCheckBox("Show Hidden Files"); setHiddenCheckBox.addActionListener(optionListener); showFullDescriptionCheckBox = new JCheckBox("With File Extensions"); showFullDescriptionCheckBox.addActionListener(optionListener); showFullDescriptionCheckBox.setSelected(true); showFullDescriptionCheckBox.setEnabled(false); useFileViewCheckBox = new JCheckBox("Use FileView"); useFileViewCheckBox.addActionListener(optionListener); useFileViewCheckBox.setSelected(false); useFileSystemViewCheckBox = new JCheckBox("Use FileSystemView", false); useFileSystemViewCheckBox.addActionListener(optionListener); useEmbedInWizardCheckBox = new JCheckBox("Embed in Wizard"); useEmbedInWizardCheckBox.addActionListener(optionListener); useEmbedInWizardCheckBox.setSelected(false); useControlsCheckBox = new JCheckBox("Show Control Buttons"); useControlsCheckBox.addActionListener(optionListener); useControlsCheckBox.setSelected(true); enableDragCheckBox = new JCheckBox("Enable Dragging"); enableDragCheckBox.addActionListener(optionListener); // File or Directory chooser options ButtonGroup group3 = new ButtonGroup(); justFilesRadioButton = new JRadioButton("Just Select Files"); justFilesRadioButton.setSelected(true); group3.add(justFilesRadioButton); justFilesRadioButton.addActionListener(optionListener); justDirectoriesRadioButton = new JRadioButton("Just Select Directories"); group3.add(justDirectoriesRadioButton); justDirectoriesRadioButton.addActionListener(optionListener); bothFilesAndDirectoriesRadioButton = new JRadioButton( "Select Files or Directories"); group3.add(bothFilesAndDirectoriesRadioButton); bothFilesAndDirectoriesRadioButton.addActionListener(optionListener); singleSelectionRadioButton = new JRadioButton("Single Selection", true); singleSelectionRadioButton.addActionListener(optionListener); multiSelectionRadioButton = new JRadioButton("Multi Selection"); multiSelectionRadioButton.addActionListener(optionListener); ButtonGroup group4 = new ButtonGroup(); group4.add(singleSelectionRadioButton); group4.add(multiSelectionRadioButton); // Create show button showButton = new JButton("Show FileChooser"); showButton.addActionListener(this); showButton.setMnemonic('s'); // Create laf combo box lafComboBox = new JComboBox(supportedLaFs.toArray()); lafComboBox.setSelectedItem(nimbusLaF); lafComboBox.setEditable(false); lafComboBox.addActionListener(optionListener); // ******************************************************** // ******************** Dialog Type *********************** // ******************************************************** JPanel control1 = new InsetPanel(insets); control1.setBorder(BorderFactory.createTitledBorder("Dialog Type")); control1.setLayout(new BoxLayout(control1, BoxLayout.Y_AXIS)); control1.add(Box.createRigidArea(vpad20)); control1.add(openRadioButton); control1.add(Box.createRigidArea(vpad7)); control1.add(saveRadioButton); control1.add(Box.createRigidArea(vpad7)); control1.add(customButton); control1.add(Box.createRigidArea(vpad4)); JPanel fieldWrapper = new JPanel(); fieldWrapper.setLayout(new BoxLayout(fieldWrapper, BoxLayout.X_AXIS)); fieldWrapper.setAlignmentX(Component.LEFT_ALIGNMENT); fieldWrapper.add(Box.createRigidArea(hpad10)); fieldWrapper.add(Box.createRigidArea(hpad10)); fieldWrapper.add(customField); control1.add(fieldWrapper); control1.add(Box.createRigidArea(vpad20)); control1.add(Box.createGlue()); // ******************************************************** // ***************** Filter Controls ********************** // ******************************************************** JPanel control2 = new InsetPanel(insets); control2.setBorder(BorderFactory.createTitledBorder("Filter Controls")); control2.setLayout(new BoxLayout(control2, BoxLayout.Y_AXIS)); control2.add(Box.createRigidArea(vpad20)); control2.add(showAllFilesFilterCheckBox); control2.add(Box.createRigidArea(vpad7)); control2.add(showImageFilesFilterCheckBox); control2.add(Box.createRigidArea(vpad4)); JPanel checkWrapper = new JPanel(); checkWrapper.setLayout(new BoxLayout(checkWrapper, BoxLayout.X_AXIS)); checkWrapper.setAlignmentX(Component.LEFT_ALIGNMENT); checkWrapper.add(Box.createRigidArea(hpad10)); checkWrapper.add(Box.createRigidArea(hpad10)); checkWrapper.add(showFullDescriptionCheckBox); control2.add(checkWrapper); control2.add(Box.createRigidArea(vpad20)); control2.add(Box.createGlue()); // ******************************************************** // ****************** Display Options ********************* // ******************************************************** JPanel control3 = new InsetPanel(insets); control3.setBorder(BorderFactory.createTitledBorder("Display Options")); control3.setLayout(new BoxLayout(control3, BoxLayout.Y_AXIS)); control3.add(Box.createRigidArea(vpad20)); control3.add(setHiddenCheckBox); control3.add(Box.createRigidArea(vpad7)); control3.add(useFileViewCheckBox); control3.add(Box.createRigidArea(vpad7)); control3.add(useFileSystemViewCheckBox); control3.add(Box.createRigidArea(vpad7)); control3.add(accessoryCheckBox); control3.add(Box.createRigidArea(vpad7)); control3.add(useEmbedInWizardCheckBox); control3.add(Box.createRigidArea(vpad7)); control3.add(useControlsCheckBox); control3.add(Box.createRigidArea(vpad7)); control3.add(enableDragCheckBox); control3.add(Box.createRigidArea(vpad20)); control3.add(Box.createGlue()); // ******************************************************** // ************* File & Directory Options ***************** // ******************************************************** JPanel control4 = new InsetPanel(insets); control4.setBorder(BorderFactory.createTitledBorder( "File and Directory Options")); control4.setLayout(new BoxLayout(control4, BoxLayout.Y_AXIS)); control4.add(Box.createRigidArea(vpad20)); control4.add(justFilesRadioButton); control4.add(Box.createRigidArea(vpad7)); control4.add(justDirectoriesRadioButton); control4.add(Box.createRigidArea(vpad7)); control4.add(bothFilesAndDirectoriesRadioButton); control4.add(Box.createRigidArea(vpad20)); control4.add(singleSelectionRadioButton); control4.add(Box.createRigidArea(vpad7)); control4.add(multiSelectionRadioButton); control4.add(Box.createRigidArea(vpad20)); control4.add(Box.createGlue()); // ******************************************************** // **************** Look & Feel Switch ******************** // ******************************************************** JPanel panel = new JPanel(); panel.add(new JLabel("Look and Feel: ")); panel.add(lafComboBox); panel.add(showButton); // ******************************************************** // ****************** Wrap 'em all up ********************* // ******************************************************** JPanel wrapper = new JPanel(); wrapper.setLayout(new BoxLayout(wrapper, BoxLayout.X_AXIS)); add(Box.createRigidArea(vpad20)); wrapper.add(Box.createRigidArea(hpad10)); wrapper.add(Box.createRigidArea(hpad10)); wrapper.add(control1); wrapper.add(Box.createRigidArea(hpad10)); wrapper.add(control2); wrapper.add(Box.createRigidArea(hpad10)); wrapper.add(control3); wrapper.add(Box.createRigidArea(hpad10)); wrapper.add(control4); wrapper.add(Box.createRigidArea(hpad10)); wrapper.add(Box.createRigidArea(hpad10)); add(wrapper); add(Box.createRigidArea(vpad20)); add(panel); add(Box.createRigidArea(vpad20)); } public void actionPerformed(ActionEvent e) { if (customButton.isSelected()) { chooser.setApproveButtonText(customField.getText()); } if (chooser.isMultiSelectionEnabled()) { chooser.setSelectedFiles(null); } else { chooser.setSelectedFile(null); } // clear the preview from the previous display of the chooser JComponent accessory = chooser.getAccessory(); if (accessory != null) { ((FilePreviewer) accessory).loadImage(null); } if (useEmbedInWizardCheckBox.isSelected()) { WizardDialog wizard = new WizardDialog(frame, true); wizard.setVisible(true); wizard.dispose(); return; } int retval = chooser.showDialog(frame, null); if (retval == APPROVE_OPTION) { JOptionPane.showMessageDialog(frame, getResultString()); } else if (retval == CANCEL_OPTION) { JOptionPane.showMessageDialog(frame, "User cancelled operation. No file was chosen."); } else if (retval == ERROR_OPTION) { JOptionPane.showMessageDialog(frame, "An error occured. No file was chosen."); } else { JOptionPane.showMessageDialog(frame, "Unknown operation occured."); } } private void resetFileFilters(boolean enableFilters, boolean showExtensionInDescription) { chooser.resetChoosableFileFilters(); if (enableFilters) { FileFilter jpgFilter = createFileFilter( "JPEG Compressed Image Files", showExtensionInDescription, "jpg"); FileFilter gifFilter = createFileFilter("GIF Image Files", showExtensionInDescription, "gif"); FileFilter bothFilter = createFileFilter("JPEG and GIF Image Files", showExtensionInDescription, "jpg", "gif"); chooser.addChoosableFileFilter(bothFilter); chooser.addChoosableFileFilter(jpgFilter); chooser.addChoosableFileFilter(gifFilter); } } private FileFilter createFileFilter(String description, boolean showExtensionInDescription, String... extensions) { if (showExtensionInDescription) { description = createFileNameFilterDescriptionFromExtensions( description, extensions); } return new FileNameExtensionFilter(description, extensions); } private String createFileNameFilterDescriptionFromExtensions( String description, String[] extensions) { String fullDescription = (description == null) ? "(" : description + " ("; // build the description from the extension list fullDescription += "." + extensions[0]; for (int i = 1; i < extensions.length; i++) { fullDescription += ", ."; fullDescription += extensions[i]; } fullDescription += ")"; return fullDescription; } private class WizardDialog extends JDialog implements ActionListener { CardLayout cardLayout; JPanel cardPanel; JLabel messageLabel; JButton backButton, nextButton, closeButton; @SuppressWarnings("LeakingThisInConstructor") WizardDialog(JFrame frame, boolean modal) { super(frame, "Embedded JFileChooser Demo", modal); cardLayout = new CardLayout(); cardPanel = new JPanel(cardLayout); getContentPane().add(cardPanel, BorderLayout.CENTER); messageLabel = new JLabel("", JLabel.CENTER); cardPanel.add(chooser, "fileChooser"); cardPanel.add(messageLabel, "label"); cardLayout.show(cardPanel, "fileChooser"); chooser.addActionListener(this); JPanel buttonPanel = new JPanel(); backButton = new JButton("< Back"); nextButton = new JButton("Next >"); closeButton = new JButton("Close"); buttonPanel.add(backButton); buttonPanel.add(nextButton); buttonPanel.add(closeButton); getContentPane().add(buttonPanel, BorderLayout.SOUTH); backButton.setEnabled(false); getRootPane().setDefaultButton(nextButton); backButton.addActionListener(this); nextButton.addActionListener(this); closeButton.addActionListener(this); pack(); setLocationRelativeTo(frame); } public void actionPerformed(ActionEvent evt) { Object src = evt.getSource(); String cmd = evt.getActionCommand(); if (src == backButton) { back(); } else if (src == nextButton) { FileChooserUI ui = chooser.getUI(); if (ui instanceof BasicFileChooserUI) { // Workaround for bug 4528663. This is necessary to // pick up the contents of the file chooser text field. // This will trigger an APPROVE_SELECTION action. ((BasicFileChooserUI) ui).getApproveSelectionAction(). actionPerformed(null); } else { next(); } } else if (src == closeButton) { close(); } else if (APPROVE_SELECTION.equals(cmd)) { next(); } else if (CANCEL_SELECTION.equals(cmd)) { close(); } } private void back() { backButton.setEnabled(false); nextButton.setEnabled(true); cardLayout.show(cardPanel, "fileChooser"); getRootPane().setDefaultButton(nextButton); chooser.requestFocus(); } private void next() { backButton.setEnabled(true); nextButton.setEnabled(false); messageLabel.setText(getResultString()); cardLayout.show(cardPanel, "label"); getRootPane().setDefaultButton(closeButton); closeButton.requestFocus(); } private void close() { setVisible(false); } @Override public void dispose() { chooser.removeActionListener(this); // The chooser is hidden by CardLayout on remove // so fix it here cardPanel.remove(chooser); chooser.setVisible(true); super.dispose(); } } private String getResultString() { String resultString; String filter; if (chooser.getFileFilter() == null) { filter = ""; } else { filter = chooser.getFileFilter().getDescription(); } String path = null; boolean isDirMode = (chooser.getFileSelectionMode() == DIRECTORIES_ONLY); boolean isMulti = chooser.isMultiSelectionEnabled(); if (isMulti) { File[] files = chooser.getSelectedFiles(); if (files != null && files.length > 0) { path = ""; for (File file : files) { path = path + "<br>" + file.getPath(); } } } else { File file = chooser.getSelectedFile(); if (file != null) { path = "<br>" + file.getPath(); } } if (path != null) { path = path.replace(" ", "&nbsp;"); filter = filter.replace(" ", "&nbsp;"); resultString = "<html>You chose " + (isMulti ? "these" : "this") + " " + (isDirMode ? (isMulti ? "directories" : "directory") : (isMulti ? "files" : "file")) + ": <code>" + path + "</code><br><br>with filter: <br><code>" + filter; } else { resultString = "Nothing was chosen"; } return resultString; } /** An ActionListener that listens to the radio buttons. */ private class OptionListener implements ActionListener { public void actionPerformed(ActionEvent e) { JComponent c = (JComponent) e.getSource(); boolean selected = false; if (c instanceof JToggleButton) { selected = ((JToggleButton) c).isSelected(); } if (c == openRadioButton) { chooser.setDialogType(OPEN_DIALOG); customField.setEnabled(false); repaint(); } else if (c == useEmbedInWizardCheckBox) { useControlsCheckBox.setEnabled(!selected); useControlsCheckBox.setSelected(!selected); chooser.setControlButtonsAreShown(!selected); } else if (c == useControlsCheckBox) { chooser.setControlButtonsAreShown(selected); } else if (c == enableDragCheckBox) { chooser.setDragEnabled(selected); } else if (c == saveRadioButton) { chooser.setDialogType(SAVE_DIALOG); customField.setEnabled(false); repaint(); } else if (c == customButton || c == customField) { customField.setEnabled(true); chooser.setDialogType(CUSTOM_DIALOG); repaint(); } else if (c == showAllFilesFilterCheckBox) { chooser.setAcceptAllFileFilterUsed(selected); } else if (c == showImageFilesFilterCheckBox) { resetFileFilters(selected, showFullDescriptionCheckBox.isSelected()); showFullDescriptionCheckBox.setEnabled(selected); } else if (c == setHiddenCheckBox) { chooser.setFileHidingEnabled(!selected); } else if (c == accessoryCheckBox) { if (selected) { chooser.setAccessory(previewer); } else { chooser.setAccessory(null); } } else if (c == useFileViewCheckBox) { if (selected) { chooser.setFileView(fileView); } else { chooser.setFileView(null); } } else if (c == useFileSystemViewCheckBox) { if (selected) { chooser.setFileSystemView(fileSystemView); } else { // Restore default behaviour chooser.setFileSystemView(FileSystemView.getFileSystemView()); } } else if (c == showFullDescriptionCheckBox) { resetFileFilters(showImageFilesFilterCheckBox.isSelected(), selected); } else if (c == justFilesRadioButton) { chooser.setFileSelectionMode(FILES_ONLY); } else if (c == justDirectoriesRadioButton) { chooser.setFileSelectionMode(DIRECTORIES_ONLY); } else if (c == bothFilesAndDirectoriesRadioButton) { chooser.setFileSelectionMode(FILES_AND_DIRECTORIES); } else if (c == singleSelectionRadioButton) { if (selected) { chooser.setMultiSelectionEnabled(false); } } else if (c == multiSelectionRadioButton) { if (selected) { chooser.setMultiSelectionEnabled(true); } } else if (c == lafComboBox) { SupportedLaF supportedLaF = ((SupportedLaF) lafComboBox. getSelectedItem()); LookAndFeel laf = supportedLaF.laf; try { UIManager.setLookAndFeel(laf); SwingUtilities.updateComponentTreeUI(frame); if (chooser != null) { SwingUtilities.updateComponentTreeUI(chooser); } frame.pack(); } catch (UnsupportedLookAndFeelException exc) { // This should not happen because we already checked ((DefaultComboBoxModel) lafComboBox.getModel()). removeElement(supportedLaF); } } } } private class FilePreviewer extends JComponent implements PropertyChangeListener { ImageIcon thumbnail = null; @SuppressWarnings("LeakingThisInConstructor") public FilePreviewer(JFileChooser fc) { setPreferredSize(new Dimension(100, 50)); fc.addPropertyChangeListener(this); } public void loadImage(File f) { if (f == null) { thumbnail = null; } else { ImageIcon tmpIcon = new ImageIcon(f.getPath()); if (tmpIcon.getIconWidth() > 90) { thumbnail = new ImageIcon( tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT)); } else { thumbnail = tmpIcon; } } } public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if (SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) { if (isShowing()) { loadImage((File) e.getNewValue()); repaint(); } } } @Override public void paint(Graphics g) { if (thumbnail != null) { int x = getWidth() / 2 - thumbnail.getIconWidth() / 2; int y = getHeight() / 2 - thumbnail.getIconHeight() / 2; if (y < 0) { y = 0; } if (x < 5) { x = 5; } thumbnail.paintIcon(this, g, x, y); } } } public static void main(String s[]) { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { /* * NOTE: By default, the look and feel will be set to the * Cross Platform Look and Feel (which is currently Metal). * The following code tries to set the Look and Feel to Nimbus. * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/nimbus.html */ try { for (LookAndFeelInfo info : UIManager. getInstalledLookAndFeels()) { if (NIMBUS_LAF_NAME.equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception ignored) { } FileChooserDemo panel = new FileChooserDemo(); frame = new JFrame("FileChooserDemo"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add("Center", panel); frame.pack(); frame.setVisible(true); } }); } catch (InterruptedException ex) { Logger.getLogger(FileChooserDemo.class.getName()).log(Level.SEVERE, null, ex); } catch (InvocationTargetException ex) { Logger.getLogger(FileChooserDemo.class.getName()).log(Level.SEVERE, null, ex); } } private static class InsetPanel extends JPanel { Insets i; InsetPanel(Insets i) { this.i = i; } @Override public Insets getInsets() { return i; } } }
package org.sagebionetworks.bridge; import static com.google.common.base.Preconditions.checkNotNull; import static org.sagebionetworks.bridge.TestConstants.TEST_STUDY_IDENTIFIER; import java.util.HashSet; import java.util.List; import java.util.Set; import org.sagebionetworks.bridge.models.CriteriaContext; import org.sagebionetworks.bridge.models.accounts.AccountId; import org.sagebionetworks.bridge.models.accounts.SignIn; import org.sagebionetworks.bridge.models.accounts.StudyParticipant; import org.sagebionetworks.bridge.models.accounts.UserSession; import org.sagebionetworks.bridge.models.studies.Study; import org.sagebionetworks.bridge.models.studies.StudyIdentifier; import org.sagebionetworks.bridge.models.subpopulations.SubpopulationGuid; import org.sagebionetworks.bridge.services.AuthenticationService; import org.sagebionetworks.bridge.services.StudyService; import org.sagebionetworks.bridge.services.UserAdminService; import com.google.common.collect.Sets; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * A support class that can be injected into any SpringJUnit4ClassRunner test that needs to * create a test user before performing some tests. After (in a @Before method or a finally * block), call deleteUser() with the TestUser object that was returned, and the user will * be deleted (if there's a session, the session will also be cleaned up). */ @Component public class TestUserAdminHelper { private static final String PASSWORD = "P4ssword!"; UserAdminService userAdminService; AuthenticationService authService; StudyService studyService; public class TestUser { private final Study study; private final UserSession session; public TestUser(Study study, UserSession session) { this.study = study; this.session = session; } public StudyParticipant getStudyParticipant() { return session.getParticipant(); } public SignIn getSignIn() { return new SignIn.Builder().withStudy(study.getIdentifier()).withEmail(getStudyParticipant().getEmail()) .withPassword(getStudyParticipant().getPassword()).build(); } public String getEmail() { return getStudyParticipant().getEmail(); } public String getPassword() { return getStudyParticipant().getPassword(); } public UserSession getSession() { return session; } public String getSessionToken() { return (session == null) ? null : session.getSessionToken(); } public Study getStudy() { return study; } public String getHealthCode() { return (session == null) ? null : session.getHealthCode(); } public String getId() { return (session == null) ? null : session.getId(); } public StudyIdentifier getStudyIdentifier() { return study.getStudyIdentifier(); } public AccountId getAccountId() { return AccountId.forId(study.getIdentifier(), getStudyParticipant().getId()); } public CriteriaContext getCriteriaContext() { return new CriteriaContext.Builder() .withLanguages(session.getParticipant().getLanguages()) .withHealthCode(session.getHealthCode()) .withUserId(session.getId()) .withStudyIdentifier(study.getStudyIdentifier()) .withUserDataGroups(session.getParticipant().getDataGroups()) .build(); } } @Autowired public final void setUserAdminService(UserAdminService userAdminService) { this.userAdminService = userAdminService; } @Autowired public final void setAuthService(AuthenticationService authService) { this.authService = authService; } @Autowired public final void setStudyService(StudyService studyService) { this.studyService = studyService; } public Builder getBuilder(Class<?> cls) { checkNotNull(cls); return new Builder(cls); } public void deleteUser(TestUser testUser) { checkNotNull(testUser); String userId = testUser.getId(); if (testUser.getSession() != null) { authService.signOut(testUser.getSession()); } deleteUser(testUser.getStudy(), userId); } public void deleteUser(Study study, String id) { checkNotNull(study); checkNotNull(id); userAdminService.deleteUser(study, id); } public class Builder { private Class<?> cls; private Study study; private SubpopulationGuid subpopGuid; private boolean signIn; private boolean consent; private Set<Roles> roles; private Set<String> dataGroups; private String email; private String password; private List<String> languages; private Builder(Class<?> cls) { this.cls = cls; this.signIn = true; this.consent = true; } public Builder withStudy(Study study) { this.study = study; return this; } public Builder withSignIn(boolean signIn) { this.signIn = signIn; return this; } public Builder withGuid(SubpopulationGuid subpopGuid) { this.subpopGuid = subpopGuid; return this; } public Builder withConsent(boolean consent) { this.consent = consent; return this; } public Builder withRoles(Set<Roles> roles) { this.roles = Sets.newHashSet(roles); return this; } public Builder withRoles(Roles... roles) { this.roles = Sets.newHashSet(roles); return this; } public Builder withDataGroups(Set<String> dataGroups) { this.dataGroups = dataGroups; return this; } public Builder withLanguages(List<String> languages) { this.languages = languages; return this; } public Builder withEmail(String email) { this.email = email; return this; } public Builder withPassword(String password) { this.password = password; return this; } public TestUser build() { // There are tests where we partially create a user with the builder, then change just // some fields before creating another test user with multiple build() calls. Anything we // default in thie build method needs to be updated with each call to build(). Study finalStudy = (study == null) ? studyService.getStudy(TEST_STUDY_IDENTIFIER) : study; String finalEmail = (email == null) ? TestUtils.makeRandomTestEmail(cls) : email; String finalPassword = (password == null) ? PASSWORD : password; // Add the "test_user" data group to all test users. if (dataGroups == null) { dataGroups = new HashSet<String>(); } dataGroups.add(BridgeConstants.TEST_USER_GROUP); StudyParticipant finalParticipant = new StudyParticipant.Builder().withEmail(finalEmail) .withPassword(finalPassword).withRoles(roles).withLanguages(languages).withDataGroups(dataGroups) .build(); UserSession session = userAdminService.createUser( finalStudy, finalParticipant, subpopGuid, signIn, consent); // fix some stuff. In the admin/test path, we want to refer to the password after-the-fact. StudyParticipant newParticipant = new StudyParticipant.Builder() .copyOf(session.getParticipant()) .withPassword(finalParticipant.getPassword()) .build(); session.setParticipant(newParticipant); return new TestUser(finalStudy, session); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.rackspace.cloudloadbalancers.v1.domain; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import org.jclouds.rackspace.cloudloadbalancers.v1.domain.internal.BaseNode; import com.google.common.base.Objects; import com.google.common.base.Objects.ToStringHelper; /** * The nodes defined by the load balancer are responsible for servicing the requests received * through the load balancer's virtual IP. By default, the load balancer employs a basic health * check that ensures the node is listening on its defined port. The node is checked at the time of * addition and at regular intervals as defined by the load balancer health check configuration. If * a back-end node is not listening on its port or does not meet the conditions of the defined * active health check for the load balancer, then the load balancer will not forward connections * and its status will be listed as OFFLINE. Only nodes that are in an ONLINE status will receive * and be able to service traffic from the load balancer. * <p/> * All nodes have an associated status that indicates whether the node is ONLINE, OFFLINE, or * DRAINING. Only nodes that are in ONLINE status will receive and be able to service traffic from * the load balancer. The OFFLINE status represents a node that cannot accept or service traffic. A * node in DRAINING status represents a node that stops the traffic manager from sending any * additional new connections to the node, but honors established sessions. If the traffic manager * receives a request and session persistence requires that the node is used, the traffic manager * will use it. The status is determined by the passive or active health monitors. * <p/> * If the WEIGHTED_ROUND_ROBIN load balancer algorithm mode is selected, then the caller should * assign the relevant weights to the node as part of the weight attribute of the node element. When * the algorithm of the load balancer is changed to WEIGHTED_ROUND_ROBIN and the nodes do not * already have an assigned weight, the service will automatically set the weight to "1" for all * nodes. */ public class Node extends BaseNode<Node> { private int id; private Status status; private Metadata metadata = new Metadata(); // for serialization only protected Node() { } public Node(String address, int port, Condition condition, Type type, Integer weight, int id, Status status, Metadata metadata) { super(address, port, condition, type, weight); checkArgument(id != -1, "id must be specified"); this.id = id; this.status = checkNotNull(status, "status"); this.metadata = metadata != null ? metadata : this.metadata; } public int getId() { return id; } public Status getStatus() { return status; } public Metadata getMetadata() { return metadata; } protected ToStringHelper string() { return Objects.toStringHelper(this).omitNullValues() .add("id", id).add("address", address).add("port", port).add("condition", condition) .add("type", type).add("weight", weight).add("status", status).add("metadata", metadata); } @Override public String toString() { return string().toString(); } @Override public int hashCode() { return Objects.hashCode(id); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Node that = Node.class.cast(obj); return Objects.equal(this.id, that.id); } /** * The status is determined by the passive or active health monitors. */ public static enum Status { /** * Only nodes that are in an ONLINE status will receive and be able to service traffic from * the load balancer. */ ONLINE, /** * Represents a node that cannot accept or service traffic. */ OFFLINE, /** * Represents a node that stops the traffic manager from sending any additional new * connections to the node, but honors established sessions. */ DRAINING, UNRECOGNIZED; public static Status fromValue(String status) { try { return valueOf(checkNotNull(status, "status")); } catch (IllegalArgumentException e) { return UNRECOGNIZED; } } } public static class Builder extends BaseNode.Builder<Node> { private int id = -1; private Status status; private Metadata metadata; public Builder id(int id) { this.id = id; return this; } /** * @see Status */ public Builder status(Status status) { this.status = status; return this; } public Builder metadata(Metadata metadata) { this.metadata = checkNotNull(metadata, "metadata"); return this; } @Override public Node build() { return new Node(address, port, condition, type, weight, id, status, metadata); } /** * {@inheritDoc} */ @Override public Builder address(String address) { return Builder.class.cast(super.address(address)); } /** * {@inheritDoc} */ @Override public Builder condition(Condition condition) { return Builder.class.cast(super.condition(condition)); } /** * {@inheritDoc} */ @Override public Builder type(Type type) { return Builder.class.cast(super.type(type)); } /** * {@inheritDoc} */ @Override public Builder port(int port) { return Builder.class.cast(super.port(port)); } /** * {@inheritDoc} */ @Override public Builder weight(Integer weight) { return Builder.class.cast(super.weight(weight)); } @Override public Builder from(Node in) { return Builder.class.cast(super.from(in)).id(in.getId()).status(in.getStatus()).metadata(in.getMetadata()); } } @SuppressWarnings("unchecked") public static Builder builder() { return new Builder(); } @Override public Builder toBuilder() { return new Builder().from(this); } }
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.server; import org.openqa.selenium.Capabilities; import org.openqa.selenium.server.browserlaunchers.BrowserLauncher; import org.openqa.selenium.remote.SessionId; import org.openqa.selenium.remote.server.log.LoggingManager; import org.openqa.selenium.remote.server.log.PerSessionLogHandler; import org.openqa.selenium.server.browserlaunchers.BrowserLauncherFactory; import org.openqa.selenium.server.browserlaunchers.InvalidBrowserExecutableException; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; /** * Manages browser sessions, their creation, and their closure. * <p> * Maintains a cache of unused and available browser sessions in case the server is reusing * sessions. Also manages the creation and finalization of all browser sessions. * * @author jbevan@google.com (Jennifer Bevan) */ public class BrowserSessionFactory { private static final long DEFAULT_CLEANUP_INTERVAL = 300000; // 5 minutes. private static final long DEFAULT_MAX_IDLE_SESSION_TIME = 600000; // 10 minutes private static Logger log = Logger.getLogger(BrowserSessionFactory.class.getName()); // cached, unused, already-launched browser sessions. protected final Set<BrowserSessionInfo> availableSessions = Collections.synchronizedSet(new HashSet<BrowserSessionInfo>()); // active browser sessions. protected final Set<BrowserSessionInfo> activeSessions = Collections.synchronizedSet(new HashSet<BrowserSessionInfo>()); private final BrowserLauncherFactory browserLauncherFactory; private final Timer cleanupTimer; private final long maxIdleSessionTime; private final boolean doCleanup; public BrowserSessionFactory(BrowserLauncherFactory blf) { this(blf, DEFAULT_CLEANUP_INTERVAL, DEFAULT_MAX_IDLE_SESSION_TIME, true); } /** * Constructor for testing purposes. * * @param blf an injected BrowserLauncherFactory. * @param cleanupInterval the time between idle available session cleaning sweeps. * @param maxIdleSessionTime the max time in ms for an available session to be idle. * @param doCleanup whether or not the idle session cleanup thread should run. */ protected BrowserSessionFactory(BrowserLauncherFactory blf, long cleanupInterval, long maxIdleSessionTime, boolean doCleanup) { browserLauncherFactory = blf; this.maxIdleSessionTime = maxIdleSessionTime; this.doCleanup = doCleanup; cleanupTimer = new Timer(/* daemon= */true); if (doCleanup) { cleanupTimer.schedule(new CleanupTask(), 0, cleanupInterval); } } /** * Gets a new browser session, using the SeleniumServer static fields to populate parameters. * * @param browserString browser name string * @param startURL starting url * @param extensionJs per-session user extension Javascript * @param configuration Remote Control configuration. Cannot be null. * @param browserConfigurations capabilities of requested browser * @return the BrowserSessionInfo for the new browser session. * @throws RemoteCommandException remote command exception if new session fails */ public BrowserSessionInfo getNewBrowserSession(String browserString, String startURL, String extensionJs, Capabilities browserConfigurations, RemoteControlConfiguration configuration) throws RemoteCommandException { return getNewBrowserSession(browserString, startURL, extensionJs, browserConfigurations, configuration.reuseBrowserSessions(), configuration.isEnsureCleanSession(), configuration); } /** * Gets a new browser session * * @param browserString browser name string * @param startURL starting url * @param extensionJs per-session user extension Javascript * @param configuration Remote Control configuration. Cannot be null. * @param useCached if a cached session should be used if one is available * @param ensureClean if a clean session (e.g. no previous cookies) is required. * @param browserConfigurations capabilities of requested browser * @return the BrowserSessionInfo for the new browser session. * @throws RemoteCommandException remote command exception if new session fails */ protected BrowserSessionInfo getNewBrowserSession(String browserString, String startURL, String extensionJs, Capabilities browserConfigurations, boolean useCached, boolean ensureClean, RemoteControlConfiguration configuration) throws RemoteCommandException { BrowserSessionInfo sessionInfo = null; browserString = validateBrowserString(browserString, configuration); if (configuration.getProxyInjectionModeArg()) { InjectionHelper.setBrowserSideLogEnabled(configuration.isBrowserSideLogEnabled()); InjectionHelper.init(); } if (useCached) { log.info("grabbing available session..."); sessionInfo = grabAvailableSession(browserString, startURL); } // couldn't find one in the cache, or not reusing sessions. if (null == sessionInfo) { log.info("creating new remote session"); sessionInfo = createNewRemoteSession(browserString, startURL, extensionJs, browserConfigurations, ensureClean, configuration); } assert null != sessionInfo; if (false/* ensureClean */) { // need to add this to the launcher API. // sessionInfo.launcher.hideCurrentSessionData(); } return sessionInfo; } /** * Ends all browser sessions. * <p> * Active and available but inactive sessions are ended. * @param configuration remote control configuration */ protected void endAllBrowserSessions(RemoteControlConfiguration configuration) { boolean done = false; Set<BrowserSessionInfo> allSessions = new HashSet<>(); while (!done) { // to avoid concurrent modification exceptions... synchronized (activeSessions) { for (BrowserSessionInfo sessionInfo : activeSessions) { allSessions.add(sessionInfo); } } synchronized (availableSessions) { for (BrowserSessionInfo sessionInfo : availableSessions) { allSessions.add(sessionInfo); } } for (BrowserSessionInfo sessionInfo : allSessions) { endBrowserSession(true, sessionInfo.sessionId, configuration); } done = (0 == activeSessions.size() && 0 == availableSessions.size()); allSessions.clear(); if (doCleanup) { cleanupTimer.cancel(); } } } /** * Ends a browser session, using SeleniumServer static fields to populate parameters. * * @param sessionId the id of the session to be ended * @param configuration Remote Control configuration. Cannot be null. */ public void endBrowserSession(String sessionId, RemoteControlConfiguration configuration) { endBrowserSession(false, sessionId, configuration, configuration.isEnsureCleanSession()); } /** * Ends a browser session, using SeleniumServer static fields to populate parameters. * * @param forceClose if the session should not be reused * @param sessionId the id of the session to be ended * @param configuration Remote Control configuration. Cannot be null. */ public void endBrowserSession(boolean forceClose, String sessionId, RemoteControlConfiguration configuration) { endBrowserSession(forceClose, sessionId, configuration, configuration.isEnsureCleanSession()); } /** * Ends a browser session. * * @param forceClose if the session should not be reused * @param sessionId the id of the session to be ended * @param configuration Remote Control configuration. Cannot be null. * @param ensureClean if clean sessions (e.g. no leftover cookies) are required. */ protected void endBrowserSession(boolean forceClose, String sessionId, RemoteControlConfiguration configuration, boolean ensureClean) { BrowserSessionInfo sessionInfo = lookupInfoBySessionId(sessionId, activeSessions); if (null != sessionInfo) { activeSessions.remove(sessionInfo); try { if (forceClose || !configuration.reuseBrowserSessions()) { shutdownBrowserAndClearSessionData(sessionInfo); } else { if (null != sessionInfo.session) { // optional field sessionInfo.session.reset(sessionInfo.baseUrl); } // mark what time this session was ended sessionInfo.lastClosedAt = System.currentTimeMillis(); availableSessions.add(sessionInfo); } } finally { LoggingManager.perSessionLogHandler().removeSessionLogs(new SessionId(sessionId)); if (ensureClean) { // need to add this to the launcher API. // sessionInfo.launcher.restoreOriginalSessionData(); } } } else { // look for it in the available sessions. sessionInfo = lookupInfoBySessionId(sessionId, availableSessions); if (null != sessionInfo && (forceClose || !configuration.reuseBrowserSessions())) { try { availableSessions.remove(sessionInfo); shutdownBrowserAndClearSessionData(sessionInfo); } finally { LoggingManager.perSessionLogHandler().removeSessionLogs(new SessionId(sessionId)); if (ensureClean) { // sessionInfo.launcher.restoreOriginalSessionData(); } } } } } /** * Shuts down this browser session's launcher and clears out its session data (if session is not * null). * * @param sessionInfo the browser session to end. */ protected void shutdownBrowserAndClearSessionData(BrowserSessionInfo sessionInfo) { try { sessionInfo.launcher.close(); // can throw RuntimeException } finally { if (null != sessionInfo.session) { FrameGroupCommandQueueSet.clearQueueSet(sessionInfo.sessionId); } } } /** * Rewrites the given browser string based on server settings. * * @param inputString the input browser string * @return a possibly-modified browser string. * @throws IllegalArgumentException if inputString is null. */ private String validateBrowserString(String inputString, RemoteControlConfiguration configuration) throws IllegalArgumentException { String browserString = inputString; if (configuration.getForcedBrowserMode() != null) { browserString = configuration.getForcedBrowserMode(); log.info("overriding browser mode w/ forced browser mode setting: " + browserString); } if (configuration.getProxyInjectionModeArg() && browserString.equals("*iexplore")) { log.warning("running in proxy injection mode, but you used a *iexplore browser string; this is " + "almost surely inappropriate, so I'm changing it to *piiexplore..."); browserString = "*piiexplore"; } else if (configuration.getProxyInjectionModeArg() && (browserString.equals("*firefox") || browserString.equals("*firefox2") || browserString.equals("*firefox3"))) { log.warning("running in proxy injection mode, but you used a " + browserString + " browser string; this is " + "almost surely inappropriate, so I'm changing it to *pifirefox..."); browserString = "*pifirefox"; } if (null == browserString) { throw new IllegalArgumentException("browser string may not be null"); } return browserString; } /** * Retrieves an available, unused session from the cache. * * @param browserString the necessary browser for a suitable session * @param baseUrl the necessary baseUrl for a suitable session * @return the session info of the cached session, null if none found. */ protected BrowserSessionInfo grabAvailableSession(String browserString, String baseUrl) { BrowserSessionInfo sessionInfo = null; synchronized (availableSessions) { sessionInfo = lookupInfoByBrowserAndUrl(browserString, baseUrl, availableSessions); if (null != sessionInfo) { availableSessions.remove(sessionInfo); } } if (null != sessionInfo) { activeSessions.add(sessionInfo); } return sessionInfo; } /** * Isolated dependency * * @param sessionId session id * @param port port * @param configuration Remote Control Configuration * @return a new FrameGroupCommandQueueSet instance */ protected FrameGroupCommandQueueSet makeQueueSet(String sessionId, int port, RemoteControlConfiguration configuration) { return FrameGroupCommandQueueSet.makeQueueSet(sessionId, configuration.getPortDriversShouldContact(), configuration); } /** * Isolated dependency * * @param sessionId session id * @return an existing FrameGroupCommandQueueSet instance */ protected FrameGroupCommandQueueSet getQueueSet(String sessionId) { return FrameGroupCommandQueueSet.getQueueSet(sessionId); } /** * Creates and tries to open a new session. * * @param browserString browser name string * @param startURL starting url * @param extensionJs per-session user extension javascript * @param configuration Remote Control configuration. Cannot be null. * @param browserConfiguration capabilities of requested browser * @param ensureClean if a clean session is required * @return the BrowserSessionInfo of the new session. * @throws RemoteCommandException if the browser failed to launch and request work in the required * amount of time. */ protected BrowserSessionInfo createNewRemoteSession(String browserString, String startURL, String extensionJs, Capabilities browserConfiguration, boolean ensureClean, RemoteControlConfiguration configuration) throws RemoteCommandException { final FrameGroupCommandQueueSet queueSet; final BrowserSessionInfo sessionInfo; final BrowserLauncher launcher; String sessionId; sessionId = UUID.randomUUID().toString().replace("-", ""); if ("*webdriver".equals(browserString) && browserConfiguration != null) { Object id = browserConfiguration.getCapability("webdriver.remote.sessionid"); if (id != null && id instanceof String) { sessionId = (String) id; } } queueSet = makeQueueSet(sessionId, configuration.getPortDriversShouldContact(), configuration); queueSet.setExtensionJs(extensionJs); try { launcher = browserLauncherFactory.getBrowserLauncher(browserString, sessionId, configuration, browserConfiguration); } catch (InvalidBrowserExecutableException e) { throw new RemoteCommandException(e.getMessage(), ""); } sessionInfo = new BrowserSessionInfo(sessionId, browserString, startURL, launcher, queueSet); SessionIdTracker.setLastSessionId(sessionId); log.info("Allocated session " + sessionId + " for " + startURL + ", launching..."); final PerSessionLogHandler perSessionLogHandler = LoggingManager.perSessionLogHandler(); perSessionLogHandler.attachToCurrentThread(new SessionId(sessionId)); try { launcher.launchRemoteSession(startURL); queueSet.waitForLoad(configuration.getTimeoutInSeconds() * 1000L); // TODO DGF log4j only // NDC.push("sessionId="+sessionId); FrameGroupCommandQueueSet queue = getQueueSet(sessionId); queue.doCommand("setContext", sessionId, ""); activeSessions.add(sessionInfo); return sessionInfo; } catch (Exception e) { /* * At this point the session might not have been added to neither available nor active * sessions. This session is unlikely to be of any practical use so we need to make sure we * close the browser and clear all session data. */ log.log(Level.SEVERE, "Failed to start new browser session, shutdown browser and clear all session data", e); shutdownBrowserAndClearSessionData(sessionInfo); throw new RemoteCommandException("Error while launching browser", "", e); } finally { perSessionLogHandler.detachFromCurrentThread(); } } /** * Adds a browser session that was not created by this factory to the set of active sessions. * <p> * Allows for creation of unmanaged sessions (i.e. no FrameGroupCommandQueueSet) for task such as * running the HTML tests (see HTMLLauncher.java). All fields other than session are required to * be non-null. * * @param sessionInfo the session info to register. * @return true if session was registered */ protected boolean registerExternalSession(BrowserSessionInfo sessionInfo) { boolean result = false; if (BrowserSessionInfo.isValid(sessionInfo)) { activeSessions.add(sessionInfo); result = true; } return result; } /** * Removes a previously registered external browser session from the list of active sessions. * * @param sessionInfo the session to remove. */ protected void deregisterExternalSession(BrowserSessionInfo sessionInfo) { activeSessions.remove(sessionInfo); } /** * Looks up a session in the named set by session id * * @param sessionId the session id to find * @param set the Set to inspect * @return the matching BrowserSessionInfo or null if not found. */ protected BrowserSessionInfo lookupInfoBySessionId(String sessionId, Set<BrowserSessionInfo> set) { BrowserSessionInfo result = null; synchronized (set) { for (BrowserSessionInfo info : set) { if (info.sessionId.equals(sessionId)) { result = info; break; } } } return result; } /** * Looks up a session in the named set by browser string and base URL * * @param browserString the browser string to match * @param baseUrl the base URL to match. * @param set the Set to inspect * @return the matching BrowserSessionInfo or null if not found. */ protected BrowserSessionInfo lookupInfoByBrowserAndUrl(String browserString, String baseUrl, Set<BrowserSessionInfo> set) { BrowserSessionInfo result = null; synchronized (set) { for (BrowserSessionInfo info : set) { if (info.browserString.equals(browserString) && info.baseUrl.equals(baseUrl)) { result = info; break; } } } return result; } protected void removeIdleAvailableSessions() { long now = System.currentTimeMillis(); synchronized (availableSessions) { Iterator<BrowserSessionInfo> iter = availableSessions.iterator(); while (iter.hasNext()) { BrowserSessionInfo info = iter.next(); if (now - info.lastClosedAt > maxIdleSessionTime) { iter.remove(); shutdownBrowserAndClearSessionData(info); } } } } /** * for testing only * @param sessionId session id * @return true if it has one */ protected boolean hasActiveSession(String sessionId) { BrowserSessionInfo info = lookupInfoBySessionId(sessionId, activeSessions); return (null != info); } /** * for testing only * @param sessionId session id * @return true if it has one */ protected boolean hasAvailableSession(String sessionId) { BrowserSessionInfo info = lookupInfoBySessionId(sessionId, availableSessions); return (null != info); } /** * for testing only * @param sessionInfo browser sesssion info */ protected void addToAvailableSessions(BrowserSessionInfo sessionInfo) { availableSessions.add(sessionInfo); } /** * Collection class to hold the objects associated with a browser session. * * @author jbevan@google.com (Jennifer Bevan) */ public static class BrowserSessionInfo { public BrowserSessionInfo(String sessionId, String browserString, String baseUrl, BrowserLauncher launcher, FrameGroupCommandQueueSet session) { this.sessionId = sessionId; this.browserString = browserString; this.baseUrl = baseUrl; this.launcher = launcher; this.session = session; // optional field; may be null. lastClosedAt = 0; } public final String sessionId; public final String browserString; public final String baseUrl; public final BrowserLauncher launcher; public final FrameGroupCommandQueueSet session; public long lastClosedAt; /** * Browser sessions require the session id, the browser, the base URL, and the launcher. They * don't actually require the session to be set up as a FrameGroupCommandQueueSet. * * @param sessionInfo the sessionInfo to validate. * @return true if all fields excepting session are non-null. */ protected static boolean isValid(BrowserSessionInfo sessionInfo) { boolean result = (null != sessionInfo.sessionId && null != sessionInfo.browserString && null != sessionInfo.baseUrl && null != sessionInfo.launcher); return result; } } /** * TimerTask that looks for unused sessions in the availableSessions collection. * * @author jbevan@google.com (Jennifer Bevan) */ protected class CleanupTask extends TimerTask { @Override public void run() { removeIdleAvailableSessions(); } } }
/** * This class is adopted from Htmlunit with the following copyright: * * Copyright (c) 2002-2012 Gargoyle Software 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 io.github.cidisk.indexcrawler.url; public final class UrlResolver { /** * Resolves a given relative URL against a base URL. See * <a href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a> * Section 4 for more details. * * @param baseUrl The base URL in which to resolve the specification. * @param relativeUrl The relative URL to resolve against the base URL. * @return the resolved specification. */ public static String resolveUrl(final String baseUrl, final String relativeUrl) { if (baseUrl == null) { throw new IllegalArgumentException("Base URL must not be null"); } if (relativeUrl == null) { throw new IllegalArgumentException("Relative URL must not be null"); } final Url url = resolveUrl(parseUrl(baseUrl.trim()), relativeUrl.trim()); return url.toString(); } /** * Returns the index within the specified string of the first occurrence of * the specified search character. * * @param s the string to search * @param searchChar the character to search for * @param beginIndex the index at which to start the search * @param endIndex the index at which to stop the search * @return the index of the first occurrence of the character in the string or <tt>-1</tt> */ private static int indexOf(final String s, final char searchChar, final int beginIndex, final int endIndex) { for (int i = beginIndex; i < endIndex; i++) { if (s.charAt(i) == searchChar) { return i; } } return -1; } /** * Parses a given specification using the algorithm depicted in * <a href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a>: * * Section 2.4: Parsing a URL * * An accepted method for parsing URLs is useful to clarify the * generic-RL syntax of Section 2.2 and to describe the algorithm for * resolving relative URLs presented in Section 4. This section * describes the parsing rules for breaking down a URL (relative or * absolute) into the component parts described in Section 2.1. The * rules assume that the URL has already been separated from any * surrounding text and copied to a "parse string". The rules are * listed in the order in which they would be applied by the parser. * * @param spec The specification to parse. * @return the parsed specification. */ private static Url parseUrl(final String spec) { final Url url = new Url(); int startIndex = 0; int endIndex = spec.length(); // Section 2.4.1: Parsing the Fragment Identifier // // If the parse string contains a crosshatch "#" character, then the // substring after the first (left-most) crosshatch "#" and up to the // end of the parse string is the <fragment> identifier. If the // crosshatch is the last character, or no crosshatch is present, then // the fragment identifier is empty. The matched substring, including // the crosshatch character, is removed from the parse string before // continuing. // // Note that the fragment identifier is not considered part of the URL. // However, since it is often attached to the URL, parsers must be able // to recognize and set aside fragment identifiers as part of the // process. final int crosshatchIndex = indexOf(spec, '#', startIndex, endIndex); if (crosshatchIndex >= 0) { url.fragment_ = spec.substring(crosshatchIndex + 1, endIndex); endIndex = crosshatchIndex; } // Section 2.4.2: Parsing the Scheme // // If the parse string contains a colon ":" after the first character // and before any characters not allowed as part of a scheme name (i.e., // any not an alphanumeric, plus "+", period ".", or hyphen "-"), the // <scheme> of the URL is the substring of characters up to but not // including the first colon. These characters and the colon are then // removed from the parse string before continuing. final int colonIndex = indexOf(spec, ':', startIndex, endIndex); if (colonIndex > 0) { final String scheme = spec.substring(startIndex, colonIndex); if (isValidScheme(scheme)) { url.scheme_ = scheme; startIndex = colonIndex + 1; } } // Section 2.4.3: Parsing the Network Location/Login // // If the parse string begins with a double-slash "//", then the // substring of characters after the double-slash and up to, but not // including, the next slash "/" character is the network location/login // (<net_loc>) of the URL. If no trailing slash "/" is present, the // entire remaining parse string is assigned to <net_loc>. The double- // slash and <net_loc> are removed from the parse string before // continuing. // // Note: We also accept a question mark "?" or a semicolon ";" character as // delimiters for the network location/login (<net_loc>) of the URL. final int locationStartIndex; int locationEndIndex; if (spec.startsWith("//", startIndex)) { locationStartIndex = startIndex + 2; locationEndIndex = indexOf(spec, '/', locationStartIndex, endIndex); if (locationEndIndex >= 0) { startIndex = locationEndIndex; } } else { locationStartIndex = -1; locationEndIndex = -1; } // Section 2.4.4: Parsing the Query Information // // If the parse string contains a question mark "?" character, then the // substring after the first (left-most) question mark "?" and up to the // end of the parse string is the <query> information. If the question // mark is the last character, or no question mark is present, then the // query information is empty. The matched substring, including the // question mark character, is removed from the parse string before // continuing. final int questionMarkIndex = indexOf(spec, '?', startIndex, endIndex); if (questionMarkIndex >= 0) { if ((locationStartIndex >= 0) && (locationEndIndex < 0)) { // The substring of characters after the double-slash and up to, but not // including, the question mark "?" character is the network location/login // (<net_loc>) of the URL. locationEndIndex = questionMarkIndex; startIndex = questionMarkIndex; } url.query_ = spec.substring(questionMarkIndex + 1, endIndex); endIndex = questionMarkIndex; } // Section 2.4.5: Parsing the Parameters // // If the parse string contains a semicolon ";" character, then the // substring after the first (left-most) semicolon ";" and up to the end // of the parse string is the parameters (<params>). If the semicolon // is the last character, or no semicolon is present, then <params> is // empty. The matched substring, including the semicolon character, is // removed from the parse string before continuing. final int semicolonIndex = indexOf(spec, ';', startIndex, endIndex); if (semicolonIndex >= 0) { if ((locationStartIndex >= 0) && (locationEndIndex < 0)) { // The substring of characters after the double-slash and up to, but not // including, the semicolon ";" character is the network location/login // (<net_loc>) of the URL. locationEndIndex = semicolonIndex; startIndex = semicolonIndex; } url.parameters_ = spec.substring(semicolonIndex + 1, endIndex); endIndex = semicolonIndex; } // Section 2.4.6: Parsing the Path // // After the above steps, all that is left of the parse string is the // URL <path> and the slash "/" that may precede it. Even though the // initial slash is not part of the URL path, the parser must remember // whether or not it was present so that later processes can // differentiate between relative and absolute paths. Often this is // done by simply storing the preceding slash along with the path. if ((locationStartIndex >= 0) && (locationEndIndex < 0)) { // The entire remaining parse string is assigned to the network // location/login (<net_loc>) of the URL. locationEndIndex = endIndex; } else if (startIndex < endIndex) { url.path_ = spec.substring(startIndex, endIndex); } // Set the network location/login (<net_loc>) of the URL. if ((locationStartIndex >= 0) && (locationEndIndex >= 0)) { url.location_ = spec.substring(locationStartIndex, locationEndIndex); } return url; } /* * Returns true if specified string is a valid scheme name. */ private static boolean isValidScheme(final String scheme) { final int length = scheme.length(); if (length < 1) { return false; } char c = scheme.charAt(0); if (!Character.isLetter(c)) { return false; } for (int i = 1; i < length; i++) { c = scheme.charAt(i); if (!Character.isLetterOrDigit(c) && c != '.' && c != '+' && c != '-') { return false; } } return true; } /** * Resolves a given relative URL against a base URL using the algorithm * depicted in <a href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a>: * * Section 4: Resolving Relative URLs * * This section describes an example algorithm for resolving URLs within * a context in which the URLs may be relative, such that the result is * always a URL in absolute form. Although this algorithm cannot * guarantee that the resulting URL will equal that intended by the * original author, it does guarantee that any valid URL (relative or * absolute) can be consistently transformed to an absolute form given a * valid base URL. * * @param baseUrl The base URL in which to resolve the specification. * @param relativeUrl The relative URL to resolve against the base URL. * @return the resolved specification. */ private static Url resolveUrl(final Url baseUrl, final String relativeUrl) { final Url url = parseUrl(relativeUrl); // Step 1: The base URL is established according to the rules of // Section 3. If the base URL is the empty string (unknown), // the embedded URL is interpreted as an absolute URL and // we are done. if (baseUrl == null) { return url; } // Step 2: Both the base and embedded URLs are parsed into their // component parts as described in Section 2.4. // a) If the embedded URL is entirely empty, it inherits the // entire base URL (i.e., is set equal to the base URL) // and we are done. if (relativeUrl.length() == 0) { return new Url(baseUrl); } // b) If the embedded URL starts with a scheme name, it is // interpreted as an absolute URL and we are done. if (url.scheme_ != null) { return url; } // c) Otherwise, the embedded URL inherits the scheme of // the base URL. url.scheme_ = baseUrl.scheme_; // Step 3: If the embedded URL's <net_loc> is non-empty, we skip to // Step 7. Otherwise, the embedded URL inherits the <net_loc> // (if any) of the base URL. if (url.location_ != null) { return url; } url.location_ = baseUrl.location_; // Step 4: If the embedded URL path is preceded by a slash "/", the // path is not relative and we skip to Step 7. if ((url.path_ != null) && ((url.path_.length() > 0) && ('/' == url.path_.charAt(0)))) { url.path_ = removeLeadingSlashPoints(url.path_); return url; } // Step 5: If the embedded URL path is empty (and not preceded by a // slash), then the embedded URL inherits the base URL path, // and if (url.path_ == null) { url.path_ = baseUrl.path_; // a) if the embedded URL's <params> is non-empty, we skip to // step 7; otherwise, it inherits the <params> of the base // URL (if any) and if (url.parameters_ != null) { return url; } url.parameters_ = baseUrl.parameters_; // b) if the embedded URL's <query> is non-empty, we skip to // step 7; otherwise, it inherits the <query> of the base // URL (if any) and we skip to step 7. if (url.query_ != null) { return url; } url.query_ = baseUrl.query_; return url; } // Step 6: The last segment of the base URL's path (anything // following the rightmost slash "/", or the entire path if no // slash is present) is removed and the embedded URL's path is // appended in its place. The following operations are // then applied, in order, to the new path: final String basePath = baseUrl.path_; String path = ""; if (basePath != null) { final int lastSlashIndex = basePath.lastIndexOf('/'); if (lastSlashIndex >= 0) { path = basePath.substring(0, lastSlashIndex + 1); } } else { path = "/"; } path = path.concat(url.path_); // a) All occurrences of "./", where "." is a complete path // segment, are removed. int pathSegmentIndex; while ((pathSegmentIndex = path.indexOf("/./")) >= 0) { path = path.substring(0, pathSegmentIndex + 1).concat(path.substring(pathSegmentIndex + 3)); } // b) If the path ends with "." as a complete path segment, // that "." is removed. if (path.endsWith("/.")) { path = path.substring(0, path.length() - 1); } // c) All occurrences of "<segment>/../", where <segment> is a // complete path segment not equal to "..", are removed. // Removal of these path segments is performed iteratively, // removing the leftmost matching pattern on each iteration, // until no matching pattern remains. while ((pathSegmentIndex = path.indexOf("/../")) > 0) { final String pathSegment = path.substring(0, pathSegmentIndex); final int slashIndex = pathSegment.lastIndexOf('/'); if (slashIndex < 0) { continue; } if (!"..".equals(pathSegment.substring(slashIndex))) { path = path.substring(0, slashIndex + 1).concat(path.substring(pathSegmentIndex + 4)); } } // d) If the path ends with "<segment>/..", where <segment> is a // complete path segment not equal to "..", that // "<segment>/.." is removed. if (path.endsWith("/..")) { final String pathSegment = path.substring(0, path.length() - 3); final int slashIndex = pathSegment.lastIndexOf('/'); if (slashIndex >= 0) { path = path.substring(0, slashIndex + 1); } } path = removeLeadingSlashPoints(path); url.path_ = path; // Step 7: The resulting URL components, including any inherited from // the base URL, are recombined to give the absolute form of // the embedded URL. return url; } /** * "/.." at the beginning should be removed as browsers do (not in RFC) */ private static String removeLeadingSlashPoints(String path) { while (path.startsWith("/..")) { path = path.substring(3); } return path; } /** * Class <tt>Url</tt> represents a Uniform Resource Locator. * * @author Martin Tamme */ private static class Url { String scheme_; String location_; String path_; String parameters_; String query_; String fragment_; /** * Creates a <tt>Url</tt> object. */ public Url() { } /** * Creates a <tt>Url</tt> object from the specified * <tt>Url</tt> object. * * @param url a <tt>Url</tt> object. */ public Url(final Url url) { scheme_ = url.scheme_; location_ = url.location_; path_ = url.path_; parameters_ = url.parameters_; query_ = url.query_; fragment_ = url.fragment_; } /** * Returns a string representation of the <tt>Url</tt> object. * * @return a string representation of the <tt>Url</tt> object. */ @Override public String toString() { final StringBuilder sb = new StringBuilder(); if (scheme_ != null) { sb.append(scheme_); sb.append(':'); } if (location_ != null) { sb.append("//"); sb.append(location_); } if (path_ != null) { sb.append(path_); } if (parameters_ != null) { sb.append(';'); sb.append(parameters_); } if (query_ != null) { sb.append('?'); sb.append(query_); } if (fragment_ != null) { sb.append('#'); sb.append(fragment_); } return sb.toString(); } } }
/* * 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.flink.connector.elasticsearch.sink; import org.apache.flink.annotation.VisibleForTesting; import org.apache.flink.api.common.operators.MailboxExecutor; import org.apache.flink.api.connector.sink2.SinkWriter; import org.apache.flink.metrics.Counter; import org.apache.flink.metrics.groups.SinkWriterMetricGroup; import org.apache.flink.util.FlinkRuntimeException; import org.apache.flink.util.function.ThrowingRunnable; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.elasticsearch.action.DocWriteRequest; import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.rest.RestStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import static org.apache.flink.util.ExceptionUtils.firstOrSuppressed; import static org.apache.flink.util.Preconditions.checkNotNull; class ElasticsearchWriter<IN> implements SinkWriter<IN> { private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchWriter.class); private final ElasticsearchEmitter<? super IN> emitter; private final MailboxExecutor mailboxExecutor; private final boolean flushOnCheckpoint; private final BulkProcessor bulkProcessor; private final RestHighLevelClient client; private final RequestIndexer requestIndexer; private final Counter numBytesOutCounter; private long pendingActions = 0; private boolean checkpointInProgress = false; private volatile long lastSendTime = 0; private volatile long ackTime = Long.MAX_VALUE; private volatile boolean closed = false; /** * Constructor creating an elasticsearch writer. * * @param hosts the reachable elasticsearch cluster nodes * @param emitter converting incoming records to elasticsearch actions * @param flushOnCheckpoint if true all until now received records are flushed after every * checkpoint * @param bulkProcessorConfig describing the flushing and failure handling of the used {@link * BulkProcessor} * @param bulkProcessorBuilderFactory configuring the {@link BulkProcessor}'s builder * @param networkClientConfig describing properties of the network connection used to connect to * the elasticsearch cluster * @param metricGroup for the sink writer * @param mailboxExecutor Flink's mailbox executor */ ElasticsearchWriter( List<HttpHost> hosts, ElasticsearchEmitter<? super IN> emitter, boolean flushOnCheckpoint, BulkProcessorConfig bulkProcessorConfig, BulkProcessorBuilderFactory bulkProcessorBuilderFactory, NetworkClientConfig networkClientConfig, SinkWriterMetricGroup metricGroup, MailboxExecutor mailboxExecutor) { this.emitter = checkNotNull(emitter); this.flushOnCheckpoint = flushOnCheckpoint; this.mailboxExecutor = checkNotNull(mailboxExecutor); this.client = new RestHighLevelClient( configureRestClientBuilder( RestClient.builder(hosts.toArray(new HttpHost[0])), networkClientConfig)); this.bulkProcessor = createBulkProcessor(bulkProcessorBuilderFactory, bulkProcessorConfig); this.requestIndexer = new DefaultRequestIndexer(); checkNotNull(metricGroup); metricGroup.setCurrentSendTimeGauge(() -> ackTime - lastSendTime); this.numBytesOutCounter = metricGroup.getIOMetricGroup().getNumBytesOutCounter(); try { emitter.open(); } catch (Exception e) { throw new FlinkRuntimeException("Failed to open the ElasticsearchEmitter", e); } } @Override public void write(IN element, Context context) throws IOException, InterruptedException { // do not allow new bulk writes until all actions are flushed while (checkpointInProgress) { mailboxExecutor.yield(); } emitter.emit(element, context, requestIndexer); } @Override public void flush(boolean endOfInput) throws IOException, InterruptedException { checkpointInProgress = true; while (pendingActions != 0 && (flushOnCheckpoint || endOfInput)) { bulkProcessor.flush(); LOG.info("Waiting for the response of {} pending actions.", pendingActions); mailboxExecutor.yield(); } checkpointInProgress = false; } @VisibleForTesting void blockingFlushAllActions() throws InterruptedException { while (pendingActions != 0) { bulkProcessor.flush(); LOG.info("Waiting for the response of {} pending actions.", pendingActions); mailboxExecutor.yield(); } } @Override public void close() throws Exception { closed = true; emitter.close(); bulkProcessor.close(); client.close(); } private static RestClientBuilder configureRestClientBuilder( RestClientBuilder builder, NetworkClientConfig networkClientConfig) { if (networkClientConfig.getConnectionPathPrefix() != null) { builder.setPathPrefix(networkClientConfig.getConnectionPathPrefix()); } if (networkClientConfig.getPassword() != null && networkClientConfig.getUsername() != null) { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( AuthScope.ANY, new UsernamePasswordCredentials( networkClientConfig.getUsername(), networkClientConfig.getPassword())); builder.setHttpClientConfigCallback( httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)); } if (networkClientConfig.getConnectionRequestTimeout() != null || networkClientConfig.getConnectionTimeout() != null || networkClientConfig.getSocketTimeout() != null) { builder.setRequestConfigCallback( requestConfigBuilder -> { if (networkClientConfig.getConnectionRequestTimeout() != null) { requestConfigBuilder.setConnectionRequestTimeout( networkClientConfig.getConnectionRequestTimeout()); } if (networkClientConfig.getConnectionTimeout() != null) { requestConfigBuilder.setConnectTimeout( networkClientConfig.getConnectionTimeout()); } if (networkClientConfig.getSocketTimeout() != null) { requestConfigBuilder.setSocketTimeout( networkClientConfig.getSocketTimeout()); } return requestConfigBuilder; }); } return builder; } private BulkProcessor createBulkProcessor( BulkProcessorBuilderFactory bulkProcessorBuilderFactory, BulkProcessorConfig bulkProcessorConfig) { BulkProcessor.Builder builder = bulkProcessorBuilderFactory.apply(client, bulkProcessorConfig, new BulkListener()); // This makes flush() blocking builder.setConcurrentRequests(0); return builder.build(); } private class BulkListener implements BulkProcessor.Listener { @Override public void beforeBulk(long executionId, BulkRequest request) { LOG.info("Sending bulk of {} actions to Elasticsearch.", request.numberOfActions()); lastSendTime = System.currentTimeMillis(); numBytesOutCounter.inc(request.estimatedSizeInBytes()); } @Override public void afterBulk(long executionId, BulkRequest request, BulkResponse response) { ackTime = System.currentTimeMillis(); enqueueActionInMailbox( () -> extractFailures(request, response), "elasticsearchSuccessCallback"); } @Override public void afterBulk(long executionId, BulkRequest request, Throwable failure) { enqueueActionInMailbox( () -> { throw new FlinkRuntimeException("Complete bulk has failed.", failure); }, "elasticsearchErrorCallback"); } } private void enqueueActionInMailbox( ThrowingRunnable<? extends Exception> action, String actionName) { // If the writer is cancelled before the last bulk response (i.e. no flush on checkpoint // configured or shutdown without a final // checkpoint) the mailbox might already be shutdown, so we should not enqueue any // actions. if (isClosed()) { return; } mailboxExecutor.execute(action, actionName); } private void extractFailures(BulkRequest request, BulkResponse response) { if (!response.hasFailures()) { pendingActions -= request.numberOfActions(); return; } Throwable chainedFailures = null; for (int i = 0; i < response.getItems().length; i++) { final BulkItemResponse itemResponse = response.getItems()[i]; if (!itemResponse.isFailed()) { continue; } final Throwable failure = itemResponse.getFailure().getCause(); if (failure == null) { continue; } final RestStatus restStatus = itemResponse.getFailure().getStatus(); final DocWriteRequest<?> actionRequest = request.requests().get(i); chainedFailures = firstOrSuppressed( wrapException(restStatus, failure, actionRequest), chainedFailures); } if (chainedFailures == null) { return; } throw new FlinkRuntimeException(chainedFailures); } private static Throwable wrapException( RestStatus restStatus, Throwable rootFailure, DocWriteRequest<?> actionRequest) { if (restStatus == null) { return new FlinkRuntimeException( String.format("Single action %s of bulk request failed.", actionRequest), rootFailure); } else { return new FlinkRuntimeException( String.format( "Single action %s of bulk request failed with status %s.", actionRequest, restStatus.getStatus()), rootFailure); } } private boolean isClosed() { if (closed) { LOG.warn("Writer was closed before all records were acknowledged by Elasticsearch."); } return closed; } private class DefaultRequestIndexer implements RequestIndexer { @Override public void add(DeleteRequest... deleteRequests) { for (final DeleteRequest deleteRequest : deleteRequests) { pendingActions++; bulkProcessor.add(deleteRequest); } } @Override public void add(IndexRequest... indexRequests) { for (final IndexRequest indexRequest : indexRequests) { pendingActions++; bulkProcessor.add(indexRequest); } } @Override public void add(UpdateRequest... updateRequests) { for (final UpdateRequest updateRequest : updateRequests) { pendingActions++; bulkProcessor.add(updateRequest); } } } }
/** * Generated with Acceleo */ package org.wso2.developerstudio.eclipse.gmf.esb.parts.forms; // Start of user code for imports import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent; import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent; import org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart; import org.eclipse.emf.eef.runtime.context.impl.EObjectPropertiesEditionContext; import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent; import org.eclipse.emf.eef.runtime.part.impl.SectionPropertiesEditingPart; import org.eclipse.emf.eef.runtime.policies.PropertiesEditingPolicy; import org.eclipse.emf.eef.runtime.providers.PropertiesEditingProvider; import org.eclipse.emf.eef.runtime.ui.parts.PartComposer; import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence; import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence; import org.eclipse.emf.eef.runtime.ui.widgets.ReferencesTable; import org.eclipse.emf.eef.runtime.ui.widgets.ReferencesTable.ReferencesTableListener; import org.eclipse.emf.eef.runtime.ui.widgets.TabElementTreeSelectionDialog; import org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableContentProvider; import org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableSettings; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.forms.widgets.Form; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.ScrolledForm; import org.eclipse.ui.forms.widgets.Section; import org.wso2.developerstudio.eclipse.gmf.esb.parts.CacheMediatorInputConnectorPropertiesEditionPart; import org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbViewsRepository; import org.wso2.developerstudio.eclipse.gmf.esb.providers.EsbMessages; // End of user code /** * * */ public class CacheMediatorInputConnectorPropertiesEditionPartForm extends SectionPropertiesEditingPart implements IFormPropertiesEditionPart, CacheMediatorInputConnectorPropertiesEditionPart { protected ReferencesTable incomingLinks; protected List<ViewerFilter> incomingLinksBusinessFilters = new ArrayList<ViewerFilter>(); protected List<ViewerFilter> incomingLinksFilters = new ArrayList<ViewerFilter>(); /** * For {@link ISection} use only. */ public CacheMediatorInputConnectorPropertiesEditionPartForm() { super(); } /** * Default constructor * @param editionComponent the {@link IPropertiesEditionComponent} that manage this part * */ public CacheMediatorInputConnectorPropertiesEditionPartForm(IPropertiesEditionComponent editionComponent) { super(editionComponent); } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart# * createFigure(org.eclipse.swt.widgets.Composite, org.eclipse.ui.forms.widgets.FormToolkit) * */ public Composite createFigure(final Composite parent, final FormToolkit widgetFactory) { ScrolledForm scrolledForm = widgetFactory.createScrolledForm(parent); Form form = scrolledForm.getForm(); view = form.getBody(); GridLayout layout = new GridLayout(); layout.numColumns = 3; view.setLayout(layout); createControls(widgetFactory, view); return scrolledForm; } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart# * createControls(org.eclipse.ui.forms.widgets.FormToolkit, org.eclipse.swt.widgets.Composite) * */ public void createControls(final FormToolkit widgetFactory, Composite view) { CompositionSequence cacheMediatorInputConnectorStep = new BindingCompositionSequence(propertiesEditionComponent); cacheMediatorInputConnectorStep .addStep(EsbViewsRepository.CacheMediatorInputConnector.Properties.class) .addStep(EsbViewsRepository.CacheMediatorInputConnector.Properties.incomingLinks); composer = new PartComposer(cacheMediatorInputConnectorStep) { @Override public Composite addToPart(Composite parent, Object key) { if (key == EsbViewsRepository.CacheMediatorInputConnector.Properties.class) { return createPropertiesGroup(widgetFactory, parent); } if (key == EsbViewsRepository.CacheMediatorInputConnector.Properties.incomingLinks) { return createIncomingLinksReferencesTable(widgetFactory, parent); } return parent; } }; composer.compose(view); } /** * */ protected Composite createPropertiesGroup(FormToolkit widgetFactory, final Composite parent) { Section propertiesSection = widgetFactory.createSection(parent, Section.TITLE_BAR | Section.TWISTIE | Section.EXPANDED); propertiesSection.setText(EsbMessages.CacheMediatorInputConnectorPropertiesEditionPart_PropertiesGroupLabel); GridData propertiesSectionData = new GridData(GridData.FILL_HORIZONTAL); propertiesSectionData.horizontalSpan = 3; propertiesSection.setLayoutData(propertiesSectionData); Composite propertiesGroup = widgetFactory.createComposite(propertiesSection); GridLayout propertiesGroupLayout = new GridLayout(); propertiesGroupLayout.numColumns = 3; propertiesGroup.setLayout(propertiesGroupLayout); propertiesSection.setClient(propertiesGroup); return propertiesGroup; } /** * */ protected Composite createIncomingLinksReferencesTable(FormToolkit widgetFactory, Composite parent) { this.incomingLinks = new ReferencesTable(getDescription(EsbViewsRepository.CacheMediatorInputConnector.Properties.incomingLinks, EsbMessages.CacheMediatorInputConnectorPropertiesEditionPart_IncomingLinksLabel), new ReferencesTableListener () { public void handleAdd() { addIncomingLinks(); } public void handleEdit(EObject element) { editIncomingLinks(element); } public void handleMove(EObject element, int oldIndex, int newIndex) { moveIncomingLinks(element, oldIndex, newIndex); } public void handleRemove(EObject element) { removeFromIncomingLinks(element); } public void navigateTo(EObject element) { } }); this.incomingLinks.setHelpText(propertiesEditionComponent.getHelpContent(EsbViewsRepository.CacheMediatorInputConnector.Properties.incomingLinks, EsbViewsRepository.FORM_KIND)); this.incomingLinks.createControls(parent, widgetFactory); this.incomingLinks.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (e.item != null && e.item.getData() instanceof EObject) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(CacheMediatorInputConnectorPropertiesEditionPartForm.this, EsbViewsRepository.CacheMediatorInputConnector.Properties.incomingLinks, PropertiesEditionEvent.CHANGE, PropertiesEditionEvent.SELECTION_CHANGED, null, e.item.getData())); } } }); GridData incomingLinksData = new GridData(GridData.FILL_HORIZONTAL); incomingLinksData.horizontalSpan = 3; this.incomingLinks.setLayoutData(incomingLinksData); this.incomingLinks.disableMove(); incomingLinks.setID(EsbViewsRepository.CacheMediatorInputConnector.Properties.incomingLinks); incomingLinks.setEEFType("eef::AdvancedReferencesTable"); //$NON-NLS-1$ // Start of user code for createIncomingLinksReferencesTable // End of user code return parent; } /** * */ protected void addIncomingLinks() { TabElementTreeSelectionDialog dialog = new TabElementTreeSelectionDialog(incomingLinks.getInput(), incomingLinksFilters, incomingLinksBusinessFilters, "incomingLinks", propertiesEditionComponent.getEditingContext().getAdapterFactory(), current.eResource()) { @Override public void process(IStructuredSelection selection) { for (Iterator<?> iter = selection.iterator(); iter.hasNext();) { EObject elem = (EObject) iter.next(); propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(CacheMediatorInputConnectorPropertiesEditionPartForm.this, EsbViewsRepository.CacheMediatorInputConnector.Properties.incomingLinks, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.ADD, null, elem)); } incomingLinks.refresh(); } }; dialog.open(); } /** * */ protected void moveIncomingLinks(EObject element, int oldIndex, int newIndex) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(CacheMediatorInputConnectorPropertiesEditionPartForm.this, EsbViewsRepository.CacheMediatorInputConnector.Properties.incomingLinks, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.MOVE, element, newIndex)); incomingLinks.refresh(); } /** * */ protected void removeFromIncomingLinks(EObject element) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(CacheMediatorInputConnectorPropertiesEditionPartForm.this, EsbViewsRepository.CacheMediatorInputConnector.Properties.incomingLinks, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.REMOVE, null, element)); incomingLinks.refresh(); } /** * */ protected void editIncomingLinks(EObject element) { EObjectPropertiesEditionContext context = new EObjectPropertiesEditionContext(propertiesEditionComponent.getEditingContext(), propertiesEditionComponent, element, adapterFactory); PropertiesEditingProvider provider = (PropertiesEditingProvider)adapterFactory.adapt(element, PropertiesEditingProvider.class); if (provider != null) { PropertiesEditingPolicy policy = provider.getPolicy(context); if (policy != null) { policy.execute(); incomingLinks.refresh(); } } } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent) * */ public void firePropertiesChanged(IPropertiesEditionEvent event) { // Start of user code for tab synchronization // End of user code } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.CacheMediatorInputConnectorPropertiesEditionPart#initIncomingLinks(org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableSettings) */ public void initIncomingLinks(ReferencesTableSettings settings) { if (current.eResource() != null && current.eResource().getResourceSet() != null) this.resourceSet = current.eResource().getResourceSet(); ReferencesTableContentProvider contentProvider = new ReferencesTableContentProvider(); incomingLinks.setContentProvider(contentProvider); incomingLinks.setInput(settings); incomingLinksBusinessFilters.clear(); incomingLinksFilters.clear(); boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.CacheMediatorInputConnector.Properties.incomingLinks); if (eefElementEditorReadOnlyState && incomingLinks.getTable().isEnabled()) { incomingLinks.setEnabled(false); incomingLinks.setToolTipText(EsbMessages.CacheMediatorInputConnector_ReadOnly); } else if (!eefElementEditorReadOnlyState && !incomingLinks.getTable().isEnabled()) { incomingLinks.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.CacheMediatorInputConnectorPropertiesEditionPart#updateIncomingLinks() * */ public void updateIncomingLinks() { incomingLinks.refresh(); } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.CacheMediatorInputConnectorPropertiesEditionPart#addFilterIncomingLinks(ViewerFilter filter) * */ public void addFilterToIncomingLinks(ViewerFilter filter) { incomingLinksFilters.add(filter); } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.CacheMediatorInputConnectorPropertiesEditionPart#addBusinessFilterIncomingLinks(ViewerFilter filter) * */ public void addBusinessFilterToIncomingLinks(ViewerFilter filter) { incomingLinksBusinessFilters.add(filter); } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.CacheMediatorInputConnectorPropertiesEditionPart#isContainedInIncomingLinksTable(EObject element) * */ public boolean isContainedInIncomingLinksTable(EObject element) { return ((ReferencesTableSettings)incomingLinks.getInput()).contains(element); } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle() * */ public String getTitle() { return EsbMessages.CacheMediatorInputConnector_Part_Title; } // Start of user code additional methods // End of user code }
/* * Copyright (c) 2010-2013, MoPub Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of 'MoPub Inc.' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mopub.mobileads; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.location.Location; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.provider.Settings; import android.telephony.TelephonyManager; import com.mopub.common.AdUrlGenerator; import com.mopub.common.GpsHelper; import com.mopub.common.GpsHelperTest; import com.mopub.common.SharedPreferencesHelper; import com.mopub.common.util.Reflection.MethodBuilder; import com.mopub.common.MoPub; import com.mopub.common.util.Utils; import com.mopub.common.util.test.support.TestMethodBuilderFactory; import com.mopub.mobileads.test.support.SdkTestRunner; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.robolectric.shadows.ShadowConnectivityManager; import org.robolectric.shadows.ShadowNetworkInfo; import org.robolectric.shadows.ShadowTelephonyManager; import static android.Manifest.permission.ACCESS_NETWORK_STATE; import static android.net.ConnectivityManager.TYPE_DUMMY; import static android.net.ConnectivityManager.TYPE_ETHERNET; import static android.net.ConnectivityManager.TYPE_MOBILE; import static android.net.ConnectivityManager.TYPE_MOBILE_DUN; import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI; import static android.net.ConnectivityManager.TYPE_MOBILE_MMS; import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL; import static android.net.ConnectivityManager.TYPE_WIFI; import static android.telephony.TelephonyManager.NETWORK_TYPE_UNKNOWN; import static com.mopub.common.AdUrlGenerator.MoPubNetworkType; import static com.mopub.common.util.Strings.isEmpty; import static com.mopub.mobileads.WebViewAdUrlGenerator.TwitterAppInstalledStatus; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; import static org.robolectric.Robolectric.application; import static org.robolectric.Robolectric.shadowOf; @RunWith(SdkTestRunner.class) public class WebViewUrlGeneratorTest { private WebViewAdUrlGenerator subject; private static final String TEST_UDID = "20b013c721c"; private String expectedUdid; private Configuration configuration; private ShadowTelephonyManager shadowTelephonyManager; private ShadowConnectivityManager shadowConnectivityManager; private Activity context; private MethodBuilder methodBuilder; @Before public void setup() { context = new Activity(); shadowOf(context).grantPermissions(ACCESS_NETWORK_STATE); subject = new WebViewAdUrlGenerator(context); Settings.Secure.putString(application.getContentResolver(), Settings.Secure.ANDROID_ID, TEST_UDID); expectedUdid = "sha%3A" + Utils.sha1(TEST_UDID); configuration = application.getResources().getConfiguration(); shadowTelephonyManager = shadowOf((TelephonyManager) application.getSystemService(Context.TELEPHONY_SERVICE)); shadowConnectivityManager = shadowOf((ConnectivityManager) application.getSystemService(Context.CONNECTIVITY_SERVICE)); methodBuilder = TestMethodBuilderFactory.getSingletonMock(); } @After public void tearDown() throws Exception { AdUrlGenerator.setTwitterAppInstalledStatus(TwitterAppInstalledStatus.UNKNOWN); reset(methodBuilder); } @Test public void generateAdUrl_shouldIncludeMinimumFields() throws Exception { String expectedAdUrl = new AdUrlBuilder(expectedUdid).build(); String adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(expectedAdUrl); } @Test public void generateAdUrl_shouldRunMultipleTimes() throws Exception { String expectedAdUrl = new AdUrlBuilder(expectedUdid).build(); String adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(expectedAdUrl); adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(expectedAdUrl); } @Test public void generateAdUrl_shouldIncludeAllFields() throws Exception { final String expectedAdUrl = new AdUrlBuilder(expectedUdid) .withAdUnitId("adUnitId") .withQuery("key%3Avalue") .withLatLon("20.1%2C30.0", "1") .withMcc("123") .withMnc("456") .withCountryIso("expected%20country") .withCarrierName("expected%20carrier") .withExternalStoragePermission(false) .build(); shadowTelephonyManager.setNetworkOperator("123456"); shadowTelephonyManager.setNetworkCountryIso("expected country"); shadowTelephonyManager.setNetworkOperatorName("expected carrier"); Location location = new Location(""); location.setLatitude(20.1); location.setLongitude(30.0); location.setAccuracy(1.23f); // should get rounded to "1" String adUrl = subject .withAdUnitId("adUnitId") .withKeywords("key:value") .withLocation(location) .generateUrlString("ads.mopub.com"); assertThat(adUrl).isEqualTo(expectedAdUrl); } @Test public void generateAdUrl_shouldRecognizeOrientation() throws Exception { configuration.orientation = Configuration.ORIENTATION_LANDSCAPE; assertThat(generateMinimumUrlString()).contains("&o=l"); configuration.orientation = Configuration.ORIENTATION_PORTRAIT; assertThat(generateMinimumUrlString()).contains("&o=p"); configuration.orientation = Configuration.ORIENTATION_SQUARE; assertThat(generateMinimumUrlString()).contains("&o=s"); } @Test public void generateAdUrl_shouldHandleFunkyNetworkOperatorCodes() throws Exception { AdUrlBuilder urlBuilder = new AdUrlBuilder(expectedUdid); shadowTelephonyManager.setNetworkOperator("123456"); String adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withMcc("123").withMnc("456").build()); shadowTelephonyManager.setNetworkOperator("12345"); adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withMcc("123").withMnc("45").build()); shadowTelephonyManager.setNetworkOperator("1234"); adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withMcc("123").withMnc("4").build()); shadowTelephonyManager.setNetworkOperator("123"); adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withMcc("123").withMnc("").build()); shadowTelephonyManager.setNetworkOperator("12"); adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withMcc("12").withMnc("").build()); } @Test public void generateAdurl_whenOnCDMA_shouldGetOwnerStringFromSimCard() throws Exception { AdUrlBuilder urlBuilder = new AdUrlBuilder(expectedUdid); shadowTelephonyManager.setPhoneType(TelephonyManager.PHONE_TYPE_CDMA); shadowTelephonyManager.setSimState(TelephonyManager.SIM_STATE_READY); shadowTelephonyManager.setNetworkOperator("123456"); shadowTelephonyManager.setSimOperator("789012"); String adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withMcc("789").withMnc("012").build()); } @Test public void generateAdurl_whenSimNotReady_shouldDefaultToNetworkOperator() throws Exception { AdUrlBuilder urlBuilder = new AdUrlBuilder(expectedUdid); shadowTelephonyManager.setPhoneType(TelephonyManager.PHONE_TYPE_CDMA); shadowTelephonyManager.setSimState(TelephonyManager.SIM_STATE_ABSENT); shadowTelephonyManager.setNetworkOperator("123456"); shadowTelephonyManager.setSimOperator("789012"); String adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withMcc("123").withMnc("456").build()); } @Test public void generateAdUrl_shouldSetNetworkType() throws Exception { AdUrlBuilder urlBuilder = new AdUrlBuilder(expectedUdid); String adUrl; shadowConnectivityManager.setActiveNetworkInfo(createNetworkInfo(TYPE_DUMMY)); adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withNetworkType(MoPubNetworkType.UNKNOWN).build()); shadowConnectivityManager.setActiveNetworkInfo(createNetworkInfo(TYPE_ETHERNET)); adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withNetworkType(MoPubNetworkType.ETHERNET).build()); shadowConnectivityManager.setActiveNetworkInfo(createNetworkInfo(TYPE_WIFI)); adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withNetworkType(MoPubNetworkType.WIFI).build()); // bunch of random mobile types just to make life more interesting shadowConnectivityManager.setActiveNetworkInfo(createNetworkInfo(TYPE_MOBILE)); adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withNetworkType(MoPubNetworkType.MOBILE).build()); shadowConnectivityManager.setActiveNetworkInfo(createNetworkInfo(TYPE_MOBILE_DUN)); adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withNetworkType(MoPubNetworkType.MOBILE).build()); shadowConnectivityManager.setActiveNetworkInfo(createNetworkInfo(TYPE_MOBILE_HIPRI)); adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withNetworkType(MoPubNetworkType.MOBILE).build()); shadowConnectivityManager.setActiveNetworkInfo(createNetworkInfo(TYPE_MOBILE_MMS)); adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withNetworkType(MoPubNetworkType.MOBILE).build()); shadowConnectivityManager.setActiveNetworkInfo(createNetworkInfo(TYPE_MOBILE_SUPL)); adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withNetworkType(MoPubNetworkType.MOBILE).build()); } @Test public void generateAdUrl_whenNoNetworkPermission_shouldGenerateUnknownNetworkType() throws Exception { AdUrlBuilder urlBuilder = new AdUrlBuilder(expectedUdid); shadowOf(context).denyPermissions(ACCESS_NETWORK_STATE); shadowConnectivityManager.setActiveNetworkInfo(createNetworkInfo(TYPE_MOBILE)); String adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withNetworkType(MoPubNetworkType.UNKNOWN).build()); } @Test public void generateAdUrl_whenTwitterIsNotInstalled_shouldProcessAndNotSetTwitterInstallStatusOnFirstRequest() throws Exception { AdUrlBuilder urlBuilder = new AdUrlBuilder(expectedUdid); WebViewAdUrlGenerator spySubject = Mockito.spy(subject); AdUrlGenerator.setTwitterAppInstalledStatus(TwitterAppInstalledStatus.UNKNOWN); doReturn(TwitterAppInstalledStatus.NOT_INSTALLED).when(spySubject).getTwitterAppInstallStatus(); String adUrl = spySubject.generateUrlString("ads.mopub.com"); assertThat(adUrl).isEqualTo(urlBuilder.withTwitterAppInstalledStatus(TwitterAppInstalledStatus.NOT_INSTALLED).build()); } @Test public void generateAdUrl_whenTwitterIsInstalled_shouldProcessAndSetTwitterInstallStatusOnFirstRequest() throws Exception { AdUrlBuilder urlBuilder = new AdUrlBuilder(expectedUdid); WebViewAdUrlGenerator spySubject = Mockito.spy(subject); AdUrlGenerator.setTwitterAppInstalledStatus(TwitterAppInstalledStatus.UNKNOWN); doReturn(TwitterAppInstalledStatus.INSTALLED).when(spySubject).getTwitterAppInstallStatus(); String adUrl = spySubject.generateUrlString("ads.mopub.com"); assertThat(adUrl).isEqualTo(urlBuilder.withTwitterAppInstalledStatus(TwitterAppInstalledStatus.INSTALLED).build()); } @Test public void generateAdUrl_shouldNotProcessTwitterInstallStatusIfStatusIsAlreadySet() throws Exception { AdUrlBuilder urlBuilder = new AdUrlBuilder(expectedUdid); WebViewAdUrlGenerator spySubject = Mockito.spy(subject); AdUrlGenerator.setTwitterAppInstalledStatus(TwitterAppInstalledStatus.NOT_INSTALLED); doReturn(TwitterAppInstalledStatus.INSTALLED).when(spySubject).getTwitterAppInstallStatus(); String adUrl = spySubject.generateUrlString("ads.mopub.com"); assertThat(adUrl).isEqualTo(urlBuilder.withTwitterAppInstalledStatus(TwitterAppInstalledStatus.NOT_INSTALLED).build()); } @Test public void generateAdUrl_shouldTolerateNullActiveNetwork() throws Exception { AdUrlBuilder urlBuilder = new AdUrlBuilder(expectedUdid); shadowConnectivityManager.setActiveNetworkInfo(null); String adUrl = generateMinimumUrlString(); assertThat(adUrl).isEqualTo(urlBuilder.withNetworkType(MoPubNetworkType.UNKNOWN).build()); } @Test public void generateAdUrl_whenGooglePlayServicesIsLinkedAndAdInfoIsCached_shouldUseAdInfoParams() throws Exception { GpsHelper.setClassNamesForTesting(); when(methodBuilder.setStatic(any(Class.class))).thenReturn(methodBuilder); when(methodBuilder.addParam(any(Class.class), any())).thenReturn(methodBuilder); when(methodBuilder.execute()).thenReturn(GpsHelper.GOOGLE_PLAY_SUCCESS_CODE); GpsHelperTest.TestAdInfo adInfo = new GpsHelperTest.TestAdInfo(); SharedPreferencesHelper.getSharedPreferences(context) .edit() .putString(GpsHelper.ADVERTISING_ID_KEY, adInfo.ADVERTISING_ID) .putBoolean(GpsHelper.IS_LIMIT_AD_TRACKING_ENABLED_KEY, adInfo.LIMIT_AD_TRACKING_ENABLED) .commit(); expectedUdid = "ifa%3A" + adInfo.ADVERTISING_ID; String expectedAdUrl = new AdUrlBuilder(expectedUdid) .withDnt(adInfo.LIMIT_AD_TRACKING_ENABLED) .build(); assertThat(generateMinimumUrlString()).isEqualTo(expectedAdUrl); } private NetworkInfo createNetworkInfo(int type) { return ShadowNetworkInfo.newInstance(null, type, NETWORK_TYPE_UNKNOWN, true, true); } private String generateMinimumUrlString() { return subject.generateUrlString("ads.mopub.com"); } private static class AdUrlBuilder { private String expectedUdid; private String adUnitId = ""; private String query = ""; private String latLon = ""; private String locationAccuracy = ""; private String mnc = ""; private String mcc = ""; private String countryIso = ""; private String carrierName = ""; private String dnt = ""; private MoPubNetworkType networkType = MoPubNetworkType.MOBILE; private TwitterAppInstalledStatus twitterAppInstalledStatus = TwitterAppInstalledStatus.UNKNOWN; private int externalStoragePermission; public AdUrlBuilder(String expectedUdid) { this.expectedUdid = expectedUdid; } public String build() { return "http://ads.mopub.com/m/ad" + "?v=6" + paramIfNotEmpty("id", adUnitId) + "&nv=" + MoPub.SDK_VERSION + "&dn=" + Build.MANUFACTURER + "%2C" + Build.MODEL + "%2C" + Build.PRODUCT + "&udid=" + expectedUdid + paramIfNotEmpty("dnt", dnt) + paramIfNotEmpty("q", query) + (isEmpty(latLon) ? "" : "&ll=" + latLon + "&lla=" + locationAccuracy) + "&z=-0700" + "&o=u" + "&sc_a=1.0" + "&mr=1" + paramIfNotEmpty("mcc", mcc) + paramIfNotEmpty("mnc", mnc) + paramIfNotEmpty("iso", countryIso) + paramIfNotEmpty("cn", carrierName) + "&ct=" + networkType + "&av=1.0" + "&android_perms_ext_storage=" + externalStoragePermission + ((twitterAppInstalledStatus == TwitterAppInstalledStatus.INSTALLED) ? "&ts=1" : ""); } public AdUrlBuilder withAdUnitId(String adUnitId) { this.adUnitId = adUnitId; return this; } public AdUrlBuilder withQuery(String query) { this.query = query; return this; } public AdUrlBuilder withLatLon(String latLon, String locationAccuracy) { this.latLon = latLon; this.locationAccuracy = locationAccuracy; return this; } public AdUrlBuilder withMcc(String mcc) { this.mcc = mcc; return this; } public AdUrlBuilder withMnc(String mnc) { this.mnc = mnc; return this; } public AdUrlBuilder withCountryIso(String countryIso) { this.countryIso = countryIso; return this; } public AdUrlBuilder withCarrierName(String carrierName) { this.carrierName = carrierName; return this; } public AdUrlBuilder withNetworkType(MoPubNetworkType networkType) { this.networkType = networkType; return this; } public AdUrlBuilder withExternalStoragePermission(boolean enabled) { this.externalStoragePermission = enabled ? 1 : 0; return this; } public AdUrlBuilder withTwitterAppInstalledStatus(TwitterAppInstalledStatus status) { this.twitterAppInstalledStatus = status; return this; } public AdUrlBuilder withDnt(boolean dnt) { if (dnt) { this.dnt = "1"; } return this; } private String paramIfNotEmpty(String key, String value) { if (isEmpty(value)) { return ""; } else { return "&" + key + "=" + value; } } } }
package sarong; import sarong.util.CrossHash; import sarong.util.StringKit; import java.io.Serializable; /** * A high-quality StatefulRandomness that is tied for the fastest 64-bit generator in this library that passes * statistical tests tests and is equidistributed. Has 64 bits of state and natively outputs 64 bits at a time, changing * the state with a variant on a linear congruential generator (an "XLCG" that XORs then multiplies the state with each * step; it is {@code state = (state ^ 0x6C8E9CF570932BD5L) * 0x41C64E6BL}). Starting with that XLCG's output, it * xorshifts that output, adds a very large negative long, then returns another xorshift. For whatever reason, the * output of this simple function passes all 32TB of PractRand, meaning its statistical quality is excellent. This * algorithm is almost identical to {@link LinnormRNG} and also to {@link MizuchiRNG} (in speed and quality), but uses * an XLCG instead of an LCG for the state and adds rather than multiplies the same large negative long. As mentioned * earlier, this is the fastest high-quality generator here (tied with LinnormRNG and MizuchiRNG) other than * {@link ThrustAltRNG}. Unlike ThrustAltRNG, this can produce all long values as output; ThrustAltRNG bunches some * outputs and makes producing them more likely while others can't be produced at all. Notably, this generator is faster * than {@link LightRNG} while keeping the same or higher quality, and also faster than {@link XoRoRNG} while passing * tests that XoRoRNG always or frequently fails, such as binary matrix rank tests. * <br> * This generator is a StatefulRandomness but not a SkippingRandomness, so it can't (efficiently) have the skip() method * that LightRNG has. A method could be written to run the generator's state backwards, though, as well as to get the * state from an output of {@link #nextLong()}. * <br> * The name comes from its Quick speed, X for XLCG and XorShift operations used, and the literary reference to Don * Quixote because I felt like trying to improve LinnormRNG was like jousting at windmills (before I found this one). * <br> * Regarding constants used here (magic numbers): The number that is XORed with state was tinkered with manually to * avoid long runs of 0 bits, mimicking the pattern of numbers used in Weyl sequence increments; it can probably be * changed if it stays 63 bits long, though it must have the last 3 bits be {@code 101}, meaning the last hex digit must * be 5 or B, because of how an XLCG works. The single multiplier is an LCG multiplier used in PractRand, minus 2 to fit * the XLCG requirement for the last 3 bits to be {@code 011}. The single addend is a multiplier from PCG-Random; it may * also be changeable without affecting quality, as long as it is odd and 64 bits long. * <br> * Written June 19, 2018 by Tommy Ettinger. Thanks to M.E. O'Neill for her insights into the family of generators both * this and her PCG-Random fall into, and to the team that worked on SplitMix64 for SplittableRandom in JDK 8. Chris * Doty-Humphrey's work on PractRand has been invaluable, as has his rediscovery of the XLCG technique from somewhere on * Usenet. Thanks also to Sebastiano Vigna and David Blackwell for creating the incredibly fast xoroshiro128+ generator * and also very fast <a href="http://xoshiro.di.unimi.it/hwd.php">HWD tool</a>; the former inspired me to make my code * even faster and the latter tool seems useful so far in proving the quality of the generator. * <br> * <em>NOTE:</em> This generator is still being adapted and improvements may be found to its speed or to other aspects * of how it works (it lacks a determine() method, for instance). These should be expected to change the output of a * QuixoticRNG across versions/commits until it stabilizes. * @author Tommy Ettinger */ public final class QuixoticRNG implements StatefulRandomness, Serializable { private static final long serialVersionUID = 153186732328748834L; private long state; /* The state can be seeded with any value. */ /** * Creates a new generator seeded using Math.random. */ public QuixoticRNG() { this((long) ((Math.random() - 0.5) * 0x10000000000000L) ^ (long) (((Math.random() - 0.5) * 2.0) * 0x8000000000000000L)); } public QuixoticRNG(final long seed) { state = seed; } public QuixoticRNG(final String seed) { state = CrossHash.hash64(seed); } @Override public final int next(int bits) { long z = (state = (state ^ 0x6C8E9CF570932BD5L) * 0x41C64E6BL); z = (z ^ z >>> 27) + 0xAEF17502108EF2D9L; return (int)(z ^ z >>> 25) >>> (32 - bits); } /** * Can return any long, positive or negative, of any size permissible in a 64-bit signed integer. * * @return any long, all 64 bits are random */ @Override public final long nextLong() { long z = (state = (state ^ 0x6C8E9CF570932BD5L) * 0x41C64E6BL); z = (z ^ z >>> 27) + 0xAEF17502108EF2D9L; return (z ^ z >>> 25); } /** * Produces a copy of this RandomnessSource that, if next() and/or nextLong() are called on this object and the * copy, both will generate the same sequence of random numbers from the point copy() was called. This just need to * copy the state so it isn't shared, usually, and produce a new value with the same exact state. * * @return a copy of this RandomnessSource */ @Override public QuixoticRNG copy() { return new QuixoticRNG(state); } /** * Can return any int, positive or negative, of any size permissible in a 32-bit signed integer. * * @return any int, all 32 bits are random */ public final int nextInt() { long z = (state = (state ^ 0x6C8E9CF570932BD5L) * 0x41C64E6BL); z = (z ^ z >>> 27) + 0xAEF17502108EF2D9L; return (int)(z ^ z >>> 25); } /** * Exclusive on the outer bound. The inner bound is 0. * The bound can be negative, which makes this produce either a negative int or 0. * * @param bound the upper bound; should be positive * @return a random int between 0 (inclusive) and bound (exclusive) */ public final int nextInt(final int bound) { long z = (state = (state ^ 0x6C8E9CF570932BD5L) * 0x41C64E6BL); z = (z ^ z >>> 27) + 0xAEF17502108EF2D9L; return (int)((bound * ((z ^ z >>> 25) & 0xFFFFFFFFL)) >> 32); } /** * Inclusive inner, exclusive outer. * * @param inner the inner bound, inclusive, can be positive or negative * @param outer the outer bound, exclusive, can be positive or negative, usually greater than inner * @return a random int between inner (inclusive) and outer (exclusive) */ public final int nextInt(final int inner, final int outer) { return inner + nextInt(outer - inner); } /** * Exclusive on bound (which may be positive or negative), with an inner bound of 0. * If bound is negative this returns a negative long; if bound is positive this returns a positive long. The bound * can even be 0, which will cause this to return 0L every time. * <br> * Credit for this method goes to <a href="https://oroboro.com/large-random-in-range/">Rafael Baptista's blog</a>, * with some adaptation for signed long values and a 64-bit generator. This method is drastically faster than the * previous implementation when the bound varies often (roughly 4x faster, possibly more). It also always gets at * most one random number, so it advances the state as much as {@link #nextInt(int)}. * @param bound the outer exclusive bound; can be positive or negative * @return a random long between 0 (inclusive) and bound (exclusive) */ public long nextLong(long bound) { long rand = (state = (state ^ 0x6C8E9CF570932BD5L) * 0x41C64E6BL); rand = (rand ^ rand >>> 27) + 0xAEF17502108EF2D9L; rand ^= rand >>> 25; final long randLow = rand & 0xFFFFFFFFL; final long boundLow = bound & 0xFFFFFFFFL; rand >>>= 32; bound >>= 32; final long z = (randLow * boundLow >> 32); long t = rand * boundLow + z; final long tLow = t & 0xFFFFFFFFL; t >>>= 32; return rand * bound + t + (tLow + randLow * bound >> 32) - (z >> 63) - (bound >> 63); } /** * Inclusive inner, exclusive outer; lower and upper can be positive or negative and there's no requirement for one * to be greater than or less than the other. * * @param lower the lower bound, inclusive, can be positive or negative * @param upper the upper bound, exclusive, can be positive or negative * @return a random long that may be equal to lower and will otherwise be between lower and upper */ public final long nextLong(final long lower, final long upper) { return lower + nextLong(upper - lower); } /** * Gets a uniform random double in the range [0.0,1.0) * * @return a random double at least equal to 0.0 and less than 1.0 */ public final double nextDouble() { long z = (state = (state ^ 0x6C8E9CF570932BD5L) * 0x41C64E6BL); z = (z ^ z >>> 27) + 0xAEF17502108EF2D9L; return ((z ^ z >>> 25) & 0x1FFFFFFFFFFFFFL) * 0x1p-53; } /** * Gets a uniform random double in the range [0.0,outer) given a positive parameter outer. If outer * is negative, it will be the (exclusive) lower bound and 0.0 will be the (inclusive) upper bound. * * @param outer the exclusive outer bound, can be negative * @return a random double between 0.0 (inclusive) and outer (exclusive) */ public final double nextDouble(final double outer) { long z = (state = (state ^ 0x6C8E9CF570932BD5L) * 0x41C64E6BL); z = (z ^ z >>> 27) + 0xAEF17502108EF2D9L; return ((z ^ z >>> 25) & 0x1FFFFFFFFFFFFFL) * 0x1p-53 * outer; } /** * Gets a uniform random float in the range [0.0,1.0) * * @return a random float at least equal to 0.0 and less than 1.0 */ public final float nextFloat() { long z = (state = (state ^ 0x6C8E9CF570932BD5L) * 0x41C64E6BL); return ((z ^ z >>> 27) + 0xAEF17502108EF2D9L >>> 40) * 0x1p-24f; } /** * Gets a random value, true or false. * Calls nextLong() once. * * @return a random true or false value. */ public final boolean nextBoolean() { return (state = (state ^ 0x6C8E9CF570932BD5L) * 0x41C64E6BL) < 0; } /** * Given a byte array as a parameter, this will fill the array with random bytes (modifying it * in-place). Calls nextLong() {@code Math.ceil(bytes.length / 8.0)} times. * * @param bytes a byte array that will have its contents overwritten with random bytes. */ public final void nextBytes(final byte[] bytes) { int i = bytes.length, n; while (i != 0) { n = Math.min(i, 8); for (long bits = nextLong(); n-- != 0; bits >>>= 8) bytes[--i] = (byte) bits; } } /** * Sets the seed (also the current state) of this generator. * * @param seed the seed to use for this LightRNG, as if it was constructed with this seed. */ @Override public final void setState(final long seed) { state = seed; } /** * Gets the current state of this generator. * * @return the current seed of this LightRNG, changed once per call to nextLong() */ @Override public final long getState() { return state; } @Override public String toString() { return "QuixoticRNG with state 0x" + StringKit.hex(state) + 'L'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return state == ((QuixoticRNG) o).state; } @Override public int hashCode() { return (int) (state ^ (state >>> 32)); } // public static void main(String[] args){ // //Oriole32RNG oriole = new Oriole32RNG(123, 456, 789); // LinnormRNG r = new LinnormRNG(123456789L); // for (int j = 0; j < 15; j++) { // for (long i = 0x100000000L + j; i <= 0x30000000FL; i += 0x100000000L) { // long limit = 4L;//oriole.nextInt(); // long result = r.nextLong(limit); // System.out.printf("%016X %021d %016X %021d %b, ", result, result, limit, limit,Math.abs(limit) - Math.abs(result) >= 0 && (limit >> 63) == (result >> 63)); // } // System.out.println(); // } // } // public static void main(String[] args) // { // /* // cd target/classes // java -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly sarong/DervishRNG > Dervish_asm.txt // */ // long longState = 1L; // int intState = 1; // float floatState = 0f; // double doubleState = 0.0; // LinnormRNG rng = new LinnormRNG(1L); // //longState += determine(i); // //longState = longState + 0x9E3779B97F4A7C15L; // //seed += determine(longState++); // for (int r = 0; r < 10; r++) { // for (int i = 0; i < 10000007; i++) { // longState += rng.nextLong(); // } // } // System.out.println(longState); // // for (int r = 0; r < 10; r++) { // for (int i = 0; i < 10000007; i++) { // intState += rng.next(16); // } // } // System.out.println(intState); // // for (int r = 0; r < 10; r++) { // for (int i = 0; i < 10000007; i++) { // floatState += rng.nextFloat(); // } // } // System.out.println(floatState); // // for (int r = 0; r < 10; r++) { // for (int i = 0; i < 10000007; i++) { // doubleState += rng.nextDouble(); // } // } // System.out.println(doubleState); // // } }
/*************************GO-LICENSE-START********************************* * Copyright 2015 ThoughtWorks, 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. *************************GO-LICENSE-END***********************************/ package com.thoughtworks.cruise.page; import com.thoughtworks.cruise.SahiBrowserWrapper; import com.thoughtworks.cruise.state.ScenarioState; import net.sf.sahi.client.Browser; import net.sf.sahi.client.ElementStub; import net.sf.sahi.client.ExecutionException; import java.util.List; import static java.lang.String.format; import static junit.framework.Assert.assertEquals; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; public class AlreadyOnPipelinesSelectorSection { private final Browser browser; private final ScenarioState scenarioState; public AlreadyOnPipelinesSelectorSection(ScenarioState scenarioState, Browser browser) { this.scenarioState = scenarioState; this.browser = browser; } @com.thoughtworks.gauge.Step("Verify groups <groupNames> are visible - Already on pipelines selector section") public void verifyGroupsAreVisible(String groupNames) throws Exception { String[] groups = groupNames.split(","); for (String group : groups) { assertThat(groupSelector(group),is(not(nullValue()))); } } @com.thoughtworks.gauge.Step("Verify groups <groupNames> are not visible - Already on pipelines selector section") public void verifyGroupsAreNotVisible(String groupNames) throws Exception { String[] groups = groupNames.split(","); for (String group : groups) { try { groupSelector(group).getText(); fail("expected not to find group: " + group); } catch (ExecutionException e) { } } } private ElementStub groupSelector(String group) { return findElementByScopedId(format("select_group_%s", group.trim())); } private ElementStub pipelineSelector(String pipeline) { return findElementByScopedId(format("select_pipeline_%s", pipeline.trim())); } private ElementStub findElementByScopedId(String id){ return browser.byId(id).in(elementSelectorWidget()); // return driver.findElement(By.xpath(IN_PIPELINE_SELECTOR + driver.byIdXPath(id))); } private ElementStub elementSelectorWidget() { return browser.byId("pipelines_selector"); } private ElementStub elementSelectorWidgetPipelineSelections() { return browser.byId("pipelines_selector_pipelines"); } @com.thoughtworks.gauge.Step("Verify all pipelines are selected") public void verifyAllPipelinesAreSelected() throws Exception { verifyCheckboxesAreSelected(true); } private void verifyCheckboxesAreSelected(boolean selected) { verifyCheckboxesAreSelected("", selected); } private void verifyCheckboxesAreSelected(String subScope, boolean selected) { List<ElementStub> checkBoxes = new SahiBrowserWrapper(browser).collectIn("checkbox", subScope, elementSelectorWidgetPipelineSelections()); // List<WebElement> checkBoxes = driver.findElements(By.xpath(IN_PIPELINE_SELECTOR + subScope + "//input[@type='checkbox']")); for (ElementStub checkBox : checkBoxes) { assertThat(checkBox.checked(), is(selected)); } } @com.thoughtworks.gauge.Step("Deselect all pipelines") public void deselectAllPipelines() throws Exception { findElementByScopedId("select_no_pipelines").click(); } @com.thoughtworks.gauge.Step("Select all pipelines") public void selectAllPipelines() throws Exception { findElementByScopedId("select_all_pipelines").click(); } @com.thoughtworks.gauge.Step("Verify no pipelines are selected") public void verifyNoPipelinesAreSelected() throws Exception { verifyCheckboxesAreSelected(false); } @com.thoughtworks.gauge.Step("Deselect group <group>") public void deselectGroup(String group) throws Exception { selectGroup(group, false); } @com.thoughtworks.gauge.Step("Select group <group>") public void selectGroup(String group) throws Exception { selectGroup(group, true); } private void selectGroup(String group, boolean select) { ElementStub groupCheckBox = groupSelector(group); select(groupCheckBox, select); } private void select(ElementStub checkBox, boolean select) { assertChecked(checkBox,!select); checkBox.click(); assertChecked(checkBox,select); } private void assertChecked(ElementStub checkBox, boolean select) { assertThat(format("Expected '%s' selected to be %s", checkBox.fetch("id"), select), checkBox.checked(), is(select)); } @com.thoughtworks.gauge.Step("Verify all pipelines in group <group> are deselected") public void verifyAllPipelinesInGroupAreDeselected(String group)throws Exception { verifyCheckboxesAreSelected(format("selector_group_%s", group), false); } @com.thoughtworks.gauge.Step("Verify all pipelines in group <group> are selected") public void verifyAllPipelinesInGroupAreSelected(String group)throws Exception { verifyCheckboxesAreSelected(format("selector_group_%s", group), true); } @com.thoughtworks.gauge.Step("Deselect pipeline <pipeline> and verify <group> is deselected") public void deselectPipelineAndVerifyIsDeselected(String pipeline, String group)throws Exception { select(pipelineSelector(scenarioState.pipelineNamed(pipeline)), false); assertChecked(groupSelector(group), false); } @com.thoughtworks.gauge.Step("Select pipeline <pipeline> and verify <group> is selected") public void selectPipelineAndVerifyIsSelected(String pipeline, String group)throws Exception { select(pipelineSelector(scenarioState.pipelineNamed(pipeline)), true); assertChecked(groupSelector(group), true); } @com.thoughtworks.gauge.Step("Apply selections") public void applySelections() throws Exception { findElementByScopedId("apply_pipelines_selector").click(); } @com.thoughtworks.gauge.Step("Set show newly created pipelines option status as <expectedStatus>") public void setShowNewlyCreatedPipelinesOptionStatusAs(String expectedStatus) throws Exception { String actualStatus = actualShowNewlyCreatedPipelinesOptionStatus(); if (expectedStatus != actualStatus) { showNewlyCreatedPipelinesOptionElement().click(); } } @com.thoughtworks.gauge.Step("Verify show newly created pipelines option status is <expectedStatus>") public void verifyShowNewlyCreatedPipelinesOptionStatusIs(String expectedStatus) throws Exception { String actualStatus = actualShowNewlyCreatedPipelinesOptionStatus(); assertEquals("Expected Option Status is: "+expectedStatus+"but actual value is: "+ actualStatus, expectedStatus, actualStatus); } private String actualShowNewlyCreatedPipelinesOptionStatus() throws Exception { String actualStatus; ElementStub showNewPipelinesElement = showNewlyCreatedPipelinesOptionElement(); boolean checkStatus= showNewPipelinesElement.checked(); if (checkStatus == true){ actualStatus = "checked"; } else { actualStatus = "unchecked"; } return actualStatus; } private ElementStub showNewlyCreatedPipelinesOptionElement() { return browser.byId("show_new_pipelines").in(browser.div("show_new_pipelines_container")); } public void verifyGroupIsSelected(String group) throws Exception { assertChecked(groupSelector(group), true); } @com.thoughtworks.gauge.Step("Verify group <group> is deselected") public void verifyGroupIsDeselected(String group) throws Exception { assertChecked(groupSelector(group), false); } }
package com.heaven7.android.scroll; import android.util.Log; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.widget.OverScroller; import androidx.core.view.ViewCompat; import java.util.concurrent.CopyOnWriteArrayList; /** * <p> * this class is a simple implement of {@link IScrollHelper}. it can do most work of scroller. * such as {@link IScrollHelper#smoothScrollTo(int, int)}, {@link IScrollHelper#smoothScrollBy(int, int)} and etc. * </p> * Created by heaven7 on 2016/11/14. */ public class ScrollHelper implements IScrollHelper { /*protected*/ static final boolean DEBUG = Util.sDEBUG; private static final long ANIMATED_SCROLL_GAP = 250; private CopyOnWriteArrayList<OnScrollChangeListener> mScrollListeners; private final OverScroller mScroller; protected final ScrollCallback mCallback; protected final String mTag; private final View mTarget; private final int mTouchSlop; private final float mMinFlingVelocity; private final float mMaxFlingVelocity; private long mLastScroll; private int mScrollState = SCROLL_STATE_IDLE; /** * create a ScrollHelper. * * @param target the target view * @param scroller the over Scroller * @param callback the callback */ public ScrollHelper(View target, OverScroller scroller, ScrollCallback callback) { this(target, 1, scroller, callback); } /** * create a ScrollHelper. * * @param target the target view * @param sensitivity Multiplier for how sensitive the helper should be about detecting * the start of a drag. Larger values are more sensitive. 1.0f is normal. * @param scroller the over Scroller * @param callback the callback */ public ScrollHelper(View target, float sensitivity, OverScroller scroller, ScrollCallback callback) { Util.check(target, "target view can't be null."); Util.check(scroller, null); Util.check(callback, "ScrollCallback can't be null"); final ViewConfiguration vc = ViewConfiguration.get(target.getContext()); this.mTag = target.getClass().getSimpleName(); this.mTarget = target; this.mCallback = callback; this.mScroller = scroller; this.mTouchSlop = (int) (vc.getScaledTouchSlop() * (1 / sensitivity)); this.mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity(); this.mMinFlingVelocity = vc.getScaledMinimumFlingVelocity(); } public OverScroller getScroller() { return mScroller; } public int getTouchSlop() { return mTouchSlop; } public float getMinFlingVelocity() { return mMinFlingVelocity; } public float getMaxFlingVelocity() { return mMaxFlingVelocity; } public View getTarget() { return mTarget; } @Override public void dispatchOnScrolled(int dx, int dy) { // Pass the current scrollX/scrollY values; no actual change in these properties occurred // but some general-purpose code may choose to respond to changes this way. /* final int scrollX = mTarget.getScrollX(); final int scrollY = mTarget.getScrollY(); mTarget.onScrollChanged(scrollX, scrollY, scrollX, scrollY);*/ // Invoke listeners last. Subclassed view methods always handle the event first. // All internal state is consistent by the time listeners are invoked. if (mScrollListeners != null && mScrollListeners.size() > 0) { for (OnScrollChangeListener l : mScrollListeners) { if (l != null) { l.onScrolled(mTarget, dx, dy); } } } // Pass the real deltas to onScrolled, the RecyclerView-specific method. onScrolled(dx, dy); } /** * Called when the scroll position of this view changes. Subclasses should use * this method to respond to scrolling within the adapter's data set instead of an explicit * listener. this is called in {@link #dispatchOnScrolled(int, int)}. * <p/> * <p>This method will always be invoked before listeners. If a subclass needs to perform * any additional upkeep or bookkeeping after scrolling but before listeners run, * this is a good place to do so.</p> * * @param dx horizontal distance scrolled in pixels * @param dy vertical distance scrolled in pixels */ protected void onScrolled(int dx, int dy) { mCallback.onScrolled(dx, dy); } @Override public int getScrollState() { return mScrollState; } @Override public void setScrollState(int state) { if (state == mScrollState) { return; } if (DEBUG) { Log.d(mTag, "setting scroll state to " + state + " from " + mScrollState, new Exception()); } mScrollState = state; if (state != SCROLL_STATE_SETTLING) { stopScrollerInternal(); } dispatchOnScrollStateChanged(state); } protected void stopScrollerInternal() { if (!mScroller.isFinished()) { mScroller.abortAnimation(); } } /** * dispatch the scroll state change, this is called in {@link #setScrollState(int)}. * * @param state the target scroll state. */ protected void dispatchOnScrollStateChanged(int state) { if (mScrollListeners != null && mScrollListeners.size() > 0) { for (OnScrollChangeListener l : mScrollListeners) { if (l != null) { l.onScrollStateChanged(mTarget, state); } } } } @Override public void scrollBy(int dx, int dy) { scrollTo(mTarget.getScrollX() + dx, mTarget.getScrollY() + dy); } /** * {@inheritDoc}. Note: this is similar to {@link View#scrollTo(int, int)}, but limit the range of scroll, * which is indicate by {@link ScrollCallback#getMaximumXScrollDistance(View)} with {@link ScrollCallback#getMaximumYScrollDistance(View)}. * * @param x the x position to scroll to * @param y the y position to scroll to */ @Override public void scrollTo(int x, int y) { mTarget.scrollTo(Math.min(x, mCallback.getMaximumXScrollDistance(mTarget)), Math.min(y, mCallback.getMaximumYScrollDistance(mTarget))); } @Override public void smoothScrollBy(int dx, int dy) { if (mTarget instanceof ViewGroup && ((ViewGroup) mTarget).getChildCount() == 0) { // Nothing to do. return; } long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; if (duration > ANIMATED_SCROLL_GAP) { // design from scrollView final int scrollX = mTarget.getScrollX(); final int scrollY = mTarget.getScrollY(); final int maxX = mCallback.getMaximumXScrollDistance(mTarget); final int maxY = mCallback.getMaximumYScrollDistance(mTarget); if ((scrollX + dx) > maxX) { dx -= scrollX + dx - maxX; } if ((scrollY + dy) > maxY) { dy -= scrollY + dy - maxY; } setScrollState(SCROLL_STATE_SETTLING); mScroller.startScroll(scrollX, scrollY, dx, dy); ViewCompat.postInvalidateOnAnimation(mTarget); } else { if (!mScroller.isFinished()) { mScroller.abortAnimation(); } mTarget.scrollBy(dx, dy); } mLastScroll = AnimationUtils.currentAnimationTimeMillis(); } @Override public final void smoothScrollTo(int x, int y) { smoothScrollBy(x - mTarget.getScrollX(), y - mTarget.getScrollY()); } @Override public void stopScroll() { setScrollState(SCROLL_STATE_IDLE); stopScrollerInternal(); } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) {//true if not finish if(DEBUG){ Log.i(mTag, "computeScroll: scroll not finished: currX = " + mScroller.getCurrX() + " ,currY = " + mScroller.getCurrY()); } mTarget.scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); ViewCompat.postInvalidateOnAnimation(mTarget); } } @Override public boolean isScrollFinish(){ return mScroller.isFinished(); } @Override public boolean fling(float velocityX, float velocityY) { final boolean canScrollHorizontal = mCallback.canScrollHorizontally(mTarget); final boolean canScrollVertical = mCallback.canScrollVertically(mTarget); if (!canScrollHorizontal || Math.abs(velocityX) < mMinFlingVelocity) { velocityX = 0; } if (!canScrollVertical || Math.abs(velocityY) < mMinFlingVelocity) { velocityY = 0; } if (velocityX == 0 && velocityY == 0) { // If we don't have any velocity, return false return false; } return onFling(canScrollHorizontal, canScrollVertical, velocityX, velocityY); } @Override public void addOnScrollChangeListener(OnScrollChangeListener l) { if (mScrollListeners == null) { mScrollListeners = new CopyOnWriteArrayList<>(); } mScrollListeners.add(l); } @Override public void removeOnScrollChangeListener(OnScrollChangeListener l) { if (mScrollListeners != null) { mScrollListeners.remove(l); } } @Override public boolean hasOnScrollChangeListener(OnScrollChangeListener l) { return mScrollListeners != null && mScrollListeners.contains(l); } /** * do fling , this method is called in {@link #fling(float, float)} * * @param canScrollHorizontal if can scroll in Horizontal * @param canScrollVertical if can scroll in Vertical * @param velocityX the velocity of X * @param velocityY the velocity of y * @return true if the fling was started. */ protected boolean onFling(boolean canScrollHorizontal, boolean canScrollVertical, float velocityX, float velocityY) { if (canScrollHorizontal || canScrollVertical) { setScrollState(SCROLL_STATE_SETTLING); velocityX = Math.max(-mMaxFlingVelocity, Math.min(velocityX, mMaxFlingVelocity)); velocityY = Math.max(-mMaxFlingVelocity, Math.min(velocityY, mMaxFlingVelocity)); mScroller.fling(mTarget.getScrollX(), mTarget.getScrollY(), (int) velocityX, (int) velocityY, 0, canScrollHorizontal ? mCallback.getMaximumXScrollDistance(mTarget) : 0, 0, canScrollVertical ? mCallback.getMaximumYScrollDistance(mTarget) : 0 ); //TODO why recyclerView use mScroller.fling(0, 0, (int)velocityX, (int)velocityY,Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE); ViewCompat.postInvalidateOnAnimation(mTarget); return true; } return false; } /** * get the scroll state as string log. * @param state the scroll state. * @return the state as string */ public static String getScrollStateString(int state) { switch (state) { case SCROLL_STATE_DRAGGING: return "SCROLL_STATE_DRAGGING"; case SCROLL_STATE_SETTLING: return "SCROLL_STATE_SETTLING"; case SCROLL_STATE_IDLE: return "SCROLL_STATE_IDLE"; default: return "unknown state"; } } /** * the scroll callback of {@link ScrollHelper}. */ public static abstract class ScrollCallback { /** * if can scroll in Horizontal * * @param target the target view. * @return true if can scroll in Horizontal */ public abstract boolean canScrollHorizontally(View target); /** * if can scroll in Vertical * * @param target the target view. * @return true if can scroll in Vertical */ public abstract boolean canScrollVertically(View target); /** * get the maximum x scroll distance of the target view. * * @param target the target view. * @return the maximum x scroll distance */ public int getMaximumXScrollDistance(View target) { return target.getWidth(); } /** * get the maximum y scroll distance of the target view. * * @param target the target view. * @return the maximum y scroll distance */ public int getMaximumYScrollDistance(View target) { return target.getHeight(); } /** * called in {@link ScrollHelper#dispatchOnScrolled(int, int)}. * * @param dx the delta x * @param dy the delta y */ public void onScrolled(int dx, int dy) { } } }
package assemble; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.concurrent.atomic.AtomicInteger; import jgi.BBMerge; import kmer.KmerTableSet; import stream.ByteBuilder; import stream.ConcurrentReadInputStream; import stream.Read; import ukmer.AbstractKmerTableU; import ukmer.HashArrayU1D; import ukmer.HashForestU; import ukmer.Kmer; import ukmer.KmerNodeU; import ukmer.KmerTableSetU; import align2.IntList; import align2.ListNum; import align2.LongList; import align2.Shared; import align2.Tools; import dna.AminoAcid; import dna.Parser; import dna.Timer; /** * Short-kmer assembler based on KmerCountExact. * @author Brian Bushnell * @date May 15, 2015 * */ public class Tadpole2 extends Tadpole { /** * Code entrance from the command line. * @param args Command line arguments */ public static void main(String[] args){ args=Parser.parseConfig(args); if(Parser.parseHelp(args)){ printOptions(); System.exit(0); } Timer t=new Timer(), t2=new Timer(); t.start(); t2.start(); //Create a new CountKmersExact instance Tadpole2 wog=new Tadpole2(args, true); t2.stop(); outstream.println("Initialization Time: \t"+t2); ///And run it wog.process(t); } /** * Constructor. * @param args Command line arguments */ public Tadpole2(String[] args, boolean setDefaults){ super(args, setDefaults); final int extraBytesPerKmer; { int x=0; if(useOwnership){x+=4;} if(processingMode==correctMode){} else if(processingMode==contigMode || processingMode==extendMode){x+=1;} extraBytesPerKmer=x; } tables=new KmerTableSetU(args, extraBytesPerKmer); assert(kbig==tables.kbig); // kbig=tables.kbig; ksmall=tables.k; // k2=tables.k2; // ways=tables.ways; } /*--------------------------------------------------------------*/ /*---------------- Outer Methods ----------------*/ /*--------------------------------------------------------------*/ /*--------------------------------------------------------------*/ /*---------------- Inner Methods ----------------*/ /*--------------------------------------------------------------*/ @Override void initializeOwnership(){ tables.initializeOwnership(); } @Override long shave(boolean shave, boolean rinse){ final Shaver2 shaver=new Shaver2(tables, THREADS); long sum=0; for(int i=0; i<maxShaveDepth; i++){ int a=1, b=maxShaveDepth, c=i+1; // if(i>3){Shaver2.verbose2=true;} outstream.println("\nShave("+a+", "+b+", "+c+")"); long removed=shaver.shave(a, b, c, Tools.max(minContigLen, shaveDiscardLen), shaveExploreDist, shave, rinse); sum+=removed; if(removed<100 || i>2){break;} } System.err.println(); return sum; } @Override public long loadKmers(Timer t){ tables.process(t); return tables.kmersLoaded; } /*--------------------------------------------------------------*/ /*---------------- Recall Methods ----------------*/ /*--------------------------------------------------------------*/ public final int getCount(Kmer kmer){return tables.getCount(kmer);} private final boolean claim(Kmer kmer, int id){return tables.claim(kmer, id);} private final boolean doubleClaim(ByteBuilder bb, int id/*, long rid*/, Kmer kmer){return tables.doubleClaim(bb, id/*, rid*/, kmer);} private final boolean claim(ByteBuilder bb, int id, /*long rid, */boolean earlyExit, Kmer kmer){return tables.claim(bb, id/*, rid*/, earlyExit, kmer);} private final boolean claim(byte[] array, int len, int id, /*long rid, */boolean earlyExit, Kmer kmer){return tables.claim(array, len, id/*, rid*/, earlyExit, kmer);} private final int findOwner(Kmer kmer){return tables.findOwner(kmer);} private final int findOwner(ByteBuilder bb, int id, Kmer kmer){return tables.findOwner(bb, id, kmer);} private final int findOwner(byte[] array, int len, int id, Kmer kmer){return tables.findOwner(array, len, id, kmer);} private final void release(Kmer kmer, int id){tables.release(kmer, id);} private final void release(ByteBuilder bb, int id, Kmer kmer){tables.release(bb, id, kmer);} private final void release(byte[] array, int len, int id, Kmer kmer){tables.release(array, len, id, kmer);} private final int fillRightCounts(Kmer kmer, int[] counts){return tables.fillRightCounts(kmer, counts);} private final int fillLeftCounts(Kmer kmer, int[] counts){return tables.fillLeftCounts(kmer, counts);} private final StringBuilder toText(Kmer kmer){return AbstractKmerTableU.toText(kmer);} private final StringBuilder toText(long[] key, int k){return AbstractKmerTableU.toText(key, k);} /*--------------------------------------------------------------*/ /*---------------- Inner Classes ----------------*/ /*--------------------------------------------------------------*/ /*--------------------------------------------------------------*/ /*---------------- BuildThread ----------------*/ /*--------------------------------------------------------------*/ @Override BuildThread makeBuildThread(int id, int mode, ConcurrentReadInputStream[] crisa){ return new BuildThread(id, mode, crisa); } /** * Builds contigs. */ private class BuildThread extends AbstractBuildThread{ public BuildThread(int id_, int mode_, ConcurrentReadInputStream[] crisa_){ super(id_, mode_, crisa_); } @Override public void run(){ if(crisa==null || crisa.length==0){ //Build from kmers if(id==0){System.err.print("Seeding with min count = ");} String comma=""; for(int i=contigPasses-1; i>0; i--){ minCountSeedCurrent=(int)Tools.min(Integer.MAX_VALUE, Tools.max(minCountSeed+i, (long)Math.floor((minCountSeed)*Math.pow(contigPassMult, i)*0.92-0.25) )); if(id==0){ System.err.print(comma+minCountSeedCurrent); comma=", "; } while(processNextTable(nextTable[i])){} while(processNextVictims(nextVictims[i])){} } //Final pass minCountSeedCurrent=minCountSeed; if(id==0){System.err.println(comma+minCountSeedCurrent);} while(processNextTable(nextTable[0])){} while(processNextVictims(nextVictims[0])){} }else{ //Extend reads for(ConcurrentReadInputStream cris : crisa){ synchronized(crisa){ if(!cris.started()){ cris.start(); } } run(cris); } } } private boolean processNextTable(AtomicInteger aint){ final int tnum=aint.getAndAdd(1); if(tnum>=tables.ways){return false;} final HashArrayU1D table=tables.getTable(tnum); final int max=table.arrayLength(); if(verbose && id==0){System.err.println("Processing table "+tnum+", size "+table.size()+", length "+max);} for(int cell=0; cell<max; cell++){ if(verbose && id==0){System.err.println("Processing cell "+cell);} int x=processCell(table, cell, myKmer); } return true; } private boolean processNextVictims(AtomicInteger aint){ final int tnum=aint.getAndAdd(1); if(tnum>=tables.ways){return false;} final HashArrayU1D table=tables.getTable(tnum); final HashForestU forest=table.victims(); if(verbose && id==0){System.err.println("Processing forest "+tnum+", size "+forest.size());} final int max=forest.arrayLength(); for(int cell=0; cell<max; cell++){ KmerNodeU kn=forest.getNode(cell); int x=traverseKmerNodeU(kn); } return true; } private int processCell(HashArrayU1D table, int cell, Kmer kmer){ int count=table.readCellValue(cell); if(count<minCountSeedCurrent){ if(verbose){System.err.println("For cell "+cell+", count="+count);} return 0; } kmer=table.fillKmer(cell, kmer); // assert(kmer.verify(false)); // assert(kmer.verify(true)); if(verbose){outstream.println("id="+id+" processing cell "+cell+"; \tkmer="+kmer);} if(useOwnership){ int owner=table.getCellOwner(cell); if(verbose){outstream.println("Owner is initially "+owner);} if(owner>-1){return 0;} owner=table.setOwner(kmer, id, cell); if(verbose){outstream.println("Owner is now "+owner);} if(owner!=id){return 0;} } return processKmer(kmer); } private int traverseKmerNodeU(KmerNodeU kn){ int sum=0; if(kn!=null){ sum+=processKmerNodeU(kn); if(kn.left()!=null){ sum+=traverseKmerNodeU(kn.left()); } if(kn.right()!=null){ sum+=traverseKmerNodeU(kn.right()); } } return sum; } private int processKmerNodeU(KmerNodeU kn){ final long[] key=kn.pivot(); final int count=kn.getValue(key); if(count<minCountSeedCurrent){return 0;} if(verbose){outstream.println("id="+id+" processing KmerNodeU; \tkmer="+Arrays.toString(key)+"\t"+toText(key, ksmall));} if(useOwnership){ int owner=kn.getOwner(key); if(verbose){outstream.println("Owner is initially "+owner);} if(owner>-1){return 0;} owner=kn.setOwner(key, id); if(verbose){outstream.println("Owner is now "+owner);} if(owner!=id){return 0;} } myKmer.setFrom(key); return processKmer(myKmer); } private int processKmer(Kmer kmer){ byte[] contig=makeContig(builderT, kmer, true); if(contig!=null){ float coverage=tables.calcCoverage(contig, contig.length, kmer); if(coverage<minCoverage){return 0;} if(verbose){System.err.println("Added "+contig.length);} final long num=contigNum.incrementAndGet(); Read r=new Read(contig, -1, -1, -1, "*", null, num, 0); float gc=r.gc(); r.id="contig_"+num+",length="+contig.length+",cov="+String.format("%.1f", coverage)+",gc="+String.format("%.3f", gc); contigs.add(r); return contig.length; }else{ if(verbose){System.err.println("Created null contig.");} } return 0; } private void run(ConcurrentReadInputStream cris){ ListNum<Read> ln=cris.nextList(); ArrayList<Read> reads=(ln!=null ? ln.list : null); //While there are more reads lists... while(reads!=null && reads.size()>0){ //For each read (or pair) in the list... for(int i=0; i<reads.size(); i++){ final Read r1=reads.get(i); final Read r2=r1.mate; processReadPair(r1, r2); } //Fetch a new read list cris.returnList(ln.id, ln.list.isEmpty()); ln=cris.nextList(); reads=(ln!=null ? ln.list : null); } cris.returnList(ln.id, ln.list.isEmpty()); } private void processReadPair(Read r1, Read r2){ if(verbose){System.err.println("Considering read "+r1.id+" "+new String(r1.bases));} readsInT++; basesInT+=r1.length(); if(r2!=null){ readsInT++; basesInT+=r2.length(); } if(mode==insertMode){ int x=BBMerge.findOverlapStrict(r1, r2, false); if(x<1){ x=findInsertSize(r1, r2, rightCounts, myKmer, myKmer2); } insertSizes.increment(Tools.max(x, 0)); return; } if(ecco && r1!=null && r2!=null && !r1.discarded() && !r2.discarded()){BBMerge.findOverlapStrict(r1, r2, true);} if(r1!=null){ if(r1.discarded()){ lowqBasesT+=r1.length(); lowqReadsT++; }else{ byte[] contig=makeContig(r1.bases, builderT, r1.numericID, myKmer); if(contig!=null){ if(verbose){System.err.println("Added "+contig.length);} final long num=contigNum.incrementAndGet(); Read temp=new Read(contig, -1, -1, -1, "contig_"+num+"_length_"+contig.length, null, num, 0); contigs.add(temp); } } } if(r2!=null){ if(r2.discarded()){ lowqBasesT+=r2.length(); lowqReadsT++; }else{ byte[] contig=makeContig(r2.bases, builderT, r1.numericID, myKmer); if(contig!=null){ if(verbose){System.err.println("Added "+contig.length);} final long num=contigNum.incrementAndGet(); Read temp=new Read(contig, -1, -1, -1, "contig_"+num+"_length_"+contig.length, null, num, 0); contigs.add(temp); } } } } /** From kmers */ private byte[] makeContig(final ByteBuilder bb, Kmer kmer, boolean alreadyClaimed){ bb.setLength(0); bb.appendKmer(kmer); if(verbose){outstream.println("Filled bb: "+bb);} final int initialLength=bb.length(); assert(initialLength==kbig); if(initialLength<kbig){return null;} boolean success=(alreadyClaimed || !useOwnership ? true : claim(kmer, id)); if(verbose){System.err.println("Thread "+id+" checking owner after setting: "+findOwner(bb, id, kmer));} if(!success){ assert(bb.length()==kbig); // release(bb, id); //no need to release return null; } if(verbose /*|| true*/){System.err.println("Thread "+id+" building contig; initial length "+bb.length());} if(verbose){System.err.println("Extending to right.");} { final int status=extendToRight(bb, leftCounts, rightCounts, id, kmer); if(status==DEAD_END){ //do nothing }else if(status==LOOP){//TODO //special case - handle specially, for a loop with no obvious junction, e.g. long tandem repeat. //Perhaps, the last kmer should be reclassified as a junction and removed. }else if(status==BAD_SEED){ assert(bb.length()==kbig); release(kmer, id); return null; }else{ if(bb.length()==kbig){ if(status==BAD_OWNER){ release(kmer, id); return null; }else if(status==BRANCH){ release(kmer, id); return null; }else{ throw new RuntimeException("Bad return value: "+status); } }else{ if(status==BAD_OWNER){ release(bb, id, kmer); return null; }else if(status==BRANCH){ //do nothing }else{ throw new RuntimeException("Bad return value: "+status); } } } } // success=extendToRight(bb, leftCounts, rightCounts, id, kmer); // if(!success){ // release(bb, id, kmer); // return null; // } bb.reverseComplementInPlace(); if(verbose /*|| true*/){System.err.println("Extending rcomp to right; current length "+bb.length());} { final int status=extendToRight(bb, leftCounts, rightCounts, id, kmer); if(status==DEAD_END){ //do nothing }else if(status==LOOP){//TODO //special case - handle specially, for a loop with no obvious junction, e.g. long tandem repeat. //Perhaps, the last kmer should be reclassified as a junction and removed. }else if(status==BAD_SEED){ assert(false) : bb;//This should never happen. assert(bb.length()==kbig); release(kmer, id); return null; }else{ if(status==BAD_OWNER){ release(bb, id, kmer); return null; }else if(status==BRANCH){ //do nothing }else{ throw new RuntimeException("Bad return value: "+status); } } } // success=extendToRight(bb, leftCounts, rightCounts, id, kmer); // if(!success){ // release(bb, id, kmer); // return null; // } if(verbose /*|| true*/){System.err.println("Final length for thread "+id+": "+bb.length());} // if(useOwnership && THREADS==1){assert(claim(bases, bases.length, id, rid));} success=(useOwnership ? doubleClaim(bb, id, kmer) : true); if(verbose /*|| true*/){System.err.println("Success for thread "+id+": "+success);} if(trimEnds>0){bb.trimByAmount(trimEnds, trimEnds);} if(bb.length()>=initialLength+minExtension && bb.length()>=minContigLen){ if(success){ bb.reverseComplementInPlace(); return bb.toBytes(); }else{ // assert(false) : bb.length()+", "+id; release(bb, id, kmer); return null; } } if(verbose /*|| true*/){System.err.println("Contig was too short for "+id+": "+bb.length());} return null; } /** From a seed */ private byte[] makeContig(final byte[] bases, final ByteBuilder bb, long rid, final Kmer kmer){ if(bases==null || bases.length<kbig){return null;} // if(verbose /*|| true*/){System.err.println("Thread "+id+" checking owner: "+findOwner(bases, bases.length, id));} int owner=useOwnership ? findOwner(bases, bases.length, id, kmer) : -1; if(owner>=id){return null;} boolean success=(useOwnership ? claim(bases, bases.length, id, true, kmer) : true); if(verbose /*|| true*/){System.err.println("Thread "+id+" checking owner after setting: "+findOwner(bases, bases.length, id, kmer));} if(!success){ release(bases, bases.length, id, kmer); return null; } if(verbose /*|| true*/){System.err.println("Thread "+id+" building contig; initial length "+bases.length);} bb.setLength(0); bb.append(bases); if(verbose){System.err.println("Extending to right.");} { final int status=extendToRight(bb, leftCounts, rightCounts, id, kmer); if(status==DEAD_END){ //do nothing }else if(status==LOOP){//TODO //special case - handle specially, for a loop with no obvious junction, e.g. long tandem repeat. //Perhaps, the last kmer should be reclassified as a junction and removed. }else if(status==BAD_SEED){ //do nothing }else{ if(status==BAD_OWNER){ release(bb.array, bb.length(), id, kmer); return null; }else if(status==BRANCH){ //do nothing }else{ throw new RuntimeException("Bad return value: "+status); } } } // success=extendToRight(bb, leftCounts, rightCounts, id, kmer); // if(!success){ // release(bb.array, bb.length(), id, kmer); // return null; // } bb.reverseComplementInPlace(); if(verbose /*|| true*/){System.err.println("Extending rcomp to right; current length "+bb.length());} { final int status=extendToRight(bb, leftCounts, rightCounts, id, kmer); if(status==DEAD_END){ //do nothing }else if(status==LOOP){//TODO //special case - handle specially, for a loop with no obvious junction, e.g. long tandem repeat. //Perhaps, the last kmer should be reclassified as a junction and removed. }else if(status==BAD_SEED){ //do nothing }else{ if(status==BAD_OWNER){ release(bb.array, bb.length(), id, kmer); return null; }else if(status==BRANCH){ //do nothing }else{ throw new RuntimeException("Bad return value: "+status); } } } // success=extendToRight(bb, leftCounts, rightCounts, id, kmer); // if(!success){ // release(bb.array, bb.length(), id, kmer); // return null; // } if(verbose /*|| true*/){System.err.println("Final length for thread "+id+": "+bb.length());} // if(useOwnership && THREADS==1){assert(claim(bases, bases.length, id, rid));} success=(useOwnership ? doubleClaim(bb, id, kmer) : true); if(verbose /*|| true*/){System.err.println("Success for thread "+id+": "+success);} if(bb.length()>=bases.length+minExtension && bb.length()>=minContigLen){ if(success){ bb.reverseComplementInPlace(); return bb.toBytes(); }else{ // assert(false) : bb.length()+", "+id; release(bb.array, bb.length(), id, kmer); return null; } } if(verbose /*|| true*/){System.err.println("Contig was too short for "+id+": "+bb.length());} return null; } /*--------------------------------------------------------------*/ private final Kmer myKmer=new Kmer(kbig); private final Kmer myKmer2=new Kmer(kbig); } /*--------------------------------------------------------------*/ /*---------------- Extension Methods ----------------*/ /*--------------------------------------------------------------*/ public int findInsertSize(Read r1, Read r2, int[] rightCounts, Kmer kmer1, Kmer kmer2){ kmer1=tables.rightmostKmer(r1.bases, r1.length(), kmer1); kmer2=tables.rightmostKmer(r2.bases, r2.length(), kmer2); if(kmer1==null || kmer2==null){return -1;} final int x=measureInsert(kmer1, kmer2, 24000, rightCounts); if(x<0){return -1;} return r1.length()+r2.length()+x-kbig;//TODO: May be off by 1. } /* (non-Javadoc) * @see assemble.Tadpole#extendRead(stream.Read, stream.ByteBuilder, int[], int[], int) */ @Override public int extendRead(Read r, ByteBuilder bb, int[] leftCounts, int[] rightCounts, int distance) { return extendRead(r, bb, leftCounts, rightCounts, distance, localKmer.get()); } public int extendRead(Read r, ByteBuilder bb, int[] leftCounts, int[] rightCounts, int distance, final Kmer kmer){ final int initialLen=r.length(); if(initialLen<kbig){return 0;} bb.setLength(0); bb.append(r.bases); Kmer temp=tables.rightmostKmer(bb, kmer); if(temp==null){return 0;} final int extension=extendToRight2_inner(bb, leftCounts, rightCounts, distance, true, kmer); if(extension>0){ r.bases=bb.toBytes(); if(r.quality!=null){ final byte q=Shared.FAKE_QUAL; r.quality=Arrays.copyOf(r.quality, r.bases.length); for(int i=initialLen; i<r.quality.length; i++){ r.quality[i]=q; } } } assert(extension==r.length()-initialLen); return extension; } /** Returns distance between the two kmers, or -1 */ public int measureInsert(final Kmer kmer1, final Kmer kmer2, final int maxlen, final int[] rightCounts){ int len=0; { int count=tables.getCount(kmer2); if(count<minCountSeed){return -1;} } int count=tables.getCount(kmer1); if(count<minCountSeed){return -1;} if(count<minCountSeed){ if(verbose){outstream.println("Returning because count was too low: "+count);} return -1; } int rightMaxPos=fillRightCounts(kmer1, rightCounts); int rightMax=rightCounts[rightMaxPos]; // int rightSecondPos=Tools.secondHighestPosition(rightCounts); // int rightSecond=rightCounts[rightSecondPos]; if(rightMax<minCountExtend){return -1;} // if(isJunction(rightMax, rightSecond)){return -1;} while(!kmer1.equals(kmer2) && len<maxlen){ //Generate the new kmer // final byte b=AminoAcid.numberToBase[rightMaxPos]; final long x=rightMaxPos; kmer1.addRightNumeric(x); assert(tables.getCount(kmer1)==rightMax); count=rightMax; assert(count>=minCountExtend) : count; rightMaxPos=fillRightCounts(kmer1, rightCounts); rightMax=rightCounts[rightMaxPos]; // rightSecondPos=Tools.secondHighestPosition(rightCounts); // rightSecond=rightCounts[rightSecondPos]; if(verbose){ outstream.println("kmer: "+kmer1); outstream.println("Counts: "+count+", "+Arrays.toString(rightCounts)); outstream.println("rightMaxPos="+rightMaxPos); outstream.println("rightMax="+rightMax); // outstream.println("rightSecondPos="+rightSecondPos); // outstream.println("rightSecond="+rightSecond); } if(rightMax<minCountExtend){ if(verbose){outstream.println("Breaking because highest right was too low:"+rightMax);} break; } // if(isJunction(rightMax, rightSecond)){return -1;} len++; } return len>=maxlen ? -1 : len; } /** * Extend these bases into a contig. * Stops at both left and right junctions. * Claims ownership. */ public int extendToRight(final ByteBuilder bb, final int[] leftCounts, final int[] rightCounts, final int id, Kmer kmer){ if(bb.length()<kbig){return BAD_SEED;} kmer.clear(); kmer=tables.rightmostKmer(bb, kmer); if(kmer==null || kmer.len<kbig){return BAD_SEED;} assert(kmer.len==kbig); /* Now the trailing kmer has been initialized. */ if(verbose){ System.err.println("extendToRight kmer="+kmer+", bb="+bb); } HashArrayU1D table=tables.getTable(kmer); int count=table.getValue(kmer); if(count<minCountSeed){ if(verbose){outstream.println("Returning because count was too low: "+count);} return BAD_SEED; } int owner=(useOwnership ? table.getOwner(kmer) : id); if(verbose){outstream.println("Owner: "+owner);} if(owner>id){return BAD_OWNER;} int leftMaxPos=0; int leftMax=minCountExtend; int leftSecondPos=1; int leftSecond=0; if(leftCounts!=null){ leftMaxPos=fillLeftCounts(kmer, leftCounts); leftMax=leftCounts[leftMaxPos]; leftSecondPos=Tools.secondHighestPosition(leftCounts); leftSecond=leftCounts[leftSecondPos]; } int rightMaxPos=fillRightCounts(kmer, rightCounts); int rightMax=rightCounts[rightMaxPos]; int rightSecondPos=Tools.secondHighestPosition(rightCounts); int rightSecond=rightCounts[rightSecondPos]; if(verbose){ outstream.println("kmer: "+toText(kmer)); outstream.println("Counts: "+count+", "+(leftCounts==null ? "null" : Arrays.toString(leftCounts))+", "+Arrays.toString(rightCounts)); outstream.println("leftMaxPos="+leftMaxPos); outstream.println("leftMax="+leftMax); outstream.println("leftSecondPos="+leftSecondPos); outstream.println("leftSecond="+leftSecond); outstream.println("rightMaxPos="+rightMaxPos); outstream.println("rightMax="+rightMax); outstream.println("rightSecondPos="+rightSecondPos); outstream.println("rightSecond="+rightSecond); } if(rightMax<minCountExtend){return DEAD_END;} if(isJunction(rightMax, rightSecond, leftMax, leftSecond)){return BRANCH;} if(useOwnership){ owner=table.setOwner(kmer, id); if(verbose){outstream.println("A. Owner is now "+id+" for kmer "+kmer);} if(owner!=id){ if(verbose){outstream.println("Returning early because owner was "+owner+" for thread "+id+".");} return BAD_OWNER; } } final int maxLen=Tools.min((extendRight<0 ? maxContigLen : bb.length()+extendRight), maxContigLen); while(owner==id && bb.length()<maxLen){ //Generate the new kmer final byte b=AminoAcid.numberToBase[rightMaxPos]; //Now consider the next kmer final long evicted=kmer.addRightNumeric(rightMaxPos); table=tables.getTable(kmer); assert(table.getValue(kmer)==rightMax); count=rightMax; assert(count>=minCountExtend) : count; if(leftCounts!=null){ leftMaxPos=fillLeftCounts(kmer, leftCounts); leftMax=leftCounts[leftMaxPos]; leftSecondPos=Tools.secondHighestPosition(leftCounts); leftSecond=leftCounts[leftSecondPos]; } rightMaxPos=fillRightCounts(kmer, rightCounts); rightMax=rightCounts[rightMaxPos]; rightSecondPos=Tools.secondHighestPosition(rightCounts); rightSecond=rightCounts[rightSecondPos]; if(verbose){ outstream.println("kmer: "+toText(kmer)); outstream.println("Counts: "+count+", "+(leftCounts==null ? "null" : Arrays.toString(leftCounts))+", "+Arrays.toString(rightCounts)); outstream.println("leftMaxPos="+leftMaxPos); outstream.println("leftMax="+leftMax); outstream.println("leftSecondPos="+leftSecondPos); outstream.println("leftSecond="+leftSecond); outstream.println("rightMaxPos="+rightMaxPos); outstream.println("rightMax="+rightMax); outstream.println("rightSecondPos="+rightSecondPos); outstream.println("rightSecond="+rightSecond); } if(isJunction(rightMax, rightSecond, leftMax, leftSecond)){ if(verbose){outstream.println("B: Breaking because isJunction("+rightMax+", "+rightSecond+", "+leftMax+", "+leftSecond+")");} return BRANCH; } if(leftCounts!=null && leftMaxPos!=evicted){ if(verbose){outstream.println("B: Breaking because of hidden branch: leftMaxPos!=evicted ("+leftMaxPos+"!="+evicted+")" + "\nleftMaxPos="+leftMaxPos+", leftMax="+leftMax+", leftSecondPos="+leftSecondPos+", leftSecond="+leftSecond);} return BRANCH; } bb.append(b); if(verbose){outstream.println("Added base "+(char)b);} if(useOwnership){ owner=table.getOwner(kmer); if(verbose){outstream.println("Owner is initially "+id+" for key "+kmer);} if(owner==id){//loop detection if(verbose /*|| true*/){ // outstream.println(new String(bb.array, bb.length()-31, 31)); outstream.println(bb); outstream.println(toText(kmer)); outstream.println("Breaking because owner was "+owner+" for thread "+id+"."); } return LOOP; } owner=table.setOwner(kmer, id); if(verbose){outstream.println("B. Owner is now "+id+" for kmer "+kmer);} } if(rightMax<minCountExtend){ if(verbose){outstream.println("B: Breaking because highest right was too low:"+rightMax);} return DEAD_END; } } assert(owner!=id); if(verbose /*|| true*/){ outstream.println("Current contig: "+bb+"\nReturning because owner was "+owner+" for thread "+id+"."); } return BAD_OWNER; } @Override public int extendToRight2(final ByteBuilder bb, final int[] leftCounts, final int[] rightCounts, final int distance, boolean includeJunctionBase){ initializeThreadLocals(); return extendToRight2(bb, leftCounts, rightCounts, distance, includeJunctionBase, localKmer.get()); } @Override public int extendToRight2(final ByteBuilder bb, final int[] leftCounts, final int[] rightCounts, final int distance, boolean includeJunctionBase, Kmer kmer){ if(verbose || verbose2){outstream.println("Entering extendToRight2 (no kmers).");} final int initialLength=bb.length(); if(initialLength<kbig){return 0;} kmer.clear(); kmer=tables.rightmostKmer(bb, kmer); if(kmer==null || kmer.len<kbig){return 0;} assert(kmer.len==kbig); return extendToRight2_inner(bb, leftCounts, rightCounts, distance, includeJunctionBase, kmer); } /** * Extend these bases to the right by at most 'distance'. * Stops at right junctions only. * Does not claim ownership. */ private int extendToRight2_inner(final ByteBuilder bb, final int[] leftCounts, final int[] rightCounts, final int distance, boolean includeJunctionBase, Kmer kmer){ if(verbose || verbose2){outstream.println("Entering extendToRight2_inner (with kmers).");} final int initialLength=bb.length(); assert(kmer.len==kbig) : kmer.len+", "+kbig+", "+bb.length(); HashArrayU1D table=tables.getTable(kmer); int count=table.getValue(kmer); if(count<minCountSeed){ if(verbose || verbose2){outstream.println("Returning because count was too low: "+count+"<"+minCountSeed);} return 0; } int leftMaxPos=0; int leftMax=minCountExtend; int leftSecondPos=1; int leftSecond=0; if(leftCounts!=null){ leftMaxPos=fillLeftCounts(kmer, leftCounts); leftMax=leftCounts[leftMaxPos]; leftSecondPos=Tools.secondHighestPosition(leftCounts); leftSecond=leftCounts[leftSecondPos]; } int rightMaxPos=fillRightCounts(kmer, rightCounts); int rightMax=rightCounts[rightMaxPos]; int rightSecondPos=Tools.secondHighestPosition(rightCounts); int rightSecond=rightCounts[rightSecondPos]; if(verbose){ outstream.println("kmer: "+toText(kmer)); outstream.println("Counts: "+count+", "+Arrays.toString(rightCounts)); outstream.println("rightMaxPos="+rightMaxPos); outstream.println("rightMax="+rightMax); outstream.println("rightSecondPos="+rightSecondPos); outstream.println("rightSecond="+rightSecond); } if(rightMax<minCountExtend){ if(verbose || verbose2){outstream.println("Returning because rightMax was too low: "+rightMax+"<"+minCountExtend+"\n"+count+", "+Arrays.toString(rightCounts));} return 0; } if(isJunction(rightMax, rightSecond, leftMax, leftSecond)){ if(verbose || verbose2){outstream.println("Returning because isJunction: "+rightMax+", "+rightSecond+"; "+leftMax+", "+leftSecond);} return 0; } final int maxLen=Tools.min(bb.length()+distance, maxContigLen); while(bb.length()<maxLen){ //Generate the new kmer final byte b=AminoAcid.numberToBase[rightMaxPos]; //Now consider the next kmer final long evicted=kmer.addRightNumeric(rightMaxPos); table=tables.getTable(kmer); assert(table.getValue(kmer)==rightMax); count=rightMax; assert(count>=minCountExtend) : count; if(leftCounts!=null){ leftMaxPos=fillLeftCounts(kmer, leftCounts); leftMax=leftCounts[leftMaxPos]; leftSecondPos=Tools.secondHighestPosition(leftCounts); leftSecond=leftCounts[leftSecondPos]; } rightMaxPos=fillRightCounts(kmer, rightCounts); rightMax=rightCounts[rightMaxPos]; rightSecondPos=Tools.secondHighestPosition(rightCounts); rightSecond=rightCounts[rightSecondPos]; if(verbose){ outstream.println("kmer: "+toText(kmer)); outstream.println("Counts: "+count+", "+Arrays.toString(rightCounts)); outstream.println("rightMaxPos="+rightMaxPos); outstream.println("rightMax="+rightMax); outstream.println("rightSecondPos="+rightSecondPos); outstream.println("rightSecond="+rightSecond); } if(isJunction(rightMax, rightSecond, leftMax, leftSecond)){ if(includeJunctionBase && kmer.key()==kmer.array2()){//TODO: Does not work on palindromes. bb.append(b); if(verbose){outstream.println("Added base "+(char)b);} } break; } if(leftCounts!=null && leftMaxPos!=evicted){ if(verbose){outstream.println("B: Breaking because of hidden branch: leftMaxPos!=evicted ("+leftMaxPos+"!="+evicted+")" + "\nleftMaxPos="+leftMaxPos+", leftMax="+leftMax+", leftSecondPos="+leftSecondPos+", leftSecond="+leftSecond);} if(includeJunctionBase && kmer.key()==kmer.array2()){//TODO: Does not work on palindromes. bb.append(b); if(verbose){outstream.println("Added base "+(char)b);} } break; } bb.append(b); if(verbose){outstream.println("Added base "+(char)b);} if(rightMax<minCountExtend){ if(verbose || verbose2){outstream.println("C: Breaking because highest right was too low: "+rightMax+"<"+minCountExtend);} break; } } if(verbose || verbose2){System.err.println("Extended by "+(bb.length()-initialLength));} return bb.length()-initialLength; } /*--------------------------------------------------------------*/ /*---------------- Error Correction ----------------*/ /*--------------------------------------------------------------*/ @Override public int errorCorrect(Read r){ initializeThreadLocals(); int corrected=errorCorrect(r, localLeftCounts.get(), localRightCounts.get(), localIntList.get(), localByteBuilder.get(), null, localBitSet.get(), localKmer.get()); return corrected; } @Override public int errorCorrect(Read r, final int[] leftCounts, final int[] rightCounts, LongList kmers, IntList counts, final ByteBuilder bb, final int[] detectedArray, final BitSet bs, Kmer kmer){ return errorCorrect(r, leftCounts, rightCounts, counts, bb, detectedArray, bs, kmer); } public int errorCorrect(Read r, final int[] leftCounts, final int[] rightCounts, IntList counts, final ByteBuilder bb, final int[] detectedArray, final BitSet bs, final Kmer kmer){ final byte[] bases=r.bases; final byte[] quals=r.quality; if(detectedArray!=null){ detectedArray[0]=0; detectedArray[1]=0; detectedArray[2]=0; detectedArray[3]=0; } int valid=tables.fillCounts(bases, counts, kmer); if(valid<2){return 0;} int correctedPincer=0; int correctedTail=0; if(ECC_PINCER){ correctedPincer+=errorCorrectPincer(bases, quals, leftCounts, rightCounts, counts, bb, detectedArray, errorExtensionPincer, kmer); } if(ECC_TAIL || ECC_ALL){ int start=(ECC_ALL ? 0 : counts.size-kbig-1); // if(ECC_PINCER && detectedArray!=null && detectedArray[0]>correctedPincer){start=start-kbig;} correctedTail+=errorCorrectTail(bases, quals, leftCounts, rightCounts, counts, bb, detectedArray, start, errorExtensionTail, kmer); r.reverseComplement(); counts.reverse(); correctedTail+=errorCorrectTail(bases, quals, leftCounts, rightCounts, counts, bb, detectedArray, start, errorExtensionTail, kmer); r.reverseComplement(); counts.reverse(); } if(MARK_BAD_BASES>0){ int marked=markBadBases(bases, quals, counts, bs, MARK_BAD_BASES, MARK_DELTA_ONLY); detectedArray[3]=marked; } assert(detectedArray==null || (correctedPincer==detectedArray[1] && correctedTail==detectedArray[2])) : correctedPincer+", "+correctedTail+", "+Arrays.toString(detectedArray); // if(ECC_PINCER && correctedTail>0){ // valid=fillKmers(bases, kmers); // counts.reverse(); // correctedPincer+=errorCorrectPincer(bases, quals, leftCounts, rightCounts, kmers, counts, bb, detectedArray, errorExtensionPincer); // } return correctedPincer+correctedTail; } public int errorCorrectPincer(final byte[] bases, final byte[] quals, final int[] leftBuffer, final int[] rightBuffer, final IntList counts, final ByteBuilder bb, final int[] detectedArray, final int errorExtension, final Kmer kmer){ int detected=0; int corrected=0; //a is the index of the left kmer //b is a+1 //c is d-1 //d is the index of the right kmer //the base between the kmers is at a+k for(int a=0, d=kbig+1; d<counts.size; a++, d++){ final int aCount=counts.get(a); final int bCount=counts.get(a+1); final int cCount=counts.get(d-1); final int dCount=counts.get(d); if(isError(aCount, bCount) && isError(dCount, cCount) && isSimilar(aCount, dCount)){ if(verbose){ System.err.println("Found error: "+aCount+", "+bCount+", "+cCount+", "+dCount); } //Looks like a 1bp substitution; attempt to correct. detected++; int ret=correctSingleBasePincer(a, d, bases, quals, leftBuffer, rightBuffer, counts, bb, errorExtension, kmer); corrected+=ret; if(verbose){ System.err.println("Corrected error."); } }else{ if(verbose){ System.err.println("Not an error: "+aCount+", "+bCount+", "+cCount+", "+dCount+ "; "+isError(aCount, bCount)+", "+isError(dCount, cCount)+", "+isSimilar(aCount, dCount)); } } } // if(detected==0 && counts.get(0)>2 && counts.get(counts.size-1)>2){ // assert(!verbose); // verbose=true; // System.err.println("\n"+counts); // errorCorrectPincer(bases, quals, leftBuffer, rightBuffer, kmers, counts, bb, detectedArray); // assert(false); // } if(detectedArray!=null){ detectedArray[0]+=detected; detectedArray[1]+=corrected; } return corrected; } public int errorCorrectTail(final byte[] bases, final byte[] quals, final int[] leftBuffer, final int[] rightBuffer, final IntList counts, final ByteBuilder bb, final int[] detectedArray, final int startPos, final int errorExtension, final Kmer kmer){ if(bases.length<kbig+2*(1+errorExtension)){return 0;} int detected=0; int corrected=0; //a is the index of the left kmer //b is a+1 //the base between the kmers is at a+k for(int a=Tools.max(startPos, errorExtension), lim=counts.size-Tools.min(errorExtension, (errorExtension+3)/2); a<lim; a++){//errorExtension-1 final int aCount=counts.get(a); final int bCount=counts.get(a+1); if(isError(aCount, bCount) && isSimilar(aCount, a-errorExtension, a-1, counts) && isError(aCount, a+2, a+kbig, counts)){ if(verbose){ System.err.println("Found error: "+aCount+", "+bCount); } //Assume like a 1bp substitution; attempt to correct. detected++; int ret=correctSingleBaseRight(a, bases, quals, leftBuffer, rightBuffer, counts, bb, errorExtension, kmer); corrected+=ret; if(verbose){ System.err.println("Corrected error."); } }else{ if(verbose){ System.err.println("Not an error: "+aCount+", "+bCount+ "; "+isError(aCount, bCount)+", "+isSimilar(aCount, a-errorExtension, a-1, counts)+", "+isError(aCount, a+2, a+kbig, counts)); } } } // if(detected==0 && counts.get(0)>2 && counts.get(counts.size-1)>2){ // assert(!verbose); // verbose=true; // System.err.println("\n"+counts); // errorCorrectPincer(bases, quals, leftBuffer, rightBuffer, kmers, counts, bb, detectedArray); // assert(false); // } if(detectedArray!=null){ detectedArray[0]+=detected; detectedArray[2]+=corrected; } return corrected; } private int correctSingleBasePincer(final int a, final int d, final byte[] bases, final byte[] quals, final int[] leftBuffer, final int[] rightBuffer, final IntList counts, final ByteBuilder bb, final int errorExtension, final Kmer kmer0){ final byte leftReplacement, rightReplacement; final int loc=a+kbig; { bb.clear(); Kmer kmer=getKmer(bases, a, kmer0); if(kmer==null){return 0;} int extension=extendToRight2_inner(bb, null, rightBuffer, errorExtension, true, kmer); if(extension<errorExtension){return 0;} for(int i=1; i<extension; i++){ if(bb.get(i)!=bases[loc+i]){return 0;} } leftReplacement=bb.get(0); } { bb.clear(); Kmer kmer=getKmer(bases, d, kmer0); if(kmer==null){return 0;} kmer.rcomp(); int extension=extendToRight2_inner(bb, null, rightBuffer, errorExtension, true, kmer); if(extension<errorExtension){return 0;} bb.reverseComplementInPlace(); for(int i=0; i<extension-1; i++){ if(bb.get(i)!=bases[loc+i+1-extension]){return 0;} } rightReplacement=bb.get(extension-1); } if(leftReplacement!=rightReplacement){return 0;} if(bases[loc]==leftReplacement){return 0;} if(!isSimilar(bases, a, leftReplacement, counts, kmer0)){return 0;} bases[loc]=leftReplacement; assert(d==a+kbig+1); tables.regenerateCounts(bases, counts, a, kmer0); return 1; } private int correctSingleBaseRight(final int a, final byte[] bases, final byte[] quals, final int[] leftBuffer, final int[] rightBuffer, final IntList counts, final ByteBuilder bb, final int errorExtension0, final Kmer kmer0){ final byte leftReplacement; final int loc=a+kbig; final int errorExtension=Tools.min(errorExtension0, bases.length-loc); { bb.clear(); Kmer kmer=getKmer(bases, a, kmer0); if(kmer==null){return 0;} int extension=extendToRight2_inner(bb, null, rightBuffer, errorExtension, true, kmer); if(extension<errorExtension){return 0;} for(int i=1; i<extension; i++){ if(bb.get(i)!=bases[loc+i]){ return 0; } } leftReplacement=bb.get(0); } if(bases[loc]==leftReplacement){return 0;} if(!isSimilar(bases, a, leftReplacement, counts, kmer0)){return 0;} bases[loc]=leftReplacement; tables.regenerateCounts(bases, counts, a, kmer0); return 1; } private final boolean isSimilar(byte[] bases, int a, byte newBase, IntList counts, final Kmer kmer0){ Kmer kmer=getKmer(bases, a, kmer0); if(kmer==null){ assert(false); //Should never happen return false; } kmer.addRight(newBase); int count=getCount(kmer); int aCount=counts.get(a); boolean similar=isSimilar(aCount, count); return similar; } /*--------------------------------------------------------------*/ /*---------------- Inherited Abstract Methods ----------------*/ /*--------------------------------------------------------------*/ final void makeKhist(){ tables.makeKhist(outHist, histColumns, histMax, histHeader, histZeros, true, smoothHist, 1); } final void dumpKmersAsText(){ tables.dumpKmersAsText(outKmers, minToDump, true); } /*--------------------------------------------------------------*/ /*---------------- Fields ----------------*/ /*--------------------------------------------------------------*/ final KmerTableSetU tables(){return tables;} public final KmerTableSetU tables; /** Normal kmer length */ private final int ksmall; }
package org.docksidestage.sqlite.dbflute.cbean.bs; import org.dbflute.cbean.AbstractConditionBean; import org.dbflute.cbean.ConditionBean; import org.dbflute.cbean.ConditionQuery; import org.dbflute.cbean.chelper.*; import org.dbflute.cbean.coption.*; import org.dbflute.cbean.dream.*; import org.dbflute.cbean.sqlclause.SqlClause; import org.dbflute.cbean.sqlclause.SqlClauseCreator; import org.dbflute.cbean.scoping.*; import org.dbflute.dbmeta.DBMetaProvider; import org.dbflute.twowaysql.factory.SqlAnalyzerFactory; import org.dbflute.twowaysql.style.BoundDateDisplayTimeZoneProvider; import org.docksidestage.sqlite.dbflute.allcommon.MaDBFluteConfig; import org.docksidestage.sqlite.dbflute.allcommon.MaDBMetaInstanceHandler; import org.docksidestage.sqlite.dbflute.allcommon.MaImplementedInvokerAssistant; import org.docksidestage.sqlite.dbflute.allcommon.MaImplementedSqlClauseCreator; import org.docksidestage.sqlite.dbflute.cbean.*; import org.docksidestage.sqlite.dbflute.cbean.cq.*; import org.docksidestage.sqlite.dbflute.cbean.nss.*; /** * The base condition-bean of MEMBER_WITHDRAWAL. * @author DBFlute(AutoGenerator) */ public class BsMemberWithdrawalCB extends AbstractConditionBean { // =================================================================================== // Attribute // ========= protected MemberWithdrawalCQ _conditionQuery; // =================================================================================== // Constructor // =========== public BsMemberWithdrawalCB() { if (MaDBFluteConfig.getInstance().isPagingCountLater()) { enablePagingCountLater(); } if (MaDBFluteConfig.getInstance().isPagingCountLeastJoin()) { enablePagingCountLeastJoin(); } if (MaDBFluteConfig.getInstance().isNonSpecifiedColumnAccessAllowed()) { enableNonSpecifiedColumnAccess(); } if (MaDBFluteConfig.getInstance().isSpecifyColumnRequired()) { enableSpecifyColumnRequired(); } xsetSpecifyColumnRequiredExceptDeterminer(MaDBFluteConfig.getInstance().getSpecifyColumnRequiredExceptDeterminer()); if (MaDBFluteConfig.getInstance().isSpecifyColumnRequiredWarningOnly()) { xenableSpecifyColumnRequiredWarningOnly(); } if (MaDBFluteConfig.getInstance().isQueryUpdateCountPreCheck()) { enableQueryUpdateCountPreCheck(); } } // =================================================================================== // SqlClause // ========= @Override protected SqlClause createSqlClause() { SqlClauseCreator creator = MaDBFluteConfig.getInstance().getSqlClauseCreator(); if (creator != null) { return creator.createSqlClause(this); } return new MaImplementedSqlClauseCreator().createSqlClause(this); // as default } // =================================================================================== // DB Meta // ======= @Override protected DBMetaProvider getDBMetaProvider() { return MaDBMetaInstanceHandler.getProvider(); // as default } public String asTableDbName() { return "MEMBER_WITHDRAWAL"; } // =================================================================================== // PrimaryKey Handling // =================== /** * Accept the query condition of primary key as equal. * @param memberId : PK, NotNull, INTEGER(2000000000, 10), FK to MEMBER. (NotNull) * @return this. (NotNull) */ public MemberWithdrawalCB acceptPK(Integer memberId) { assertObjectNotNull("memberId", memberId); BsMemberWithdrawalCB cb = this; cb.query().setMemberId_Equal(memberId); return (MemberWithdrawalCB)this; } public ConditionBean addOrderBy_PK_Asc() { query().addOrderBy_MemberId_Asc(); return this; } public ConditionBean addOrderBy_PK_Desc() { query().addOrderBy_MemberId_Desc(); return this; } // =================================================================================== // Query // ===== /** * Prepare for various queries. <br> * Examples of main functions are following: * <pre> * <span style="color: #3F7E5E">// Basic Queries</span> * cb.query().setMemberId_Equal(value); <span style="color: #3F7E5E">// =</span> * cb.query().setMemberId_NotEqual(value); <span style="color: #3F7E5E">// !=</span> * cb.query().setMemberId_GreaterThan(value); <span style="color: #3F7E5E">// &gt;</span> * cb.query().setMemberId_LessThan(value); <span style="color: #3F7E5E">// &lt;</span> * cb.query().setMemberId_GreaterEqual(value); <span style="color: #3F7E5E">// &gt;=</span> * cb.query().setMemberId_LessEqual(value); <span style="color: #3F7E5E">// &lt;=</span> * cb.query().setMemberName_InScope(valueList); <span style="color: #3F7E5E">// in ('a', 'b')</span> * cb.query().setMemberName_NotInScope(valueList); <span style="color: #3F7E5E">// not in ('a', 'b')</span> * <span style="color: #3F7E5E">// LikeSearch with various options: (versatile)</span> * <span style="color: #3F7E5E">// {like ... [options]}</span> * cb.query().setMemberName_LikeSearch(value, option); * cb.query().setMemberName_NotLikeSearch(value, option); <span style="color: #3F7E5E">// not like ...</span> * <span style="color: #3F7E5E">// FromTo with various options: (versatile)</span> * <span style="color: #3F7E5E">// {(default) fromDatetime &lt;= BIRTHDATE &lt;= toDatetime}</span> * cb.query().setBirthdate_FromTo(fromDatetime, toDatetime, option); * <span style="color: #3F7E5E">// DateFromTo: (Date means yyyy/MM/dd)</span> * <span style="color: #3F7E5E">// {fromDate &lt;= BIRTHDATE &lt; toDate + 1 day}</span> * cb.query().setBirthdate_IsNull(); <span style="color: #3F7E5E">// is null</span> * cb.query().setBirthdate_IsNotNull(); <span style="color: #3F7E5E">// is not null</span> * * <span style="color: #3F7E5E">// ExistsReferrer: (correlated sub-query)</span> * <span style="color: #3F7E5E">// {where exists (select PURCHASE_ID from PURCHASE where ...)}</span> * cb.query().existsPurchase(purchaseCB <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * purchaseCB.query().set... <span style="color: #3F7E5E">// referrer sub-query condition</span> * }); * cb.query().notExistsPurchase... * * <span style="color: #3F7E5E">// (Query)DerivedReferrer: (correlated sub-query)</span> * cb.query().derivedPurchaseList().max(purchaseCB <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * purchaseCB.specify().columnPurchasePrice(); <span style="color: #3F7E5E">// derived column for function</span> * purchaseCB.query().set... <span style="color: #3F7E5E">// referrer sub-query condition</span> * }).greaterEqual(value); * * <span style="color: #3F7E5E">// ScalarCondition: (self-table sub-query)</span> * cb.query().scalar_Equal().max(scalarCB <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * scalarCB.specify().columnBirthdate(); <span style="color: #3F7E5E">// derived column for function</span> * scalarCB.query().set... <span style="color: #3F7E5E">// scalar sub-query condition</span> * }); * * <span style="color: #3F7E5E">// OrderBy</span> * cb.query().addOrderBy_MemberName_Asc(); * cb.query().addOrderBy_MemberName_Desc().withManualOrder(option); * cb.query().addOrderBy_MemberName_Desc().withNullsFirst(); * cb.query().addOrderBy_MemberName_Desc().withNullsLast(); * cb.query().addSpecifiedDerivedOrderBy_Desc(aliasName); * * <span style="color: #3F7E5E">// Query(Relation)</span> * cb.query().queryMemberStatus()...; * cb.query().queryMemberAddressAsValid(targetDate)...; * </pre> * @return The instance of condition-query for base-point table to set up query. (NotNull) */ public MemberWithdrawalCQ query() { assertQueryPurpose(); // assert only when user-public query return doGetConditionQuery(); } public MemberWithdrawalCQ xdfgetConditionQuery() { // public for parameter comment and internal return doGetConditionQuery(); } protected MemberWithdrawalCQ doGetConditionQuery() { if (_conditionQuery == null) { _conditionQuery = createLocalCQ(); } return _conditionQuery; } protected MemberWithdrawalCQ createLocalCQ() { return xcreateCQ(null, getSqlClause(), getSqlClause().getBasePointAliasName(), 0); } protected MemberWithdrawalCQ xcreateCQ(ConditionQuery childQuery, SqlClause sqlClause, String aliasName, int nestLevel) { MemberWithdrawalCQ cq = xnewCQ(childQuery, sqlClause, aliasName, nestLevel); cq.xsetBaseCB(this); return cq; } protected MemberWithdrawalCQ xnewCQ(ConditionQuery childQuery, SqlClause sqlClause, String aliasName, int nestLevel) { return new MemberWithdrawalCQ(childQuery, sqlClause, aliasName, nestLevel); } /** * {@inheritDoc} */ public ConditionQuery localCQ() { return doGetConditionQuery(); } // =================================================================================== // Union // ===== /** * Set up 'union' for base-point table. <br> * You don't need to call SetupSelect in union-query, * because it inherits calls before. (Don't call SetupSelect after here) * <pre> * cb.query().<span style="color: #CC4747">union</span>(<span style="color: #553000">unionCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">unionCB</span>.query().set... * }); * </pre> * @param unionCBLambda The callback for query of 'union'. (NotNull) */ public void union(UnionQuery<MemberWithdrawalCB> unionCBLambda) { final MemberWithdrawalCB cb = new MemberWithdrawalCB(); cb.xsetupForUnion(this); xsyncUQ(cb); try { lock(); unionCBLambda.query(cb); } finally { unlock(); } xsaveUCB(cb); final MemberWithdrawalCQ cq = cb.query(); query().xsetUnionQuery(cq); } /** * Set up 'union all' for base-point table. <br> * You don't need to call SetupSelect in union-query, * because it inherits calls before. (Don't call SetupSelect after here) * <pre> * cb.query().<span style="color: #CC4747">unionAll</span>(<span style="color: #553000">unionCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">unionCB</span>.query().set... * }); * </pre> * @param unionCBLambda The callback for query of 'union all'. (NotNull) */ public void unionAll(UnionQuery<MemberWithdrawalCB> unionCBLambda) { final MemberWithdrawalCB cb = new MemberWithdrawalCB(); cb.xsetupForUnion(this); xsyncUQ(cb); try { lock(); unionCBLambda.query(cb); } finally { unlock(); } xsaveUCB(cb); final MemberWithdrawalCQ cq = cb.query(); query().xsetUnionAllQuery(cq); } // =================================================================================== // SetupSelect // =========== protected MemberNss _nssMember; public MemberNss xdfgetNssMember() { if (_nssMember == null) { _nssMember = new MemberNss(null); } return _nssMember; } /** * Set up relation columns to select clause. <br> * MEMBER by my MEMBER_ID, named 'member'. * <pre> * <span style="color: #0000C0">memberWithdrawalBhv</span>.selectEntity(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.<span style="color: #CC4747">setupSelect_Member()</span>; <span style="color: #3F7E5E">// ...().with[nested-relation]()</span> * <span style="color: #553000">cb</span>.query().set... * }).alwaysPresent(<span style="color: #553000">memberWithdrawal</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * ... = <span style="color: #553000">memberWithdrawal</span>.<span style="color: #CC4747">getMember()</span>; <span style="color: #3F7E5E">// you can get by using SetupSelect</span> * }); * </pre> * @return The set-upper of nested relation. {setupSelect...().with[nested-relation]} (NotNull) */ public MemberNss setupSelect_Member() { assertSetupSelectPurpose("member"); doSetupSelect(() -> query().queryMember()); if (_nssMember == null || !_nssMember.hasConditionQuery()) { _nssMember = new MemberNss(query().queryMember()); } return _nssMember; } /** * Set up relation columns to select clause. <br> * WITHDRAWAL_REASON by my WITHDRAWAL_REASON_CODE, named 'withdrawalReason'. * <pre> * <span style="color: #0000C0">memberWithdrawalBhv</span>.selectEntity(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.<span style="color: #CC4747">setupSelect_WithdrawalReason()</span>; <span style="color: #3F7E5E">// ...().with[nested-relation]()</span> * <span style="color: #553000">cb</span>.query().set... * }).alwaysPresent(<span style="color: #553000">memberWithdrawal</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * ... = <span style="color: #553000">memberWithdrawal</span>.<span style="color: #CC4747">getWithdrawalReason()</span>; <span style="color: #3F7E5E">// you can get by using SetupSelect</span> * }); * </pre> */ public void setupSelect_WithdrawalReason() { assertSetupSelectPurpose("withdrawalReason"); if (hasSpecifiedLocalColumn()) { specify().columnWithdrawalReasonCode(); } doSetupSelect(() -> query().queryWithdrawalReason()); } // [DBFlute-0.7.4] // =================================================================================== // Specify // ======= protected HpSpecification _specification; /** * Prepare for SpecifyColumn, (Specify)DerivedReferrer. <br> * This method should be called after SetupSelect. * <pre> * <span style="color: #0000C0">memberBhv</span>.selectEntity(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.setupSelect_MemberStatus(); <span style="color: #3F7E5E">// should be called before specify()</span> * <span style="color: #553000">cb</span>.specify().columnMemberName(); * <span style="color: #553000">cb</span>.specify().specifyMemberStatus().columnMemberStatusName(); * <span style="color: #553000">cb</span>.specify().derivedPurchaseList().max(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.specify().columnPurchaseDatetime(); * <span style="color: #553000">purchaseCB</span>.query().set... * }, aliasName); * }).alwaysPresent(<span style="color: #553000">member</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * ... * }); * </pre> * @return The instance of specification. (NotNull) */ public HpSpecification specify() { assertSpecifyPurpose(); if (_specification == null) { _specification = new HpSpecification(this , xcreateSpQyCall(() -> true, () -> xdfgetConditionQuery()) , _purpose, getDBMetaProvider(), xcSDRFnFc()); } return _specification; } public HpColumnSpHandler localSp() { return specify(); } public boolean hasSpecifiedLocalColumn() { return _specification != null && _specification.hasSpecifiedColumn(); } public static class HpSpecification extends HpAbstractSpecification<MemberWithdrawalCQ> { protected MemberCB.HpSpecification _member; protected WithdrawalReasonCB.HpSpecification _withdrawalReason; public HpSpecification(ConditionBean baseCB, HpSpQyCall<MemberWithdrawalCQ> qyCall , HpCBPurpose purpose, DBMetaProvider dbmetaProvider , HpSDRFunctionFactory sdrFuncFactory) { super(baseCB, qyCall, purpose, dbmetaProvider, sdrFuncFactory); } /** * MEMBER_ID: {PK, NotNull, INTEGER(2000000000, 10), FK to MEMBER} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnMemberId() { return doColumn("MEMBER_ID"); } /** * WITHDRAWAL_REASON_CODE: {TEXT(2000000000, 10), FK to WITHDRAWAL_REASON} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnWithdrawalReasonCode() { return doColumn("WITHDRAWAL_REASON_CODE"); } /** * WITHDRAWAL_REASON_INPUT_TEXT: {TEXT(2000000000, 10)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnWithdrawalReasonInputText() { return doColumn("WITHDRAWAL_REASON_INPUT_TEXT"); } /** * WITHDRAWAL_DATETIME: {NotNull, DATETIME(2000000000, 10)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnWithdrawalDatetime() { return doColumn("WITHDRAWAL_DATETIME"); } /** * REGISTER_DATETIME: {NotNull, DATETIME(2000000000, 10)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnRegisterDatetime() { return doColumn("REGISTER_DATETIME"); } /** * REGISTER_PROCESS: {NotNull, TEXT(2000000000, 10)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnRegisterProcess() { return doColumn("REGISTER_PROCESS"); } /** * REGISTER_USER: {NotNull, TEXT(2000000000, 10)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnRegisterUser() { return doColumn("REGISTER_USER"); } /** * UPDATE_DATETIME: {NotNull, DATETIME(2000000000, 10)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnUpdateDatetime() { return doColumn("UPDATE_DATETIME"); } /** * UPDATE_PROCESS: {NotNull, TEXT(2000000000, 10)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnUpdateProcess() { return doColumn("UPDATE_PROCESS"); } /** * UPDATE_USER: {NotNull, TEXT(2000000000, 10)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnUpdateUser() { return doColumn("UPDATE_USER"); } /** * VERSION_NO: {NotNull, INTEGER(2000000000, 10)} * @return The information object of specified column. (NotNull) */ public SpecifiedColumn columnVersionNo() { return doColumn("VERSION_NO"); } public void everyColumn() { doEveryColumn(); } public void exceptRecordMetaColumn() { doExceptRecordMetaColumn(); } @Override protected void doSpecifyRequiredColumn() { columnMemberId(); // PK if (qyCall().qy().hasConditionQueryWithdrawalReason() || qyCall().qy().xgetReferrerQuery() instanceof WithdrawalReasonCQ) { columnWithdrawalReasonCode(); // FK or one-to-one referrer } } @Override protected String getTableDbName() { return "MEMBER_WITHDRAWAL"; } /** * Prepare to specify functions about relation table. <br> * MEMBER by my MEMBER_ID, named 'member'. * @return The instance for specification for relation table to specify. (NotNull) */ public MemberCB.HpSpecification specifyMember() { assertRelation("member"); if (_member == null) { _member = new MemberCB.HpSpecification(_baseCB , xcreateSpQyCall(() -> _qyCall.has() && _qyCall.qy().hasConditionQueryMember() , () -> _qyCall.qy().queryMember()) , _purpose, _dbmetaProvider, xgetSDRFnFc()); if (xhasSyncQyCall()) { // inherits it _member.xsetSyncQyCall(xcreateSpQyCall( () -> xsyncQyCall().has() && xsyncQyCall().qy().hasConditionQueryMember() , () -> xsyncQyCall().qy().queryMember())); } } return _member; } /** * Prepare to specify functions about relation table. <br> * WITHDRAWAL_REASON by my WITHDRAWAL_REASON_CODE, named 'withdrawalReason'. * @return The instance for specification for relation table to specify. (NotNull) */ public WithdrawalReasonCB.HpSpecification specifyWithdrawalReason() { assertRelation("withdrawalReason"); if (_withdrawalReason == null) { _withdrawalReason = new WithdrawalReasonCB.HpSpecification(_baseCB , xcreateSpQyCall(() -> _qyCall.has() && _qyCall.qy().hasConditionQueryWithdrawalReason() , () -> _qyCall.qy().queryWithdrawalReason()) , _purpose, _dbmetaProvider, xgetSDRFnFc()); if (xhasSyncQyCall()) { // inherits it _withdrawalReason.xsetSyncQyCall(xcreateSpQyCall( () -> xsyncQyCall().has() && xsyncQyCall().qy().hasConditionQueryWithdrawalReason() , () -> xsyncQyCall().qy().queryWithdrawalReason())); } } return _withdrawalReason; } /** * Prepare for (Specify)MyselfDerived (SubQuery). * @return The object to set up a function for myself table. (NotNull) */ public HpSDRFunction<MemberWithdrawalCB, MemberWithdrawalCQ> myselfDerived() { assertDerived("myselfDerived"); if (xhasSyncQyCall()) { xsyncQyCall().qy(); } // for sync (for example, this in ColumnQuery) return cHSDRF(_baseCB, _qyCall.qy(), (String fn, SubQuery<MemberWithdrawalCB> sq, MemberWithdrawalCQ cq, String al, DerivedReferrerOption op) -> cq.xsmyselfDerive(fn, sq, al, op), _dbmetaProvider); } } // =================================================================================== // Dream Cruise // ============ /** * Welcome to the Dream Cruise for condition-bean deep world. <br> * This is very specialty so you can get the frontier spirit. Bon voyage! * @return The condition-bean for dream cruise, which is linked to main condition-bean. */ public MemberWithdrawalCB dreamCruiseCB() { MemberWithdrawalCB cb = new MemberWithdrawalCB(); cb.xsetupForDreamCruise((MemberWithdrawalCB) this); return cb; } protected ConditionBean xdoCreateDreamCruiseCB() { return dreamCruiseCB(); } // [DBFlute-0.9.5.3] // =================================================================================== // Column Query // ============ /** * Set up column-query. {column1 = column2} * <pre> * <span style="color: #3F7E5E">// where FOO &lt; BAR</span> * cb.<span style="color: #CC4747">columnQuery</span>(<span style="color: #553000">colCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">colCB</span>.specify().<span style="color: #CC4747">columnFoo()</span>; <span style="color: #3F7E5E">// left column</span> * }).lessThan(<span style="color: #553000">colCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">colCB</span>.specify().<span style="color: #CC4747">columnBar()</span>; <span style="color: #3F7E5E">// right column</span> * }); <span style="color: #3F7E5E">// you can calculate for right column like '}).plus(3);'</span> * </pre> * @param colCBLambda The callback for specify-query of left column. (NotNull) * @return The object for setting up operand and right column. (NotNull) */ public HpColQyOperand<MemberWithdrawalCB> columnQuery(final SpecifyQuery<MemberWithdrawalCB> colCBLambda) { return xcreateColQyOperand((rightSp, operand) -> { return xcolqy(xcreateColumnQueryCB(), xcreateColumnQueryCB(), colCBLambda, rightSp, operand); }); } protected MemberWithdrawalCB xcreateColumnQueryCB() { MemberWithdrawalCB cb = new MemberWithdrawalCB(); cb.xsetupForColumnQuery((MemberWithdrawalCB)this); return cb; } // [DBFlute-0.9.6.3] // =================================================================================== // OrScope Query // ============= /** * Set up the query for or-scope. <br> * (Same-column-and-same-condition-key conditions are allowed in or-scope) * <pre> * <span style="color: #3F7E5E">// where (FOO = '...' or BAR = '...')</span> * cb.<span style="color: #CC4747">orScopeQuery</span>(<span style="color: #553000">orCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">orCB</span>.query().setFoo... * <span style="color: #553000">orCB</span>.query().setBar... * }); * </pre> * @param orCBLambda The callback for query of or-condition. (NotNull) */ public void orScopeQuery(OrQuery<MemberWithdrawalCB> orCBLambda) { xorSQ((MemberWithdrawalCB)this, orCBLambda); } /** * Set up the and-part of or-scope. <br> * (However nested or-scope query and as-or-split of like-search in and-part are unsupported) * <pre> * <span style="color: #3F7E5E">// where (FOO = '...' or (BAR = '...' and QUX = '...'))</span> * cb.<span style="color: #994747">orScopeQuery</span>(<span style="color: #553000">orCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">orCB</span>.query().setFoo... * <span style="color: #553000">orCB</span>.<span style="color: #CC4747">orScopeQueryAndPart</span>(<span style="color: #553000">andCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">andCB</span>.query().setBar... * <span style="color: #553000">andCB</span>.query().setQux... * }); * }); * </pre> * @param andCBLambda The callback for query of and-condition. (NotNull) */ public void orScopeQueryAndPart(AndQuery<MemberWithdrawalCB> andCBLambda) { xorSQAP((MemberWithdrawalCB)this, andCBLambda); } // =================================================================================== // DisplaySQL // ========== @Override protected SqlAnalyzerFactory getSqlAnalyzerFactory() { return new MaImplementedInvokerAssistant().assistSqlAnalyzerFactory(); } @Override protected String getConfiguredLogDatePattern() { return MaDBFluteConfig.getInstance().getLogDatePattern(); } @Override protected String getConfiguredLogTimestampPattern() { return MaDBFluteConfig.getInstance().getLogTimestampPattern(); } @Override protected String getConfiguredLogTimePattern() { return MaDBFluteConfig.getInstance().getLogTimePattern(); } @Override protected BoundDateDisplayTimeZoneProvider getConfiguredLogTimeZoneProvider() { return MaDBFluteConfig.getInstance().getLogTimeZoneProvider(); } // =================================================================================== // Meta Handling // ============= public boolean hasUnionQueryOrUnionAllQuery() { return query().hasUnionQueryOrUnionAllQuery(); } // =================================================================================== // Purpose Type // ============ @Override protected void xprepareSyncQyCall(ConditionBean mainCB) { final MemberWithdrawalCB cb; if (mainCB != null) { cb = (MemberWithdrawalCB)mainCB; } else { cb = new MemberWithdrawalCB(); } specify().xsetSyncQyCall(xcreateSpQyCall(() -> true, () -> cb.query())); } // =================================================================================== // Internal // ======== // very internal (for suppressing warn about 'Not Use Import') protected String xgetConditionBeanClassNameInternally() { return MemberWithdrawalCB.class.getName(); } protected String xgetConditionQueryClassNameInternally() { return MemberWithdrawalCQ.class.getName(); } protected String xgetSubQueryClassNameInternally() { return SubQuery.class.getName(); } protected String xgetConditionOptionClassNameInternally() { return ConditionOption.class.getName(); } }
/* * Copyright (c) 2016, WSO2 Inc. (http://wso2.com) All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.andes.kernel.dtx; import org.apache.log4j.Logger; import org.wso2.andes.kernel.AndesAckData; import org.wso2.andes.kernel.AndesChannel; import org.wso2.andes.kernel.AndesException; import org.wso2.andes.kernel.AndesMessage; import org.wso2.andes.kernel.disruptor.DisruptorEventCallback; import org.wso2.andes.kernel.disruptor.inbound.InboundEventContainer; import org.wso2.andes.kernel.disruptor.inbound.InboundEventManager; import org.wso2.andes.kernel.slot.SlotMessageCounter; import org.wso2.andes.tools.utils.MessageTracer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ScheduledFuture; import javax.transaction.xa.Xid; /** * Class which holds information relates to a specific {@link Xid} within the broker */ public class DtxBranch { /** * Class logger */ private static final Logger LOGGER = Logger.getLogger(DtxBranch.class); /** * Internal XID has this value when the branch is not in prepared state */ public static final int NULL_XID = -1; /** * Session Id of a session that is recovered from storage */ public static final UUID RECOVERY_SESSION_ID = UUID.randomUUID(); /** * XID used to identify the dtx branch by external parties */ private final Xid xid; /** * Registry used to keep dtx branch related information */ private final DtxRegistry dtxRegistry; /** * List of associated sessions to this branch */ private Map<UUID, State> associatedSessions = new HashMap<>(); /** * Event manager used to publish commit event */ private InboundEventManager eventManager; /** * Keep callback to be called after committing */ private DisruptorEventCallback callback; /** * Branch's transaction timeout value */ private long timeout; /** * Future of the scheduled timeout task. Null if no scheduled timeout tasks */ private ScheduledFuture<?> timeoutFuture; /** * Expiration time calculated from the timeout value. */ private long _expiration; /** * Keep the list of messages that need to be published when the transaction commits */ private ArrayList<AndesMessage> enqueueList = new ArrayList<>(); /** * Keep the list of messages that need to be acked when the transaction commits */ private List<AndesAckData> dequeueList = new ArrayList<>(); /** * Messages that were dequeued within a the transaction branch which is in prepared state. */ private List<AndesPreparedMessageMetadata> preparedDequeueMessages; /** * Current branch state */ private State state = State.ACTIVE; /** * Used to keep the internal xid value used in message store */ private long internalXid = NULL_XID; /** * Session id of the session which created the branch */ private UUID createdSessionId; /** * Reference to the specific command that needs to be executed when updateState method is invoked by the * {@link org.wso2.andes.kernel.disruptor.inbound.StateEventHandler} */ private Runnable updateSlotCommand; /** * Default constructor * @param sessionId session ID of originating session * @param xid XID used to identify the dtx branch by external parties * @param dtxRegistry registry used to keep dtx branch related information * @param eventManager event manager used to publish commit event */ DtxBranch(UUID sessionId, Xid xid, DtxRegistry dtxRegistry, InboundEventManager eventManager) { this.xid = xid; this.dtxRegistry = dtxRegistry; this.eventManager = eventManager; this.createdSessionId = sessionId; } /** * Getter for enqueueList */ public ArrayList<AndesMessage> getEnqueueList() { return enqueueList; } /** * Set the messages that were acknowledged but not commited withing the transaction that needs to be restored when * rollback is called. * @param messagesToRestore {@link List} of {@link AndesPreparedMessageMetadata} */ public void setMessagesToRestore(List<AndesPreparedMessageMetadata> messagesToRestore) { dequeueList.clear(); this.preparedDequeueMessages = messagesToRestore; } /** * Set the messages to be stored in Database * @param messagesToStore {@link Collection} of {@link AndesMessage} */ public void setMessagesToStore(Collection<AndesMessage> messagesToStore) { this.enqueueList.clear(); this.enqueueList.addAll(messagesToStore); } void clearEnqueueList() { enqueueList.clear(); } /** * Getter for dequeueList */ public List<AndesAckData> getDequeueList() { return dequeueList; } /** * Getter for XID * * @return XID of the branch */ public Xid getXid() { return xid; } /** * Associate a session to current branch. * * @param sessionID session identifier of the session * @return True if a new entry, False otherwise */ boolean associateSession(UUID sessionID) { return associatedSessions.put(sessionID, State.ACTIVE) != null; } /** * Disassociate the given session from the branch * * @param sessionID session identifier of the session * @return True if there is a matching entry, False otherwise */ boolean disassociateSession(UUID sessionID) { return associatedSessions.remove(sessionID) != null; } /** * Resume a session if it is suspended * * @param sessionId session identifier of the session * @return True if there is a matching suspended entry */ boolean resumeSession(UUID sessionId) { if (associatedSessions.containsKey(sessionId) && associatedSessions.get(sessionId) == State.SUSPENDED) { associatedSessions.put(sessionId, State.ACTIVE); return true; } return false; } /** * Check if a session is associated with the branch * * @param sessionId session identifier of the session * @return True is the session is associated with the branch */ boolean isAssociated(UUID sessionId) { return associatedSessions.containsKey(sessionId); } /** * Id of the session which created the branch * @return session id */ UUID getCreatedSessionId() { return createdSessionId; } /** * Suspend a associated active session * * @param sessionId session identifier of the session * @return True if a matching active sessions if found, False otherwise */ boolean suspendSession(UUID sessionId) { State state = associatedSessions.get(sessionId); if (null != state && state == State.ACTIVE) { associatedSessions.put(sessionId, State.SUSPENDED); return true; } else { return false; } } /** * Enqueue a single message to the branch * @param andesMessage enqueue record */ public synchronized void enqueueMessage(AndesMessage andesMessage) { enqueueList.add(andesMessage); } /** * Check if the branch has active associated sessions * * @return True if there are active associated sessions */ boolean hasAssociatedActiveSessions() { if (hasAssociatedSessions()) { for (State state : associatedSessions.values()) { if (state != State.SUSPENDED) { return true; } } } return false; } /** * Check if there are any associated sessions * * @return True if there are any associated sessions, false otherwise */ boolean hasAssociatedSessions() { return !associatedSessions.isEmpty(); } /** * Clear all association from branch */ void clearAssociations() { associatedSessions.clear(); } /** * Check if the branch is expired * @return True if the branch is expired, False otherwise */ public boolean expired() { return (timeout != 0 && _expiration < System.currentTimeMillis()) || state == State.TIMED_OUT; } /** * Get current state of the branch * @return state of the branch */ public State getState() { return state; } /** * Persist enqueue and dequeue records * @throws AndesException if an internal error occured */ public void persistRecords() throws AndesException { LOGGER.debug("Performing prepare for DtxBranch : " + xid); internalXid = dtxRegistry.storeRecords(this); } /** * Retrieve the messages that need to be restored on a rollback event * * @return List of {@link AndesPreparedMessageMetadata} */ public List<AndesPreparedMessageMetadata> getMessagesToRestore() { return Collections.unmodifiableList(preparedDequeueMessages); } /** * Set the state of the branch * @param state new state to be set */ public void setState(State state) { this.state = state; } /** * Add a list of dequeue records to the branch * * @param ackList list of dequeue records */ void dequeueMessages(List<AndesAckData> ackList) { dequeueList.addAll(ackList); } /*** * Cancel timeout task and remove corresponding enqueue and dequeue records from the dtx registry. * * @param callback {@link DisruptorEventCallback} * @throws AndesException if an internal error occurred */ public synchronized void rollback(DisruptorEventCallback callback) throws AndesException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Performing rollback for DtxBranch {}" + xid); } this.callback = callback; cancelTimeoutTaskIfExists(); if (internalXid != NULL_XID) { updateSlotCommand = new DtxRollbackCommand(); eventManager.requestDtxEvent(this, null, InboundEventContainer.Type.DTX_ROLLBACK_EVENT); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Cannot rollback since could not find a internal XID " + "{}" + xid); } callback.execute(); } } /** * Cancel the timeout tasks if one is already set for the current branch */ private void cancelTimeoutTaskIfExists() { if (timeoutFuture != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Attempting to cancel previous timeout task future for DtxBranch " + xid); } boolean succeeded = timeoutFuture.cancel(false); timeoutFuture = null; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Cancelling previous timeout task {} for DtxBranch " + (succeeded ? "succeeded" : "failed") + xid); } } } /** * Commit the changes (enqueue and dequeue actions) to andes core * * @param callback callback that called after completing the commit task * @param channel corresponding channel object * @throws AndesException if an internal error occured */ public void commit(DisruptorEventCallback callback, AndesChannel channel, boolean isOnePhaseCommit) throws AndesException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Performing commit for DtxBranch " + xid); } cancelTimeoutTaskIfExists(); this.callback = callback; updateSlotCommand = new DtxCommitCommand(); if (isOnePhaseCommit) { eventManager.requestDtxEvent(this, channel, InboundEventContainer.Type.DTX_ONE_PHASE_COMMIT_EVENT); } else { eventManager.requestDtxEvent(this, channel, InboundEventContainer.Type.DTX_COMMIT_EVENT); } } /** * Store enqueue and dequeue records in the DtxStore * @param callback callback that is called after completing the commit task */ public void prepare(DisruptorEventCallback callback) { updateSlotCommand = new DtxPrepareCommand(callback); traceMessageList(enqueueList, MessageTracer.PUBLISHING_DTX_PREPARE_ENQUEUE_RECORDS_TO_DISRUPTOR); traceAckData(dequeueList, MessageTracer.PUBLISHING_DTX_PREPARE_DEQUEUE_RECORDS_TO_DISRUPTOR); eventManager.requestDtxEvent(this, null, InboundEventContainer.Type.DTX_PREPARE_EVENT); } /** * Trace acknowledgement * @param dequeueList list of {@link AndesAckData} * @param description description of the message trace incident */ private void traceAckData(List<AndesAckData> dequeueList, String description) { if (MessageTracer.isEnabled()) { for (AndesAckData ackData : dequeueList) { MessageTracer.trace(ackData, xid, state, description); } } } /** * Write the committed messages to the database * * @throws AndesException throws AndesException on database error */ public void writeToDbOnCommit() throws AndesException { dtxRegistry.getStore().updateOnCommit(internalXid, enqueueList); traceMessageList(enqueueList, MessageTracer.DTX_MESSAGE_WRITTEN_TO_DB); } /** * Write committed messages to the database. * * @throws AndesException throws AndesException on database error */ public void writeToDbOnOnePhaseCommit() throws AndesException { dtxRegistry.getStore().updateOnOnePhaseCommit(enqueueList, dtxRegistry.acknowledgeAndRetrieveDequeueRecords (this)); } /** * Update the state of the transaction and respond to the client on dtx.commt and dtx.rollback events * * @param event {@link InboundEventContainer} * @throws AndesException */ public void updateState(InboundEventContainer event) throws AndesException { if (event.hasErrorOccurred()) { callback.onException(new Exception(event.getError())); } else { updateSlotCommand.run(); } } /** * * @param messageList */ private void updateSlotAndClearLists(List<AndesMessage> messageList) { try { SlotMessageCounter.getInstance().recordMetadataCountInSlot(messageList); traceMessageList(messageList, MessageTracer.DTX_RECORD_METADATA_COUNT_IN_SLOT); enqueueList.clear(); dequeueList.clear(); callback.execute(); internalXid = NULL_XID; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Messages state updated. Internal Xid " + internalXid); } } catch (Exception exception) { callback.onException(exception); } } /** * Update data store when rollback is called. Restore the acknowledged but not yet committed messages and * information regarding the transaction * * @throws AndesException throws {@link AndesException} when there is an internal data store error. */ public void writeToDbOnRollback() throws AndesException { dtxRegistry.getStore().updateOnRollback(internalXid, preparedDequeueMessages); if (MessageTracer.isEnabled()) { for (AndesPreparedMessageMetadata preparedMessageMetadata : preparedDequeueMessages) { MessageTracer.trace(preparedMessageMetadata, xid, state, MessageTracer.DTX_ROLLBACK_DEQUEUED_RECORDS); } } } /** * Trace message list * * @param messageList {@link AndesMessage} list * @param description description of the trace incident */ private void traceMessageList(List<AndesMessage> messageList, String description) { if (MessageTracer.isEnabled()) { for (AndesMessage message: messageList) { MessageTracer.trace(message.getMetadata(), xid, state, description); } } } /** * Set the transaction timeout of the current branch and schedule a timeout task. * * @param timeout transaction timeout value in seconds */ public void setTimeout(long timeout) { cancelTimeoutTaskIfExists(); this.timeout = timeout; _expiration = timeout == 0 ? 0 : System.currentTimeMillis() + (1000 * timeout); if (timeout == 0) { timeoutFuture = null; } else { long delay = 1000 * timeout; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Scheduling timeout and rollback after " + timeout + "s for DtxBranch " + xid); } timeoutFuture = dtxRegistry.scheduleTask(delay, new Runnable() { public void run() { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Timing out DtxBranch " + xid); } setState(State.TIMED_OUT); try { rollback(new DisruptorEventCallback() { @Override public void execute() { // nothing to do be done. This is an internally triggered event } @Override public void onException(Exception exception) { // nothing to be done. This is an internally triggered event } }); } catch (AndesException e) { LOGGER.error("Error while rolling back dtx due to store exception"); } } }); } } /** * Recover branch details from the persistent storage for already prepared transactions * * @param nodeId node id of the server * @return internal xid of the node * @throws AndesException throws {@link AndesException} when data storage exception occur */ boolean recoverFromStore(String nodeId) throws AndesException { internalXid = dtxRegistry.getStore().recoverBranchData(this, nodeId); if (internalXid != NULL_XID) { setState(State.PREPARED); return true; } return false; } /** * States of a {@link DtxBranch} */ public enum State { /** * The branch was suspended in a dtx.end */ SUSPENDED, /** * Branch is registered in DtxRegistry */ ACTIVE, /** * Branch can only be rolled back */ ROLLBACK_ONLY, /** * Branch is in prepared state. Branch can only be committed or rolled back after this */ PREPARED, /** * Branch was unregistered from DtxRegistry */ FORGOTTEN, /** * Branch expired */ TIMED_OUT, /** * Branch heuristically committed */ HEUR_COM, /** * Branch received a prepare call and in the process of persisting */ PRE_PREPARE, /** * Branch heuristically rolled back */ HEUR_RB } /** * Command to update slots for Dtx Commit event */ private class DtxCommitCommand implements Runnable { @Override public void run() { updateSlotAndClearLists(enqueueList); } } /** * Command to update slots for Dtx Rollback event */ private class DtxRollbackCommand implements Runnable { @Override public void run() { List<AndesMessage> dequeuedMessages = new ArrayList<>(); for (AndesPreparedMessageMetadata metadata: preparedDequeueMessages) { dequeuedMessages.add(new AndesMessage(metadata)); } updateSlotAndClearLists(dequeuedMessages); } } /** * Command to update slots for Dtx Prepare event */ private class DtxPrepareCommand implements Runnable { private final DisruptorEventCallback callback; DtxPrepareCommand(DisruptorEventCallback callback) { this.callback = callback; } @Override public void run() { callback.execute(); } } }
/* * 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.ignite.internal.processors.hadoop.jobtracker; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import javax.cache.event.CacheEntryEvent; import javax.cache.event.CacheEntryUpdatedListener; import javax.cache.expiry.Duration; import javax.cache.expiry.ExpiryPolicy; import javax.cache.expiry.ModifiedExpiryPolicy; import javax.cache.processor.EntryProcessor; import javax.cache.processor.MutableEntry; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.events.DiscoveryEvent; import org.apache.ignite.events.Event; import org.apache.ignite.events.EventType; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener; import org.apache.ignite.internal.processors.cache.GridCacheAdapter; import org.apache.ignite.internal.processors.cache.IgniteInternalCache; import org.apache.ignite.internal.processors.hadoop.HadoopClassLoader; import org.apache.ignite.internal.processors.hadoop.HadoopComponent; import org.apache.ignite.internal.processors.hadoop.HadoopContext; import org.apache.ignite.internal.processors.hadoop.HadoopInputSplit; import org.apache.ignite.internal.processors.hadoop.HadoopJob; import org.apache.ignite.internal.processors.hadoop.HadoopJobId; import org.apache.ignite.internal.processors.hadoop.HadoopJobInfo; import org.apache.ignite.internal.processors.hadoop.HadoopJobPhase; import org.apache.ignite.internal.processors.hadoop.HadoopJobStatus; import org.apache.ignite.internal.processors.hadoop.HadoopMapReducePlan; import org.apache.ignite.internal.processors.hadoop.HadoopMapReducePlanner; import org.apache.ignite.internal.processors.hadoop.HadoopTaskCancelledException; import org.apache.ignite.internal.processors.hadoop.HadoopTaskInfo; import org.apache.ignite.internal.processors.hadoop.HadoopUtils; import org.apache.ignite.internal.processors.hadoop.counter.HadoopCounterWriter; import org.apache.ignite.internal.processors.hadoop.counter.HadoopCounters; import org.apache.ignite.internal.processors.hadoop.counter.HadoopCountersImpl; import org.apache.ignite.internal.processors.hadoop.counter.HadoopPerformanceCounter; import org.apache.ignite.internal.processors.hadoop.taskexecutor.HadoopTaskStatus; import org.apache.ignite.internal.processors.hadoop.taskexecutor.external.HadoopProcessDescriptor; import org.apache.ignite.internal.processors.hadoop.v2.HadoopV2Job; import org.apache.ignite.internal.util.GridMutex; import org.apache.ignite.internal.util.GridSpinReadWriteLock; import org.apache.ignite.internal.util.future.GridFinishedFuture; import org.apache.ignite.internal.util.future.GridFutureAdapter; import org.apache.ignite.internal.util.typedef.CI1; import org.apache.ignite.internal.util.typedef.CIX1; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.internal.CU; import org.apache.ignite.internal.util.typedef.internal.SB; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteInClosure; import org.jetbrains.annotations.Nullable; import org.jsr166.ConcurrentHashMap8; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.ignite.internal.processors.hadoop.HadoopJobPhase.PHASE_CANCELLING; import static org.apache.ignite.internal.processors.hadoop.HadoopJobPhase.PHASE_COMPLETE; import static org.apache.ignite.internal.processors.hadoop.HadoopJobPhase.PHASE_MAP; import static org.apache.ignite.internal.processors.hadoop.HadoopJobPhase.PHASE_REDUCE; import static org.apache.ignite.internal.processors.hadoop.HadoopJobPhase.PHASE_SETUP; import static org.apache.ignite.internal.processors.hadoop.HadoopTaskType.ABORT; import static org.apache.ignite.internal.processors.hadoop.HadoopTaskType.COMMIT; import static org.apache.ignite.internal.processors.hadoop.HadoopTaskType.MAP; import static org.apache.ignite.internal.processors.hadoop.HadoopTaskType.REDUCE; import static org.apache.ignite.internal.processors.hadoop.HadoopTaskType.SETUP; import static org.apache.ignite.internal.processors.hadoop.taskexecutor.HadoopTaskState.COMPLETED; import static org.apache.ignite.internal.processors.hadoop.taskexecutor.HadoopTaskState.CRASHED; import static org.apache.ignite.internal.processors.hadoop.taskexecutor.HadoopTaskState.FAILED; import static org.apache.ignite.internal.processors.hadoop.taskexecutor.HadoopTaskState.RUNNING; /** * Hadoop job tracker. */ public class HadoopJobTracker extends HadoopComponent { /** */ private final GridMutex mux = new GridMutex(); /** */ private volatile IgniteInternalCache<HadoopJobId, HadoopJobMetadata> jobMetaPrj; /** Projection with expiry policy for finished job updates. */ private volatile IgniteInternalCache<HadoopJobId, HadoopJobMetadata> finishedJobMetaPrj; /** Map-reduce execution planner. */ @SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized") private HadoopMapReducePlanner mrPlanner; /** All the known jobs. */ private final ConcurrentMap<HadoopJobId, GridFutureAdapter<HadoopJob>> jobs = new ConcurrentHashMap8<>(); /** Locally active jobs. */ private final ConcurrentMap<HadoopJobId, JobLocalState> activeJobs = new ConcurrentHashMap8<>(); /** Locally requested finish futures. */ private final ConcurrentMap<HadoopJobId, GridFutureAdapter<HadoopJobId>> activeFinishFuts = new ConcurrentHashMap8<>(); /** Event processing service. */ private ExecutorService evtProcSvc; /** Component busy lock. */ private GridSpinReadWriteLock busyLock; /** Class to create HadoopJob instances from. */ private Class<? extends HadoopJob> jobCls; /** Closure to check result of async transform of system cache. */ private final IgniteInClosure<IgniteInternalFuture<?>> failsLog = new CI1<IgniteInternalFuture<?>>() { @Override public void apply(IgniteInternalFuture<?> gridFut) { try { gridFut.get(); } catch (IgniteCheckedException e) { U.error(log, "Failed to transform system cache.", e); } } }; /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void start(final HadoopContext ctx) throws IgniteCheckedException { super.start(ctx); busyLock = new GridSpinReadWriteLock(); evtProcSvc = Executors.newFixedThreadPool(1); UUID nodeId = ctx.localNodeId(); assert jobCls == null; HadoopClassLoader ldr = new HadoopClassLoader(null, HadoopClassLoader.nameForJob(nodeId)); try { jobCls = (Class<HadoopV2Job>)ldr.loadClass(HadoopV2Job.class.getName()); } catch (Exception ioe) { throw new IgniteCheckedException("Failed to load job class [class=" + HadoopV2Job.class.getName() + ']', ioe); } } /** * @return Job meta projection. */ @SuppressWarnings("NonPrivateFieldAccessedInSynchronizedContext") private IgniteInternalCache<HadoopJobId, HadoopJobMetadata> jobMetaCache() { IgniteInternalCache<HadoopJobId, HadoopJobMetadata> prj = jobMetaPrj; if (prj == null) { synchronized (mux) { if ((prj = jobMetaPrj) == null) { GridCacheAdapter<HadoopJobId, HadoopJobMetadata> sysCache = ctx.kernalContext().cache() .internalCache(CU.SYS_CACHE_HADOOP_MR); assert sysCache != null; mrPlanner = ctx.planner(); try { ctx.kernalContext().resource().injectGeneric(mrPlanner); } catch (IgniteCheckedException e) { // Must not happen. U.error(log, "Failed to inject resources.", e); throw new IllegalStateException(e); } jobMetaPrj = prj = sysCache; if (ctx.configuration().getFinishedJobInfoTtl() > 0) { ExpiryPolicy finishedJobPlc = new ModifiedExpiryPolicy( new Duration(MILLISECONDS, ctx.configuration().getFinishedJobInfoTtl())); finishedJobMetaPrj = prj.withExpiryPolicy(finishedJobPlc); } else finishedJobMetaPrj = jobMetaPrj; } } } return prj; } /** * @return Projection with expiry policy for finished job updates. */ private IgniteInternalCache<HadoopJobId, HadoopJobMetadata> finishedJobMetaCache() { IgniteInternalCache<HadoopJobId, HadoopJobMetadata> prj = finishedJobMetaPrj; if (prj == null) { jobMetaCache(); prj = finishedJobMetaPrj; assert prj != null; } return prj; } /** {@inheritDoc} */ @SuppressWarnings("deprecation") @Override public void onKernalStart() throws IgniteCheckedException { super.onKernalStart(); jobMetaCache().context().continuousQueries().executeInternalQuery( new CacheEntryUpdatedListener<HadoopJobId, HadoopJobMetadata>() { @Override public void onUpdated(final Iterable<CacheEntryEvent<? extends HadoopJobId, ? extends HadoopJobMetadata>> evts) { if (!busyLock.tryReadLock()) return; try { // Must process query callback in a separate thread to avoid deadlocks. evtProcSvc.submit(new EventHandler() { @Override protected void body() throws IgniteCheckedException { processJobMetadataUpdates(evts); } }); } finally { busyLock.readUnlock(); } } }, null, true, true, false ); ctx.kernalContext().event().addLocalEventListener(new GridLocalEventListener() { @Override public void onEvent(final Event evt) { if (!busyLock.tryReadLock()) return; try { // Must process discovery callback in a separate thread to avoid deadlock. evtProcSvc.submit(new EventHandler() { @Override protected void body() { processNodeLeft((DiscoveryEvent)evt); } }); } finally { busyLock.readUnlock(); } } }, EventType.EVT_NODE_FAILED, EventType.EVT_NODE_LEFT); } /** {@inheritDoc} */ @Override public void onKernalStop(boolean cancel) { super.onKernalStop(cancel); busyLock.writeLock(); evtProcSvc.shutdown(); // Fail all pending futures. for (GridFutureAdapter<HadoopJobId> fut : activeFinishFuts.values()) fut.onDone(new IgniteCheckedException("Failed to execute Hadoop map-reduce job (grid is stopping).")); } /** * Submits execution of Hadoop job to grid. * * @param jobId Job ID. * @param info Job info. * @return Job completion future. */ @SuppressWarnings("unchecked") public IgniteInternalFuture<HadoopJobId> submit(HadoopJobId jobId, HadoopJobInfo info) { if (!busyLock.tryReadLock()) { return new GridFinishedFuture<>(new IgniteCheckedException("Failed to execute map-reduce job " + "(grid is stopping): " + info)); } try { long jobPrepare = U.currentTimeMillis(); if (jobs.containsKey(jobId) || jobMetaCache().containsKey(jobId)) throw new IgniteCheckedException("Failed to submit job. Job with the same ID already exists: " + jobId); HadoopJob job = job(jobId, info); HadoopMapReducePlan mrPlan = mrPlanner.preparePlan(job, ctx.nodes(), null); HadoopJobMetadata meta = new HadoopJobMetadata(ctx.localNodeId(), jobId, info); meta.mapReducePlan(mrPlan); meta.pendingSplits(allSplits(mrPlan)); meta.pendingReducers(allReducers(mrPlan)); GridFutureAdapter<HadoopJobId> completeFut = new GridFutureAdapter<>(); GridFutureAdapter<HadoopJobId> old = activeFinishFuts.put(jobId, completeFut); assert old == null : "Duplicate completion future [jobId=" + jobId + ", old=" + old + ']'; if (log.isDebugEnabled()) log.debug("Submitting job metadata [jobId=" + jobId + ", meta=" + meta + ']'); long jobStart = U.currentTimeMillis(); HadoopPerformanceCounter perfCntr = HadoopPerformanceCounter.getCounter(meta.counters(), ctx.localNodeId()); perfCntr.clientSubmissionEvents(info); perfCntr.onJobPrepare(jobPrepare); perfCntr.onJobStart(jobStart); if (jobMetaCache().getAndPutIfAbsent(jobId, meta) != null) throw new IgniteCheckedException("Failed to submit job. Job with the same ID already exists: " + jobId); return completeFut; } catch (IgniteCheckedException e) { U.error(log, "Failed to submit job: " + jobId, e); return new GridFinishedFuture<>(e); } finally { busyLock.readUnlock(); } } /** * Convert Hadoop job metadata to job status. * * @param meta Metadata. * @return Status. */ @SuppressWarnings("ThrowableResultOfMethodCallIgnored") public static HadoopJobStatus status(HadoopJobMetadata meta) { HadoopJobInfo jobInfo = meta.jobInfo(); return new HadoopJobStatus( meta.jobId(), jobInfo.jobName(), jobInfo.user(), meta.pendingSplits() != null ? meta.pendingSplits().size() : 0, meta.pendingReducers() != null ? meta.pendingReducers().size() : 0, meta.mapReducePlan().mappers(), meta.mapReducePlan().reducers(), meta.phase(), meta.failCause() != null, meta.version() ); } /** * Gets hadoop job status for given job ID. * * @param jobId Job ID to get status for. * @return Job status for given job ID or {@code null} if job was not found. */ @Nullable public HadoopJobStatus status(HadoopJobId jobId) throws IgniteCheckedException { if (!busyLock.tryReadLock()) return null; // Grid is stopping. try { HadoopJobMetadata meta = jobMetaCache().get(jobId); return meta != null ? status(meta) : null; } finally { busyLock.readUnlock(); } } /** * Gets job finish future. * * @param jobId Job ID. * @return Finish future or {@code null}. * @throws IgniteCheckedException If failed. */ @Nullable public IgniteInternalFuture<?> finishFuture(HadoopJobId jobId) throws IgniteCheckedException { if (!busyLock.tryReadLock()) return null; // Grid is stopping. try { HadoopJobMetadata meta = jobMetaCache().get(jobId); if (meta == null) return null; if (log.isTraceEnabled()) log.trace("Got job metadata for status check [locNodeId=" + ctx.localNodeId() + ", meta=" + meta + ']'); if (meta.phase() == PHASE_COMPLETE) { if (log.isTraceEnabled()) log.trace("Job is complete, returning finished future: " + jobId); return new GridFinishedFuture<>(jobId); } GridFutureAdapter<HadoopJobId> fut = F.addIfAbsent(activeFinishFuts, jobId, new GridFutureAdapter<HadoopJobId>()); // Get meta from cache one more time to close the window. meta = jobMetaCache().get(jobId); if (log.isTraceEnabled()) log.trace("Re-checking job metadata [locNodeId=" + ctx.localNodeId() + ", meta=" + meta + ']'); if (meta == null) { fut.onDone(); activeFinishFuts.remove(jobId , fut); } else if (meta.phase() == PHASE_COMPLETE) { fut.onDone(jobId, meta.failCause()); activeFinishFuts.remove(jobId , fut); } return fut; } finally { busyLock.readUnlock(); } } /** * Gets job plan by job ID. * * @param jobId Job ID. * @return Job plan. * @throws IgniteCheckedException If failed. */ public HadoopMapReducePlan plan(HadoopJobId jobId) throws IgniteCheckedException { if (!busyLock.tryReadLock()) return null; try { HadoopJobMetadata meta = jobMetaCache().get(jobId); if (meta != null) return meta.mapReducePlan(); return null; } finally { busyLock.readUnlock(); } } /** * Callback from task executor invoked when a task has been finished. * * @param info Task info. * @param status Task status. */ @SuppressWarnings({"ConstantConditions", "ThrowableResultOfMethodCallIgnored"}) public void onTaskFinished(HadoopTaskInfo info, HadoopTaskStatus status) { if (!busyLock.tryReadLock()) return; try { assert status.state() != RUNNING; if (log.isDebugEnabled()) log.debug("Received task finished callback [info=" + info + ", status=" + status + ']'); JobLocalState state = activeJobs.get(info.jobId()); // Task CRASHes with null fail cause. assert (status.state() != FAILED) || status.failCause() != null : "Invalid task status [info=" + info + ", status=" + status + ']'; assert state != null || (ctx.jobUpdateLeader() && (info.type() == COMMIT || info.type() == ABORT)): "Missing local state for finished task [info=" + info + ", status=" + status + ']'; StackedProcessor incrCntrs = null; if (status.state() == COMPLETED) incrCntrs = new IncrementCountersProcessor(null, status.counters()); switch (info.type()) { case SETUP: { state.onSetupFinished(info, status, incrCntrs); break; } case MAP: { state.onMapFinished(info, status, incrCntrs); break; } case REDUCE: { state.onReduceFinished(info, status, incrCntrs); break; } case COMBINE: { state.onCombineFinished(info, status, incrCntrs); break; } case COMMIT: case ABORT: { IgniteInternalCache<HadoopJobId, HadoopJobMetadata> cache = finishedJobMetaCache(); cache.invokeAsync(info.jobId(), new UpdatePhaseProcessor(incrCntrs, PHASE_COMPLETE)). listen(failsLog); break; } } } finally { busyLock.readUnlock(); } } /** * @param jobId Job id. * @param c Closure of operation. */ private void transform(HadoopJobId jobId, EntryProcessor<HadoopJobId, HadoopJobMetadata, Void> c) { jobMetaCache().invokeAsync(jobId, c).listen(failsLog); } /** * Callback from task executor called when process is ready to received shuffle messages. * * @param jobId Job ID. * @param reducers Reducers. * @param desc Process descriptor. */ public void onExternalMappersInitialized(HadoopJobId jobId, Collection<Integer> reducers, HadoopProcessDescriptor desc) { transform(jobId, new InitializeReducersProcessor(null, reducers, desc)); } /** * Gets all input splits for given hadoop map-reduce plan. * * @param plan Map-reduce plan. * @return Collection of all input splits that should be processed. */ @SuppressWarnings("ConstantConditions") private Map<HadoopInputSplit, Integer> allSplits(HadoopMapReducePlan plan) { Map<HadoopInputSplit, Integer> res = new HashMap<>(); int taskNum = 0; for (UUID nodeId : plan.mapperNodeIds()) { for (HadoopInputSplit split : plan.mappers(nodeId)) { if (res.put(split, taskNum++) != null) throw new IllegalStateException("Split duplicate."); } } return res; } /** * Gets all reducers for this job. * * @param plan Map-reduce plan. * @return Collection of reducers. */ private Collection<Integer> allReducers(HadoopMapReducePlan plan) { Collection<Integer> res = new HashSet<>(); for (int i = 0; i < plan.reducers(); i++) res.add(i); return res; } /** * Processes node leave (or fail) event. * * @param evt Discovery event. */ @SuppressWarnings("ConstantConditions") private void processNodeLeft(DiscoveryEvent evt) { if (log.isDebugEnabled()) log.debug("Processing discovery event [locNodeId=" + ctx.localNodeId() + ", evt=" + evt + ']'); // Check only if this node is responsible for job status updates. if (ctx.jobUpdateLeader()) { boolean checkSetup = evt.eventNode().order() < ctx.localNodeOrder(); // Iteration over all local entries is correct since system cache is REPLICATED. for (Object metaObj : jobMetaCache().values()) { HadoopJobMetadata meta = (HadoopJobMetadata)metaObj; HadoopJobId jobId = meta.jobId(); HadoopMapReducePlan plan = meta.mapReducePlan(); HadoopJobPhase phase = meta.phase(); try { if (checkSetup && phase == PHASE_SETUP && !activeJobs.containsKey(jobId)) { // Failover setup task. HadoopJob job = job(jobId, meta.jobInfo()); Collection<HadoopTaskInfo> setupTask = setupTask(jobId); assert setupTask != null; ctx.taskExecutor().run(job, setupTask); } else if (phase == PHASE_MAP || phase == PHASE_REDUCE) { // Must check all nodes, even that are not event node ID due to // multiple node failure possibility. Collection<HadoopInputSplit> cancelSplits = null; for (UUID nodeId : plan.mapperNodeIds()) { if (ctx.kernalContext().discovery().node(nodeId) == null) { // Node has left the grid. Collection<HadoopInputSplit> mappers = plan.mappers(nodeId); if (cancelSplits == null) cancelSplits = new HashSet<>(); cancelSplits.addAll(mappers); } } Collection<Integer> cancelReducers = null; for (UUID nodeId : plan.reducerNodeIds()) { if (ctx.kernalContext().discovery().node(nodeId) == null) { // Node has left the grid. int[] reducers = plan.reducers(nodeId); if (cancelReducers == null) cancelReducers = new HashSet<>(); for (int rdc : reducers) cancelReducers.add(rdc); } } if (cancelSplits != null || cancelReducers != null) jobMetaCache().invoke(meta.jobId(), new CancelJobProcessor(null, new IgniteCheckedException( "One or more nodes participating in map-reduce job execution failed."), cancelSplits, cancelReducers)); } } catch (IgniteCheckedException e) { U.error(log, "Failed to cancel job: " + meta, e); } } } } /** * @param updated Updated cache entries. * @throws IgniteCheckedException If failed. */ private void processJobMetadataUpdates( Iterable<CacheEntryEvent<? extends HadoopJobId, ? extends HadoopJobMetadata>> updated) throws IgniteCheckedException { UUID locNodeId = ctx.localNodeId(); for (CacheEntryEvent<? extends HadoopJobId, ? extends HadoopJobMetadata> entry : updated) { HadoopJobId jobId = entry.getKey(); HadoopJobMetadata meta = entry.getValue(); if (meta == null || !ctx.isParticipating(meta)) continue; if (log.isDebugEnabled()) log.debug("Processing job metadata update callback [locNodeId=" + locNodeId + ", meta=" + meta + ']'); try { ctx.taskExecutor().onJobStateChanged(meta); } catch (IgniteCheckedException e) { U.error(log, "Failed to process job state changed callback (will fail the job) " + "[locNodeId=" + locNodeId + ", jobId=" + jobId + ", meta=" + meta + ']', e); transform(jobId, new CancelJobProcessor(null, e)); continue; } processJobMetaUpdate(jobId, meta, locNodeId); } } /** * @param jobId Job ID. * @param plan Map-reduce plan. */ private void printPlan(HadoopJobId jobId, HadoopMapReducePlan plan) { log.info("Plan for " + jobId); SB b = new SB(); b.a(" Map: "); for (UUID nodeId : plan.mapperNodeIds()) b.a(nodeId).a("=").a(plan.mappers(nodeId).size()).a(' '); log.info(b.toString()); b = new SB(); b.a(" Reduce: "); for (UUID nodeId : plan.reducerNodeIds()) b.a(nodeId).a("=").a(Arrays.toString(plan.reducers(nodeId))).a(' '); log.info(b.toString()); } /** * @param jobId Job ID. * @param meta Job metadata. * @param locNodeId Local node ID. * @throws IgniteCheckedException If failed. */ private void processJobMetaUpdate(HadoopJobId jobId, HadoopJobMetadata meta, UUID locNodeId) throws IgniteCheckedException { JobLocalState state = activeJobs.get(jobId); HadoopJob job = job(jobId, meta.jobInfo()); HadoopMapReducePlan plan = meta.mapReducePlan(); switch (meta.phase()) { case PHASE_SETUP: { if (ctx.jobUpdateLeader()) { Collection<HadoopTaskInfo> setupTask = setupTask(jobId); if (setupTask != null) ctx.taskExecutor().run(job, setupTask); } break; } case PHASE_MAP: { // Check if we should initiate new task on local node. Collection<HadoopTaskInfo> tasks = mapperTasks(plan.mappers(locNodeId), meta); if (tasks != null) ctx.taskExecutor().run(job, tasks); break; } case PHASE_REDUCE: { if (meta.pendingReducers().isEmpty() && ctx.jobUpdateLeader()) { HadoopTaskInfo info = new HadoopTaskInfo(COMMIT, jobId, 0, 0, null); if (log.isDebugEnabled()) log.debug("Submitting COMMIT task for execution [locNodeId=" + locNodeId + ", jobId=" + jobId + ']'); ctx.taskExecutor().run(job, Collections.singletonList(info)); break; } Collection<HadoopTaskInfo> tasks = reducerTasks(plan.reducers(locNodeId), job); if (tasks != null) ctx.taskExecutor().run(job, tasks); break; } case PHASE_CANCELLING: { // Prevent multiple task executor notification. if (state != null && state.onCancel()) { if (log.isDebugEnabled()) log.debug("Cancelling local task execution for job: " + meta); ctx.taskExecutor().cancelTasks(jobId); } if (meta.pendingSplits().isEmpty() && meta.pendingReducers().isEmpty()) { if (ctx.jobUpdateLeader()) { if (state == null) state = initState(jobId); // Prevent running multiple abort tasks. if (state.onAborted()) { HadoopTaskInfo info = new HadoopTaskInfo(ABORT, jobId, 0, 0, null); if (log.isDebugEnabled()) log.debug("Submitting ABORT task for execution [locNodeId=" + locNodeId + ", jobId=" + jobId + ']'); ctx.taskExecutor().run(job, Collections.singletonList(info)); } } break; } else { // Check if there are unscheduled mappers or reducers. Collection<HadoopInputSplit> cancelMappers = new ArrayList<>(); Collection<Integer> cancelReducers = new ArrayList<>(); Collection<HadoopInputSplit> mappers = plan.mappers(ctx.localNodeId()); if (mappers != null) { for (HadoopInputSplit b : mappers) { if (state == null || !state.mapperScheduled(b)) cancelMappers.add(b); } } int[] rdc = plan.reducers(ctx.localNodeId()); if (rdc != null) { for (int r : rdc) { if (state == null || !state.reducerScheduled(r)) cancelReducers.add(r); } } if (!cancelMappers.isEmpty() || !cancelReducers.isEmpty()) transform(jobId, new CancelJobProcessor(null, cancelMappers, cancelReducers)); } break; } case PHASE_COMPLETE: { if (log.isDebugEnabled()) log.debug("Job execution is complete, will remove local state from active jobs " + "[jobId=" + jobId + ", meta=" + meta + ']'); if (state != null) { state = activeJobs.remove(jobId); assert state != null; ctx.shuffle().jobFinished(jobId); } GridFutureAdapter<HadoopJobId> finishFut = activeFinishFuts.remove(jobId); if (finishFut != null) { if (log.isDebugEnabled()) log.debug("Completing job future [locNodeId=" + locNodeId + ", meta=" + meta + ']'); finishFut.onDone(jobId, meta.failCause()); } if (ctx.jobUpdateLeader()) job.cleanupStagingDirectory(); jobs.remove(jobId); if (ctx.jobUpdateLeader()) { ClassLoader ldr = job.getClass().getClassLoader(); try { String statWriterClsName = job.info().property(HadoopUtils.JOB_COUNTER_WRITER_PROPERTY); if (statWriterClsName != null) { Class<?> cls = ldr.loadClass(statWriterClsName); HadoopCounterWriter writer = (HadoopCounterWriter)cls.newInstance(); HadoopCounters cntrs = meta.counters(); writer.write(job, cntrs); } } catch (Exception e) { log.error("Can't write statistic due to: ", e); } } job.dispose(false); break; } default: throw new IllegalStateException("Unknown phase: " + meta.phase()); } } /** * Creates setup task based on job information. * * @param jobId Job ID. * @return Setup task wrapped in collection. */ @Nullable private Collection<HadoopTaskInfo> setupTask(HadoopJobId jobId) { if (activeJobs.containsKey(jobId)) return null; else { initState(jobId); return Collections.singleton(new HadoopTaskInfo(SETUP, jobId, 0, 0, null)); } } /** * Creates mapper tasks based on job information. * * @param mappers Mapper blocks. * @param meta Job metadata. * @return Collection of created task infos or {@code null} if no mapper tasks scheduled for local node. */ private Collection<HadoopTaskInfo> mapperTasks(Iterable<HadoopInputSplit> mappers, HadoopJobMetadata meta) { UUID locNodeId = ctx.localNodeId(); HadoopJobId jobId = meta.jobId(); JobLocalState state = activeJobs.get(jobId); Collection<HadoopTaskInfo> tasks = null; if (mappers != null) { if (state == null) state = initState(jobId); for (HadoopInputSplit split : mappers) { if (state.addMapper(split)) { if (log.isDebugEnabled()) log.debug("Submitting MAP task for execution [locNodeId=" + locNodeId + ", split=" + split + ']'); HadoopTaskInfo taskInfo = new HadoopTaskInfo(MAP, jobId, meta.taskNumber(split), 0, split); if (tasks == null) tasks = new ArrayList<>(); tasks.add(taskInfo); } } } return tasks; } /** * Creates reducer tasks based on job information. * * @param reducers Reducers (may be {@code null}). * @param job Job instance. * @return Collection of task infos. */ private Collection<HadoopTaskInfo> reducerTasks(int[] reducers, HadoopJob job) { UUID locNodeId = ctx.localNodeId(); HadoopJobId jobId = job.id(); JobLocalState state = activeJobs.get(jobId); Collection<HadoopTaskInfo> tasks = null; if (reducers != null) { if (state == null) state = initState(job.id()); for (int rdc : reducers) { if (state.addReducer(rdc)) { if (log.isDebugEnabled()) log.debug("Submitting REDUCE task for execution [locNodeId=" + locNodeId + ", rdc=" + rdc + ']'); HadoopTaskInfo taskInfo = new HadoopTaskInfo(REDUCE, jobId, rdc, 0, null); if (tasks == null) tasks = new ArrayList<>(); tasks.add(taskInfo); } } } return tasks; } /** * Initializes local state for given job metadata. * * @param jobId Job ID. * @return Local state. */ private JobLocalState initState(HadoopJobId jobId) { return F.addIfAbsent(activeJobs, jobId, new JobLocalState()); } /** * Gets or creates job instance. * * @param jobId Job ID. * @param jobInfo Job info. * @return Job. * @throws IgniteCheckedException If failed. */ @Nullable public HadoopJob job(HadoopJobId jobId, @Nullable HadoopJobInfo jobInfo) throws IgniteCheckedException { GridFutureAdapter<HadoopJob> fut = jobs.get(jobId); if (fut != null || (fut = jobs.putIfAbsent(jobId, new GridFutureAdapter<HadoopJob>())) != null) return fut.get(); fut = jobs.get(jobId); HadoopJob job = null; try { if (jobInfo == null) { HadoopJobMetadata meta = jobMetaCache().get(jobId); if (meta == null) throw new IgniteCheckedException("Failed to find job metadata for ID: " + jobId); jobInfo = meta.jobInfo(); } job = jobInfo.createJob(jobCls, jobId, log); job.initialize(false, ctx.localNodeId()); fut.onDone(job); return job; } catch (IgniteCheckedException e) { fut.onDone(e); jobs.remove(jobId, fut); if (job != null) { try { job.dispose(false); } catch (IgniteCheckedException e0) { U.error(log, "Failed to dispose job: " + jobId, e0); } } throw e; } } /** * Kills job. * * @param jobId Job ID. * @return {@code True} if job was killed. * @throws IgniteCheckedException If failed. */ public boolean killJob(HadoopJobId jobId) throws IgniteCheckedException { if (!busyLock.tryReadLock()) return false; // Grid is stopping. try { HadoopJobMetadata meta = jobMetaCache().get(jobId); if (meta != null && meta.phase() != PHASE_COMPLETE && meta.phase() != PHASE_CANCELLING) { HadoopTaskCancelledException err = new HadoopTaskCancelledException("Job cancelled."); jobMetaCache().invoke(jobId, new CancelJobProcessor(null, err)); } } finally { busyLock.readUnlock(); } IgniteInternalFuture<?> fut = finishFuture(jobId); if (fut != null) { try { fut.get(); } catch (Exception e) { if (e.getCause() instanceof HadoopTaskCancelledException) return true; } } return false; } /** * Returns job counters. * * @param jobId Job identifier. * @return Job counters or {@code null} if job cannot be found. * @throws IgniteCheckedException If failed. */ @Nullable public HadoopCounters jobCounters(HadoopJobId jobId) throws IgniteCheckedException { if (!busyLock.tryReadLock()) return null; try { final HadoopJobMetadata meta = jobMetaCache().get(jobId); return meta != null ? meta.counters() : null; } finally { busyLock.readUnlock(); } } /** * Event handler protected by busy lock. */ private abstract class EventHandler implements Runnable { /** {@inheritDoc} */ @Override public void run() { if (!busyLock.tryReadLock()) return; try { body(); } catch (Throwable e) { U.error(log, "Unhandled exception while processing event.", e); if (e instanceof Error) throw (Error)e; } finally { busyLock.readUnlock(); } } /** * Handler body. */ protected abstract void body() throws Exception; } /** * */ private class JobLocalState { /** Mappers. */ private final Collection<HadoopInputSplit> currMappers = new HashSet<>(); /** Reducers. */ private final Collection<Integer> currReducers = new HashSet<>(); /** Number of completed mappers. */ private final AtomicInteger completedMappersCnt = new AtomicInteger(); /** Cancelled flag. */ private boolean cancelled; /** Aborted flag. */ private boolean aborted; /** * @param mapSplit Map split to add. * @return {@code True} if mapper was added. */ private boolean addMapper(HadoopInputSplit mapSplit) { return currMappers.add(mapSplit); } /** * @param rdc Reducer number to add. * @return {@code True} if reducer was added. */ private boolean addReducer(int rdc) { return currReducers.add(rdc); } /** * Checks whether this split was scheduled for given attempt. * * @param mapSplit Map split to check. * @return {@code True} if mapper was scheduled. */ public boolean mapperScheduled(HadoopInputSplit mapSplit) { return currMappers.contains(mapSplit); } /** * Checks whether this split was scheduled for given attempt. * * @param rdc Reducer number to check. * @return {@code True} if reducer was scheduled. */ public boolean reducerScheduled(int rdc) { return currReducers.contains(rdc); } /** * @param taskInfo Task info. * @param status Task status. * @param prev Previous closure. */ private void onSetupFinished(final HadoopTaskInfo taskInfo, HadoopTaskStatus status, StackedProcessor prev) { final HadoopJobId jobId = taskInfo.jobId(); if (status.state() == FAILED || status.state() == CRASHED) transform(jobId, new CancelJobProcessor(prev, status.failCause())); else transform(jobId, new UpdatePhaseProcessor(prev, PHASE_MAP)); } /** * @param taskInfo Task info. * @param status Task status. * @param prev Previous closure. */ private void onMapFinished(final HadoopTaskInfo taskInfo, HadoopTaskStatus status, final StackedProcessor prev) { final HadoopJobId jobId = taskInfo.jobId(); boolean lastMapperFinished = completedMappersCnt.incrementAndGet() == currMappers.size(); if (status.state() == FAILED || status.state() == CRASHED) { // Fail the whole job. transform(jobId, new RemoveMappersProcessor(prev, taskInfo.inputSplit(), status.failCause())); return; } IgniteInClosure<IgniteInternalFuture<?>> cacheUpdater = new CIX1<IgniteInternalFuture<?>>() { @Override public void applyx(IgniteInternalFuture<?> f) { Throwable err = null; if (f != null) { try { f.get(); } catch (IgniteCheckedException e) { err = e; } } transform(jobId, new RemoveMappersProcessor(prev, taskInfo.inputSplit(), err)); } }; if (lastMapperFinished) ctx.shuffle().flush(jobId).listen(cacheUpdater); else cacheUpdater.apply(null); } /** * @param taskInfo Task info. * @param status Task status. * @param prev Previous closure. */ private void onReduceFinished(HadoopTaskInfo taskInfo, HadoopTaskStatus status, StackedProcessor prev) { HadoopJobId jobId = taskInfo.jobId(); if (status.state() == FAILED || status.state() == CRASHED) // Fail the whole job. transform(jobId, new RemoveReducerProcessor(prev, taskInfo.taskNumber(), status.failCause())); else transform(jobId, new RemoveReducerProcessor(prev, taskInfo.taskNumber())); } /** * @param taskInfo Task info. * @param status Task status. * @param prev Previous closure. */ private void onCombineFinished(HadoopTaskInfo taskInfo, HadoopTaskStatus status, final StackedProcessor prev) { final HadoopJobId jobId = taskInfo.jobId(); if (status.state() == FAILED || status.state() == CRASHED) // Fail the whole job. transform(jobId, new RemoveMappersProcessor(prev, currMappers, status.failCause())); else { ctx.shuffle().flush(jobId).listen(new CIX1<IgniteInternalFuture<?>>() { @Override public void applyx(IgniteInternalFuture<?> f) { Throwable err = null; if (f != null) { try { f.get(); } catch (IgniteCheckedException e) { err = e; } } transform(jobId, new RemoveMappersProcessor(prev, currMappers, err)); } }); } } /** * @return {@code True} if job was cancelled by this (first) call. */ public boolean onCancel() { if (!cancelled && !aborted) { cancelled = true; return true; } return false; } /** * @return {@code True} if job was aborted this (first) call. */ public boolean onAborted() { if (!aborted) { aborted = true; return true; } return false; } } /** * Update job phase transform closure. */ private static class UpdatePhaseProcessor extends StackedProcessor { /** */ private static final long serialVersionUID = 0L; /** Phase to update. */ private final HadoopJobPhase phase; /** * @param prev Previous closure. * @param phase Phase to update. */ private UpdatePhaseProcessor(@Nullable StackedProcessor prev, HadoopJobPhase phase) { super(prev); this.phase = phase; } /** {@inheritDoc} */ @Override protected void update(HadoopJobMetadata meta, HadoopJobMetadata cp) { cp.phase(phase); } } /** * Remove mapper transform closure. */ private static class RemoveMappersProcessor extends StackedProcessor { /** */ private static final long serialVersionUID = 0L; /** Mapper split to remove. */ private final Collection<HadoopInputSplit> splits; /** Error. */ private final Throwable err; /** * @param prev Previous closure. * @param split Mapper split to remove. * @param err Error. */ private RemoveMappersProcessor(@Nullable StackedProcessor prev, HadoopInputSplit split, Throwable err) { this(prev, Collections.singletonList(split), err); } /** * @param prev Previous closure. * @param splits Mapper splits to remove. * @param err Error. */ private RemoveMappersProcessor(@Nullable StackedProcessor prev, Collection<HadoopInputSplit> splits, Throwable err) { super(prev); this.splits = splits; this.err = err; } /** {@inheritDoc} */ @Override protected void update(HadoopJobMetadata meta, HadoopJobMetadata cp) { Map<HadoopInputSplit, Integer> splitsCp = new HashMap<>(cp.pendingSplits()); for (HadoopInputSplit s : splits) splitsCp.remove(s); cp.pendingSplits(splitsCp); if (cp.phase() != PHASE_CANCELLING && err != null) cp.failCause(err); if (err != null) cp.phase(PHASE_CANCELLING); if (splitsCp.isEmpty()) { if (cp.phase() != PHASE_CANCELLING) cp.phase(PHASE_REDUCE); } } } /** * Remove reducer transform closure. */ private static class RemoveReducerProcessor extends StackedProcessor { /** */ private static final long serialVersionUID = 0L; /** Mapper split to remove. */ private final int rdc; /** Error. */ private Throwable err; /** * @param prev Previous closure. * @param rdc Reducer to remove. */ private RemoveReducerProcessor(@Nullable StackedProcessor prev, int rdc) { super(prev); this.rdc = rdc; } /** * @param prev Previous closure. * @param rdc Reducer to remove. * @param err Error. */ private RemoveReducerProcessor(@Nullable StackedProcessor prev, int rdc, Throwable err) { super(prev); this.rdc = rdc; this.err = err; } /** {@inheritDoc} */ @Override protected void update(HadoopJobMetadata meta, HadoopJobMetadata cp) { Collection<Integer> rdcCp = new HashSet<>(cp.pendingReducers()); rdcCp.remove(rdc); cp.pendingReducers(rdcCp); if (err != null) { cp.phase(PHASE_CANCELLING); cp.failCause(err); } } } /** * Initialize reducers. */ private static class InitializeReducersProcessor extends StackedProcessor { /** */ private static final long serialVersionUID = 0L; /** Reducers. */ private final Collection<Integer> rdc; /** Process descriptor for reducers. */ private final HadoopProcessDescriptor desc; /** * @param prev Previous closure. * @param rdc Reducers to initialize. * @param desc External process descriptor. */ private InitializeReducersProcessor(@Nullable StackedProcessor prev, Collection<Integer> rdc, HadoopProcessDescriptor desc) { super(prev); assert !F.isEmpty(rdc); assert desc != null; this.rdc = rdc; this.desc = desc; } /** {@inheritDoc} */ @Override protected void update(HadoopJobMetadata meta, HadoopJobMetadata cp) { Map<Integer, HadoopProcessDescriptor> oldMap = meta.reducersAddresses(); Map<Integer, HadoopProcessDescriptor> rdcMap = oldMap == null ? new HashMap<Integer, HadoopProcessDescriptor>() : new HashMap<>(oldMap); for (Integer r : rdc) rdcMap.put(r, desc); cp.reducersAddresses(rdcMap); } } /** * Remove reducer transform closure. */ private static class CancelJobProcessor extends StackedProcessor { /** */ private static final long serialVersionUID = 0L; /** Mapper split to remove. */ private final Collection<HadoopInputSplit> splits; /** Reducers to remove. */ private final Collection<Integer> rdc; /** Error. */ private final Throwable err; /** * @param prev Previous closure. * @param err Fail cause. */ private CancelJobProcessor(@Nullable StackedProcessor prev, Throwable err) { this(prev, err, null, null); } /** * @param prev Previous closure. * @param splits Splits to remove. * @param rdc Reducers to remove. */ private CancelJobProcessor(@Nullable StackedProcessor prev, Collection<HadoopInputSplit> splits, Collection<Integer> rdc) { this(prev, null, splits, rdc); } /** * @param prev Previous closure. * @param err Error. * @param splits Splits to remove. * @param rdc Reducers to remove. */ private CancelJobProcessor(@Nullable StackedProcessor prev, Throwable err, Collection<HadoopInputSplit> splits, Collection<Integer> rdc) { super(prev); this.splits = splits; this.rdc = rdc; this.err = err; } /** {@inheritDoc} */ @Override protected void update(HadoopJobMetadata meta, HadoopJobMetadata cp) { final HadoopJobPhase currPhase = meta.phase(); assert currPhase == PHASE_CANCELLING || currPhase == PHASE_COMPLETE || err != null: "Invalid phase for cancel: " + currPhase; Collection<Integer> rdcCp = new HashSet<>(cp.pendingReducers()); if (rdc != null) rdcCp.removeAll(rdc); cp.pendingReducers(rdcCp); Map<HadoopInputSplit, Integer> splitsCp = new HashMap<>(cp.pendingSplits()); if (splits != null) { for (HadoopInputSplit s : splits) splitsCp.remove(s); } cp.pendingSplits(splitsCp); if (currPhase != PHASE_COMPLETE && currPhase != PHASE_CANCELLING) cp.phase(PHASE_CANCELLING); if (err != null) cp.failCause(err); } } /** * Increment counter values closure. */ private static class IncrementCountersProcessor extends StackedProcessor { /** */ private static final long serialVersionUID = 0L; /** */ private final HadoopCounters counters; /** * @param prev Previous closure. * @param counters Task counters to add into job counters. */ private IncrementCountersProcessor(@Nullable StackedProcessor prev, HadoopCounters counters) { super(prev); assert counters != null; this.counters = counters; } /** {@inheritDoc} */ @Override protected void update(HadoopJobMetadata meta, HadoopJobMetadata cp) { HadoopCounters cntrs = new HadoopCountersImpl(cp.counters()); cntrs.merge(counters); cp.counters(cntrs); } } /** * Abstract stacked closure. */ private abstract static class StackedProcessor implements EntryProcessor<HadoopJobId, HadoopJobMetadata, Void>, Serializable { /** */ private static final long serialVersionUID = 0L; /** */ private final StackedProcessor prev; /** * @param prev Previous closure. */ private StackedProcessor(@Nullable StackedProcessor prev) { this.prev = prev; } /** {@inheritDoc} */ @Override public Void process(MutableEntry<HadoopJobId, HadoopJobMetadata> e, Object... args) { HadoopJobMetadata val = apply(e.getValue()); if (val != null) e.setValue(val); else e.remove();; return null; } /** * @param meta Old value. * @return New value. */ private HadoopJobMetadata apply(HadoopJobMetadata meta) { if (meta == null) return null; HadoopJobMetadata cp = prev != null ? prev.apply(meta) : new HadoopJobMetadata(meta); update(meta, cp); return cp; } /** * Update given job metadata object. * * @param meta Initial job metadata. * @param cp Copy. */ protected abstract void update(HadoopJobMetadata meta, HadoopJobMetadata cp); } }
/* * Copyright (C) 2013 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration. * All Rights Reserved. */ package gov.nasa.worldwindx.applications.dataimporter; import gov.nasa.worldwind.*; import gov.nasa.worldwind.avlist.*; import gov.nasa.worldwind.cache.FileStore; import gov.nasa.worldwind.data.*; import gov.nasa.worldwind.exception.WWRuntimeException; import gov.nasa.worldwind.geom.Sector; import gov.nasa.worldwind.globes.ElevationModel; import gov.nasa.worldwind.layers.*; import gov.nasa.worldwind.render.*; import gov.nasa.worldwind.terrain.CompoundElevationModel; import gov.nasa.worldwind.util.*; import gov.nasa.worldwindx.examples.ApplicationTemplate; import gov.nasa.worldwindx.examples.util.ExampleUtil; import org.w3c.dom.*; import javax.swing.*; import java.awt.*; import java.beans.PropertyChangeEvent; import java.io.File; import java.util.*; /** * Handles all the work necessary to install tiled image layers and elevation models. * * @author tag * @version $Id: DataInstaller.java 1180 2013-02-15 18:40:47Z tgaskins $ */ public class DataInstaller extends AVListImpl { public static final String IMAGERY = "Imagery"; public static final String ELEVATION = "Elevation"; public static final String INSTALL_COMPLETE = "gov.nasa.worldwindx.dataimport.DataInstaller.InstallComplete"; public static final String PREVIEW_LAYER = "gov.nasa.worldwindx.dataimport.DataInstaller.PreviewLayer"; public Document installDataFromFiles(Component parentComponent, FileSet fileSet) throws Exception { // Create a DataStoreProducer that is capable of processing the file. final DataStoreProducer producer = createDataStoreProducerFromFiles(fileSet); File installLocation = this.getDefaultInstallLocation(WorldWind.getDataFileStore()); if (installLocation == null) { String message = Logging.getMessage("generic.NoDefaultImportLocation"); Logging.logger().severe(message); return null; } String datasetName = askForDatasetName(suggestDatasetName(fileSet)); DataInstallerProgressMonitor progressMonitor = new DataInstallerProgressMonitor(parentComponent, producer); Document doc = null; try { // Install the file into the specified FileStore. progressMonitor.start(); doc = createDataStore(fileSet, installLocation, datasetName, producer); // Create a raster server configuration document if the installation was successful. // The raster server document enables the layer or elevation model (created to display this data) // to create tiles from the original sources at runtime. createRasterServerConfigDoc(WorldWind.getDataFileStore(), producer); // The user clicked the ProgressMonitor's "Cancel" button. Revert any change made during production, // and // discard the returned DataConfiguration reference. if (progressMonitor.isCanceled()) { doc = null; producer.removeProductionState(); } } finally { progressMonitor.stop(); } return doc; } protected DataStoreProducer createDataStoreProducerFromFiles(FileSet fileSet) throws IllegalArgumentException { if (fileSet == null || fileSet.getLength() == 0) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String commonPixelFormat = this.determineCommonPixelFormat(fileSet); if (AVKey.IMAGE.equals(commonPixelFormat)) { return new TiledImageProducer(); } else if (AVKey.ELEVATION.equals(commonPixelFormat)) { return new TiledElevationProducer(); } String message = Logging.getMessage("generic.UnexpectedRasterType", commonPixelFormat); Logging.logger().severe(message); throw new IllegalArgumentException(message); } protected String determineCommonPixelFormat(FileSet fileSet) throws IllegalArgumentException { if (fileSet == null || fileSet.getLength() == 0) { String message = Logging.getMessage("nullValue.ArrayIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } String commonPixelFormat = null; for (File file : fileSet.getFiles()) { AVList params = new AVListImpl(); if (this.isDataRaster(file, params)) { String pixelFormat = params.getStringValue(AVKey.PIXEL_FORMAT); if (WWUtil.isEmpty(commonPixelFormat)) { if (WWUtil.isEmpty(pixelFormat)) { String message = Logging.getMessage("generic.UnrecognizedSourceType", file.getAbsolutePath()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } else { commonPixelFormat = pixelFormat; } } else if (commonPixelFormat != null && !commonPixelFormat.equals(pixelFormat)) { if (WWUtil.isEmpty(pixelFormat)) { String message = Logging.getMessage("generic.UnrecognizedSourceType", file.getAbsolutePath()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } else { String reason = Logging.getMessage("generic.UnexpectedRasterType", pixelFormat); String details = file.getAbsolutePath() + ": " + reason; String message = Logging.getMessage("DataRaster.IncompatibleRaster", details); Logging.logger().severe(message); throw new IllegalArgumentException(message); } } } } return commonPixelFormat; } protected Document createDataStore(FileSet fileSet, File installLocation, String datasetName, DataStoreProducer producer) throws Exception { // Create the production parameters. These parameters instruct the DataStoreProducer where to install the // cached data, and what name to put in the data configuration document. AVList params = new AVListImpl(); params.setValue(AVKey.DATASET_NAME, datasetName); params.setValue(AVKey.DATA_CACHE_NAME, datasetName); params.setValue(AVKey.FILE_STORE_LOCATION, installLocation.getAbsolutePath()); // These parameters define producer's behavior: // create a full tile cache OR generate only first two low resolution levels boolean enableFullPyramid = Configuration.getBooleanValue(AVKey.PRODUCER_ENABLE_FULL_PYRAMID, false); if (!enableFullPyramid) { params.setValue(AVKey.SERVICE_NAME, AVKey.SERVICE_NAME_LOCAL_RASTER_SERVER); // retrieve the value of the AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL, default to "Auto" if missing String maxLevel = Configuration.getStringValue(AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL, "0"); params.setValue(AVKey.TILED_RASTER_PRODUCER_LIMIT_MAX_LEVEL, maxLevel); } else { params.setValue(AVKey.PRODUCER_ENABLE_FULL_PYRAMID, true); } producer.setStoreParameters(params); try { for (File file : fileSet.getFiles()) { producer.offerDataSource(file, null); Thread.yield(); } // Convert the file to a form usable by World Wind components, // according to the specified DataStoreProducer. // This throws an exception if production fails for any reason. producer.startProduction(); } catch (InterruptedException ie) { producer.removeProductionState(); Thread.interrupted(); throw ie; } catch (Exception e) { // Exception attempting to convert the file. Revert any change made during production. producer.removeProductionState(); throw e; } // Return the DataConfiguration from the production results. Since production successfully completed, the // DataStoreProducer should contain a DataConfiguration in the production results. We test the production // results anyway. Iterable results = producer.getProductionResults(); if (results != null && results.iterator() != null && results.iterator().hasNext()) { Object o = results.iterator().next(); if (o != null && o instanceof Document) { return (Document) o; } } return null; } protected String askForDatasetName(String suggestedName) { String datasetName = suggestedName; for (; ; ) { Object o = JOptionPane.showInputDialog(null, "Name:", "Enter dataset name", JOptionPane.QUESTION_MESSAGE, null, null, datasetName); if (!(o instanceof String)) // user canceled the input { Thread.interrupted(); String msg = Logging.getMessage("generic.OperationCancelled", "Import"); Logging.logger().info(msg); throw new WWRuntimeException(msg); } return WWIO.replaceIllegalFileNameCharacters((String) o); } } protected String suggestDatasetName(FileSet fileSet) { if (null == fileSet || fileSet.getLength() == 0) { return null; } if (fileSet.getName() != null) return fileSet.getScale() != null ? fileSet.getName() + " " + fileSet.getScale() : fileSet.getName(); // extract file and folder names that all files have in common StringBuilder sb = new StringBuilder(); for (File file : fileSet.getFiles()) { String name = file.getAbsolutePath(); if (WWUtil.isEmpty(name)) { continue; } name = WWIO.replaceIllegalFileNameCharacters(WWIO.replaceSuffix(name, "")); if (sb.length() == 0) { sb.append(name); continue; } else { int size = Math.min(name.length(), sb.length()); for (int i = 0; i < size; i++) { if (name.charAt(i) != sb.charAt(i)) { sb.setLength(i); break; } } } } String name = sb.toString(); sb.setLength(0); ArrayList<String> words = new ArrayList<String>(); StringTokenizer tokens = new StringTokenizer(name, " _:/\\-=!@#$%^&()[]{}|\".,<>;`+"); String lastWord = null; while (tokens.hasMoreTokens()) { String word = tokens.nextToken(); // discard empty, one-char long, and duplicated keys if (WWUtil.isEmpty(word) || word.length() < 2 || word.equalsIgnoreCase(lastWord)) { continue; } lastWord = word; words.add(word); if (words.size() > 4) // let's keep only last four words { words.remove(0); } } if (words.size() > 0) { sb.setLength(0); for (String word : words) { sb.append(word).append(' '); } sb.append(fileSet.isImagery() ? " Imagery" : fileSet.isElevation() ? " Elevations" : ""); return sb.toString().trim(); } else { return (WWUtil.isEmpty(name)) ? "change me" : name; } } protected void createRasterServerConfigDoc(FileStore fileStore, DataStoreProducer producer) { AVList productionParams = (null != producer) ? producer.getProductionParameters() : new AVListImpl(); productionParams = (null == productionParams) ? new AVListImpl() : productionParams; if (!AVKey.SERVICE_NAME_LOCAL_RASTER_SERVER.equals(productionParams.getValue(AVKey.SERVICE_NAME))) { // *.RasterServer.xml is not required return; } File installLocation = this.getDefaultInstallLocation(fileStore); if (installLocation == null) { String message = Logging.getMessage("generic.NoDefaultImportLocation"); Logging.logger().severe(message); return; } Document doc = WWXML.createDocumentBuilder(true).newDocument(); Element root = WWXML.setDocumentElement(doc, "RasterServer"); WWXML.setTextAttribute(root, "version", "1.0"); StringBuilder sb = new StringBuilder(); sb.append(installLocation.getAbsolutePath()).append(File.separator); if (!productionParams.hasKey(AVKey.DATA_CACHE_NAME)) { String message = Logging.getMessage("generic.MissingRequiredParameter", AVKey.DATA_CACHE_NAME); Logging.logger().severe(message); throw new WWRuntimeException(message); } sb.append(productionParams.getValue(AVKey.DATA_CACHE_NAME)).append(File.separator); if (!productionParams.hasKey(AVKey.DATASET_NAME)) { String message = Logging.getMessage("generic.MissingRequiredParameter", AVKey.DATASET_NAME); Logging.logger().severe(message); throw new WWRuntimeException(message); } sb.append(productionParams.getValue(AVKey.DATASET_NAME)).append(".RasterServer.xml"); Object o = productionParams.getValue(AVKey.DISPLAY_NAME); if (WWUtil.isEmpty(o)) { productionParams.setValue(AVKey.DISPLAY_NAME, productionParams.getValue(AVKey.DATASET_NAME)); } String rasterServerConfigFilePath = sb.toString(); Sector extent = null; if (productionParams.hasKey(AVKey.SECTOR)) { o = productionParams.getValue(AVKey.SECTOR); if (null != o && o instanceof Sector) { extent = (Sector) o; } } if (null != extent) { WWXML.appendSector(root, "Sector", extent); } else { String message = Logging.getMessage("generic.MissingRequiredParameter", AVKey.SECTOR); Logging.logger().severe(message); throw new WWRuntimeException(message); } Element sources = doc.createElementNS(null, "Sources"); if (producer instanceof TiledRasterProducer) { for (DataRaster raster : ((TiledRasterProducer) producer).getDataRasters()) { if (raster instanceof CachedDataRaster) { try { appendSource(sources, (CachedDataRaster) raster); } catch (Throwable t) { String reason = WWUtil.extractExceptionReason(t); Logging.logger().warning(reason); // Logging.logger().severe(reason); // throw new WWRuntimeException(reason); } } else { String message = Logging.getMessage("TiledRasterProducer.UnrecognizedRasterType", raster.getClass().getName(), raster.getStringValue(AVKey.DATASET_NAME)); Logging.logger().severe(message); throw new WWRuntimeException(message); } } } AVList rasterServerProperties = new AVListImpl(); String[] keysToCopy = new String[]{AVKey.DATA_CACHE_NAME, AVKey.DATASET_NAME, AVKey.DISPLAY_NAME}; WWUtil.copyValues(productionParams, rasterServerProperties, keysToCopy, false); appendProperties(root, rasterServerProperties); // add sources root.appendChild(sources); WWXML.saveDocumentToFile(doc, rasterServerConfigFilePath); } protected void appendProperties(Element context, AVList properties) { if (null == context || properties == null) { return; } StringBuilder sb = new StringBuilder(); // add properties for (Map.Entry<String, Object> entry : properties.getEntries()) { sb.setLength(0); String key = entry.getKey(); sb.append(properties.getValue(key)); String value = sb.toString(); if (WWUtil.isEmpty(key) || WWUtil.isEmpty(value)) { continue; } Element property = WWXML.appendElement(context, "Property"); WWXML.setTextAttribute(property, "name", key); WWXML.setTextAttribute(property, "value", value); } } protected void appendSource(Element sources, CachedDataRaster raster) throws WWRuntimeException { Object o = raster.getDataSource(); if (WWUtil.isEmpty(o)) { String message = Logging.getMessage("nullValue.DataSourceIsNull"); Logging.logger().fine(message); throw new WWRuntimeException(message); } File f = WWIO.getFileForLocalAddress(o); if (WWUtil.isEmpty(f)) { String message = Logging.getMessage("TiledRasterProducer.UnrecognizedDataSource", o); Logging.logger().fine(message); throw new WWRuntimeException(message); } Element source = WWXML.appendElement(sources, "Source"); WWXML.setTextAttribute(source, "type", "file"); WWXML.setTextAttribute(source, "path", f.getAbsolutePath()); AVList params = raster.getParams(); if (null == params) { String message = Logging.getMessage("nullValue.ParamsIsNull"); Logging.logger().fine(message); throw new WWRuntimeException(message); } Sector sector = raster.getSector(); if (null == sector && params.hasKey(AVKey.SECTOR)) { o = params.getValue(AVKey.SECTOR); if (o instanceof Sector) { sector = (Sector) o; } } if (null != sector) { WWXML.appendSector(source, "Sector", sector); } } public boolean isDataRaster(Object source, AVList params) { if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } DataRasterReaderFactory readerFactory; try { readerFactory = (DataRasterReaderFactory) WorldWind.createConfigurationComponent( AVKey.DATA_RASTER_READER_FACTORY_CLASS_NAME); } catch (Exception e) { readerFactory = new BasicDataRasterReaderFactory(); } params = (null == params) ? new AVListImpl() : params; DataRasterReader reader = readerFactory.findReaderFor(source, params); if (reader == null) { return false; } if (!params.hasKey(AVKey.PIXEL_FORMAT)) { try { reader.readMetadata(source, params); } catch (Exception e) { String message = Logging.getMessage("generic.ExceptionWhileReading", e.getMessage()); Logging.logger().finest(message); } } return AVKey.IMAGE.equals(params.getStringValue(AVKey.PIXEL_FORMAT)) || AVKey.ELEVATION.equals(params.getStringValue(AVKey.PIXEL_FORMAT)); } public File getDefaultInstallLocation(FileStore fileStore) { if (fileStore == null) { String message = Logging.getMessage("nullValue.FileStoreIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } for (File location : fileStore.getLocations()) { if (fileStore.isInstallLocation(location.getPath())) { return location; } } return fileStore.getWriteLocation(); } public static void addToWorldWindow(WorldWindow wwd, Element domElement, AVList dataSet, boolean goTo) { String type = DataConfigurationUtils.getDataConfigType(domElement); if (type == null) return; if (type.equalsIgnoreCase("Layer")) { addLayerToWorldWindow(wwd, domElement, dataSet, goTo); } else if (type.equalsIgnoreCase("ElevationModel")) { addElevationModelToWorldWindow(wwd, domElement, dataSet, true); } } public static void addLayerToWorldWindow(WorldWindow wwd, Element domElement, AVList dataSet, boolean goTo) { Layer layer = null; try { Factory factory = (Factory) WorldWind.createConfigurationComponent(AVKey.LAYER_FACTORY); layer = (Layer) factory.createFromConfigSource(domElement, null); Sector sector = WWXML.getSector(domElement, "Sector", null); layer.setValue(AVKey.SECTOR, sector); dataSet.setValue(AVKey.DISPLAY_NAME, layer.getName()); } catch (Exception e) { String message = Logging.getMessage("generic.CreationFromConfigurationFailed", DataConfigurationUtils.getDataConfigDisplayName(domElement)); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } if (layer == null) return; layer.setEnabled(true); // BasicLayerFactory creates layer which is initially disabled Layer existingLayer = findLayer(wwd, dataSet.getStringValue(AVKey.DISPLAY_NAME)); if (existingLayer != null) wwd.getModel().getLayers().remove(existingLayer); removeLayerPreview(wwd, dataSet); ApplicationTemplate.insertBeforePlacenames(wwd, layer); final Sector sector = (Sector) layer.getValue(AVKey.SECTOR); if (goTo && sector != null && !sector.equals(Sector.FULL_SPHERE)) { ExampleUtil.goTo(wwd, sector); } } protected static void removeLayerPreview(WorldWindow wwd, AVList dataSet) { Layer layer = (Layer) dataSet.getValue(AVKey.LAYER); if (layer == null || layer.getValue(PREVIEW_LAYER) == null) return; if (! (layer instanceof RenderableLayer)) return; SurfaceImage surfaceImage = null; RenderableLayer renderableLayer = (RenderableLayer) layer; for (Renderable renderable : renderableLayer.getRenderables()) { if (renderable instanceof SurfaceImage) { surfaceImage = (SurfaceImage) renderable; break; } } if (surfaceImage != null) renderableLayer.removeRenderable(surfaceImage); // // wwd.getModel().getLayers().remove(layer); } public static void addElevationModelToWorldWindow(WorldWindow wwd, Element domElement, AVList dataSet, boolean goTo) { ElevationModel elevationModel = null; try { Factory factory = (Factory) WorldWind.createConfigurationComponent(AVKey.ELEVATION_MODEL_FACTORY); elevationModel = (ElevationModel) factory.createFromConfigSource(domElement, null); // elevationModel.setValue(AVKey.DATASET_NAME, dataSet.getStringValue(AVKey.DATASET_NAME)); dataSet.setValue(AVKey.DISPLAY_NAME, elevationModel.getName()); // TODO: set Sector as in addLayerToWorldWindow? } catch (Exception e) { String message = Logging.getMessage("generic.CreationFromConfigurationFailed", DataConfigurationUtils.getDataConfigDisplayName(domElement)); Logging.logger().log(java.util.logging.Level.SEVERE, message, e); } if (elevationModel == null) return; ElevationModel existingElevationModel = findElevationModel(wwd, dataSet.getStringValue(AVKey.DISPLAY_NAME)); if (existingElevationModel != null) removeElevationModel(wwd, existingElevationModel); ElevationModel defaultElevationModel = wwd.getModel().getGlobe().getElevationModel(); if (defaultElevationModel instanceof CompoundElevationModel) { if (!((CompoundElevationModel) defaultElevationModel).containsElevationModel(elevationModel)) { ((CompoundElevationModel) defaultElevationModel).addElevationModel(elevationModel); } } else { CompoundElevationModel cm = new CompoundElevationModel(); cm.addElevationModel(defaultElevationModel); cm.addElevationModel(elevationModel); wwd.getModel().getGlobe().setElevationModel(cm); } Sector sector = (Sector) elevationModel.getValue(AVKey.SECTOR); if (goTo && sector != null && !sector.equals(Sector.FULL_SPHERE)) { ExampleUtil.goTo(wwd, sector); } wwd.firePropertyChange(new PropertyChangeEvent(wwd, AVKey.ELEVATION_MODEL, null, elevationModel)); } public static DataRasterReaderFactory getReaderFactory() { try { return (DataRasterReaderFactory) WorldWind.createConfigurationComponent( AVKey.DATA_RASTER_READER_FACTORY_CLASS_NAME); } catch (Exception e) { return new BasicDataRasterReaderFactory(); } } public static Layer findLayer(WorldWindow wwd, String layerName) { for (Layer layer : wwd.getModel().getLayers()) { String dataSetName = layer.getStringValue(AVKey.DISPLAY_NAME); if (dataSetName != null && dataSetName.equals(layerName)) return layer; } return null; } public static ElevationModel findElevationModel(WorldWindow wwd, String elevationModelName) { ElevationModel defaultElevationModel = wwd.getModel().getGlobe().getElevationModel(); if (defaultElevationModel instanceof CompoundElevationModel) { CompoundElevationModel cm = (CompoundElevationModel) defaultElevationModel; for (ElevationModel em : cm.getElevationModels()) { String name = em.getStringValue(AVKey.DISPLAY_NAME); if (name != null && name.equals(elevationModelName)) return em; } } else { String name = defaultElevationModel.getStringValue(AVKey.DISPLAY_NAME); if (name != null && name.equals(elevationModelName)) return defaultElevationModel; } return null; } public static void removeElevationModel(WorldWindow wwd, ElevationModel elevationModel) { ElevationModel defaultElevationModel = wwd.getModel().getGlobe().getElevationModel(); if (defaultElevationModel instanceof CompoundElevationModel) { CompoundElevationModel cm = (CompoundElevationModel) defaultElevationModel; for (ElevationModel em : cm.getElevationModels()) { String name = em.getStringValue(AVKey.DISPLAY_NAME); if (name != null && name.equals(elevationModel.getName())) { cm.removeElevationModel(elevationModel); wwd.firePropertyChange(new PropertyChangeEvent(wwd, AVKey.ELEVATION_MODEL, null, elevationModel)); } } } } }
/** * 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.flume.serialization; import java.io.File; import java.io.IOException; import com.google.common.base.Preconditions; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.DataFileWriter; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.avro.specific.SpecificDatumReader; import org.apache.avro.specific.SpecificDatumWriter; import org.apache.flume.annotations.InterfaceAudience; import org.apache.flume.annotations.InterfaceStability; import org.apache.flume.tools.PlatformDetect; /** * <p/>Class that stores object state in an avro container file. * The file is only ever appended to. * At construction time, the object reads data from the end of the file and * caches that data for use by a client application. After construction, reads * never go to disk. * Writes always flush to disk. * * <p/>Note: This class is not thread-safe. */ @InterfaceAudience.Private @InterfaceStability.Evolving public class DurablePositionTracker implements PositionTracker { private final File trackerFile; private final DataFileWriter<TransferStateFileMeta> writer; private final DataFileReader<TransferStateFileMeta> reader; private final TransferStateFileMeta metaCache; private String target; private boolean isOpen; /** * If the file exists at startup, then read it, roll it, and open a new one. * We go through this to avoid issues with partial reads at the end of the * file from a previous crash. If we append to a bad record, * our writes may never be visible. * @param trackerFile * @param target * @return * @throws IOException */ public static DurablePositionTracker getInstance(File trackerFile, String target) throws IOException { if (!trackerFile.exists()) { return new DurablePositionTracker(trackerFile, target); } // exists DurablePositionTracker oldTracker = new DurablePositionTracker(trackerFile, target); String existingTarget = oldTracker.getTarget(); long targetPosition = oldTracker.getPosition(); oldTracker.close(); File tmpMeta = File.createTempFile(trackerFile.getName(), ".tmp", trackerFile.getParentFile()); tmpMeta.delete(); DurablePositionTracker tmpTracker = new DurablePositionTracker(tmpMeta, existingTarget); tmpTracker.storePosition(targetPosition); tmpTracker.close(); // On windows, things get messy with renames... // FIXME: This is not atomic. Consider implementing a recovery procedure // so that if it does not exist at startup, check for a rolled version // before creating a new file from scratch. if (PlatformDetect.isWindows()) { if (!trackerFile.delete()) { throw new IOException("Unable to delete existing meta file " + trackerFile); } } // rename tmp file to meta if (!tmpMeta.renameTo(trackerFile)) { throw new IOException("Unable to rename " + tmpMeta + " to " + trackerFile); } // return a new known-good version that is open for append DurablePositionTracker newTracker = new DurablePositionTracker(trackerFile, existingTarget); return newTracker; } /** * If the file exists, read it and open it for append. * @param trackerFile * @param target * @throws IOException */ DurablePositionTracker(File trackerFile, String target) throws IOException { Preconditions.checkNotNull(trackerFile, "trackerFile must not be null"); Preconditions.checkNotNull(target, "target must not be null"); this.trackerFile = trackerFile; this.target = target; DatumWriter<TransferStateFileMeta> dout = new SpecificDatumWriter<TransferStateFileMeta>( TransferStateFileMeta.SCHEMA$); DatumReader<TransferStateFileMeta> din = new SpecificDatumReader<TransferStateFileMeta>( TransferStateFileMeta.SCHEMA$); writer = new DataFileWriter<TransferStateFileMeta>(dout); if (trackerFile.exists()) { // open it for append writer.appendTo(trackerFile); reader = new DataFileReader<TransferStateFileMeta>(trackerFile, din); this.target = reader.getMetaString("file"); } else { // create the file this.target = target; writer.setMeta("file", target); writer.create(TransferStateFileMeta.SCHEMA$, trackerFile); reader = new DataFileReader<TransferStateFileMeta>(trackerFile, din); } target = getTarget(); // initialize @ line = 0; metaCache = TransferStateFileMeta.newBuilder().setOffset(0L).build(); initReader(); isOpen = true; } /** * Read the last record in the file. */ private void initReader() throws IOException { long syncPos = trackerFile.length() - 256L; if (syncPos < 0) syncPos = 0L; reader.sync(syncPos); while (reader.hasNext()) { reader.next(metaCache); } } @Override public synchronized void storePosition(long position) throws IOException { metaCache.setOffset(position); writer.append(metaCache); writer.sync(); writer.flush(); } @Override public synchronized long getPosition() { return metaCache.getOffset(); } @Override public String getTarget() { return target; } @Override public void close() throws IOException { if (isOpen) { writer.close(); reader.close(); isOpen = false; } } }
/* * Copyright (c) 2016-present, RxJava Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.rxjava3.internal.schedulers; import static org.junit.Assert.*; import java.lang.Thread.UncaughtExceptionHandler; import java.util.List; import java.util.concurrent.FutureTask; import java.util.concurrent.atomic.*; import org.junit.Test; import io.reactivex.rxjava3.core.RxJavaTest; import io.reactivex.rxjava3.disposables.CompositeDisposable; import io.reactivex.rxjava3.exceptions.TestException; import io.reactivex.rxjava3.internal.functions.Functions; import io.reactivex.rxjava3.plugins.RxJavaPlugins; import io.reactivex.rxjava3.testsupport.TestHelper; public class ScheduledRunnableTest extends RxJavaTest { @Test public void dispose() { CompositeDisposable set = new CompositeDisposable(); ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); set.add(run); assertFalse(run.isDisposed()); set.dispose(); assertTrue(run.isDisposed()); } @Test public void disposeRun() { CompositeDisposable set = new CompositeDisposable(); ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); set.add(run); assertFalse(run.isDisposed()); run.dispose(); run.dispose(); assertTrue(run.isDisposed()); } @Test public void setFutureCancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { CompositeDisposable set = new CompositeDisposable(); final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); set.add(run); final FutureTask<Object> ft = new FutureTask<>(Functions.EMPTY_RUNNABLE, 0); Runnable r1 = new Runnable() { @Override public void run() { run.setFuture(ft); } }; Runnable r2 = new Runnable() { @Override public void run() { run.dispose(); } }; TestHelper.race(r1, r2); assertEquals(0, set.size()); } } @Test public void setFutureRunRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { CompositeDisposable set = new CompositeDisposable(); final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); set.add(run); final FutureTask<Object> ft = new FutureTask<>(Functions.EMPTY_RUNNABLE, 0); Runnable r1 = new Runnable() { @Override public void run() { run.setFuture(ft); } }; Runnable r2 = new Runnable() { @Override public void run() { run.run(); } }; TestHelper.race(r1, r2); assertEquals(0, set.size()); } } @Test public void disposeRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { CompositeDisposable set = new CompositeDisposable(); final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); set.add(run); Runnable r1 = new Runnable() { @Override public void run() { run.dispose(); } }; TestHelper.race(r1, r1); assertEquals(0, set.size()); } } @Test public void runDispose() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { CompositeDisposable set = new CompositeDisposable(); final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); set.add(run); Runnable r1 = new Runnable() { @Override public void run() { run.call(); } }; Runnable r2 = new Runnable() { @Override public void run() { run.dispose(); } }; TestHelper.race(r1, r2); assertEquals(0, set.size()); } } @Test public void pluginCrash() { Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { throw new TestException("Second"); } }); CompositeDisposable set = new CompositeDisposable(); final ScheduledRunnable run = new ScheduledRunnable(new Runnable() { @Override public void run() { throw new TestException("First"); } }, set); set.add(run); try { run.run(); fail("Should have thrown!"); } catch (TestException ex) { assertEquals("Second", ex.getMessage()); } finally { Thread.currentThread().setUncaughtExceptionHandler(null); } assertTrue(run.isDisposed()); assertEquals(0, set.size()); } @Test public void crashReported() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { CompositeDisposable set = new CompositeDisposable(); final ScheduledRunnable run = new ScheduledRunnable(new Runnable() { @Override public void run() { throw new TestException("First"); } }, set); set.add(run); try { run.run(); fail("Should have thrown!"); } catch (TestException expected) { // expected } assertTrue(run.isDisposed()); assertEquals(0, set.size()); TestHelper.assertUndeliverable(errors, 0, TestException.class, "First"); } finally { RxJavaPlugins.reset(); } } @Test public void withoutParentDisposed() { ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null); run.dispose(); run.call(); } @Test public void withParentDisposed() { ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, new CompositeDisposable()); run.dispose(); run.call(); } @Test public void withFutureDisposed() { ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null); run.setFuture(new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null)); run.dispose(); run.call(); } @Test public void withFutureDisposed2() { ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null); run.dispose(); run.setFuture(new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null)); run.call(); } @Test public void withFutureDisposed3() { ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null); run.dispose(); run.set(2, Thread.currentThread()); run.setFuture(new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null)); run.call(); } @Test public void runFuture() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { CompositeDisposable set = new CompositeDisposable(); final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); set.add(run); final FutureTask<Void> ft = new FutureTask<>(Functions.EMPTY_RUNNABLE, null); Runnable r1 = new Runnable() { @Override public void run() { run.call(); } }; Runnable r2 = new Runnable() { @Override public void run() { run.setFuture(ft); } }; TestHelper.race(r1, r2); } } @Test public void syncWorkerCancelRace() { for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { final CompositeDisposable set = new CompositeDisposable(); final AtomicBoolean interrupted = new AtomicBoolean(); final AtomicInteger sync = new AtomicInteger(2); final AtomicInteger syncb = new AtomicInteger(2); Runnable r0 = new Runnable() { @Override public void run() { set.dispose(); if (sync.decrementAndGet() != 0) { while (sync.get() != 0) { } } if (syncb.decrementAndGet() != 0) { while (syncb.get() != 0) { } } for (int j = 0; j < 1000; j++) { if (Thread.currentThread().isInterrupted()) { interrupted.set(true); break; } } } }; final ScheduledRunnable run = new ScheduledRunnable(r0, set); set.add(run); final FutureTask<Void> ft = new FutureTask<>(run, null); Runnable r2 = new Runnable() { @Override public void run() { if (sync.decrementAndGet() != 0) { while (sync.get() != 0) { } } run.setFuture(ft); if (syncb.decrementAndGet() != 0) { while (syncb.get() != 0) { } } } }; TestHelper.race(ft, r2); assertFalse("The task was interrupted", interrupted.get()); } } @Test public void disposeAfterRun() { final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null); run.run(); assertEquals(ScheduledRunnable.DONE, run.get(ScheduledRunnable.FUTURE_INDEX)); run.dispose(); assertEquals(ScheduledRunnable.DONE, run.get(ScheduledRunnable.FUTURE_INDEX)); } @Test public void syncDisposeIdempotent() { final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null); run.set(ScheduledRunnable.THREAD_INDEX, Thread.currentThread()); run.dispose(); assertEquals(ScheduledRunnable.SYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX)); run.dispose(); assertEquals(ScheduledRunnable.SYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX)); run.run(); assertEquals(ScheduledRunnable.SYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX)); } @Test public void asyncDisposeIdempotent() { final ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null); run.dispose(); assertEquals(ScheduledRunnable.ASYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX)); run.dispose(); assertEquals(ScheduledRunnable.ASYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX)); run.run(); assertEquals(ScheduledRunnable.ASYNC_DISPOSED, run.get(ScheduledRunnable.FUTURE_INDEX)); } @Test public void noParentIsDisposed() { ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, null); assertFalse(run.isDisposed()); run.run(); assertTrue(run.isDisposed()); } @Test public void withParentIsDisposed() { CompositeDisposable set = new CompositeDisposable(); ScheduledRunnable run = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); set.add(run); assertFalse(run.isDisposed()); run.run(); assertTrue(run.isDisposed()); assertFalse(set.remove(run)); } @Test public void toStringStates() { CompositeDisposable set = new CompositeDisposable(); ScheduledRunnable task = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); assertEquals("ScheduledRunnable[Waiting]", task.toString()); task.set(ScheduledRunnable.THREAD_INDEX, Thread.currentThread()); assertEquals("ScheduledRunnable[Running on " + Thread.currentThread() + "]", task.toString()); task.dispose(); assertEquals("ScheduledRunnable[Disposed(Sync)]", task.toString()); task.set(ScheduledRunnable.FUTURE_INDEX, ScheduledRunnable.DONE); assertEquals("ScheduledRunnable[Finished]", task.toString()); task = new ScheduledRunnable(Functions.EMPTY_RUNNABLE, set); task.dispose(); assertEquals("ScheduledRunnable[Disposed(Async)]", task.toString()); } }
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.ext.leanback; import android.content.Context; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v17.leanback.R; import android.support.v17.leanback.media.PlaybackGlueHost; import android.support.v17.leanback.media.PlayerAdapter; import android.support.v17.leanback.media.SurfaceHolderGlueHost; import android.util.Pair; import android.view.Surface; import android.view.SurfaceHolder; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.ControlDispatcher; import com.google.android.exoplayer2.DefaultControlDispatcher; import com.google.android.exoplayer2.ExoPlaybackException; import com.google.android.exoplayer2.ExoPlayerLibraryInfo; import com.google.android.exoplayer2.PlaybackPreparer; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.Player.DiscontinuityReason; import com.google.android.exoplayer2.Player.TimelineChangeReason; import com.google.android.exoplayer2.Timeline; import com.google.android.exoplayer2.util.ErrorMessageProvider; import com.google.android.exoplayer2.video.VideoListener; /** Leanback {@code PlayerAdapter} implementation for {@link Player}. */ public final class LeanbackPlayerAdapter extends PlayerAdapter { static { ExoPlayerLibraryInfo.registerModule("goog.exo.leanback"); } private final Context context; private final Player player; private final Handler handler; private final ComponentListener componentListener; private final Runnable updateProgressRunnable; private @Nullable PlaybackPreparer playbackPreparer; private ControlDispatcher controlDispatcher; private @Nullable ErrorMessageProvider<? super ExoPlaybackException> errorMessageProvider; private SurfaceHolderGlueHost surfaceHolderGlueHost; private boolean hasSurface; private boolean lastNotifiedPreparedState; /** * Builds an instance. Note that the {@code PlayerAdapter} does not manage the lifecycle of the * {@link Player} instance. The caller remains responsible for releasing the player when it's no * longer required. * * @param context The current context (activity). * @param player Instance of your exoplayer that needs to be configured. * @param updatePeriodMs The delay between player control updates, in milliseconds. */ public LeanbackPlayerAdapter(Context context, Player player, final int updatePeriodMs) { this.context = context; this.player = player; handler = new Handler(); componentListener = new ComponentListener(); controlDispatcher = new DefaultControlDispatcher(); updateProgressRunnable = new Runnable() { @Override public void run() { Callback callback = getCallback(); callback.onCurrentPositionChanged(LeanbackPlayerAdapter.this); callback.onBufferedPositionChanged(LeanbackPlayerAdapter.this); handler.postDelayed(this, updatePeriodMs); } }; } /** * Sets the {@link PlaybackPreparer}. * * @param playbackPreparer The {@link PlaybackPreparer}. */ public void setPlaybackPreparer(@Nullable PlaybackPreparer playbackPreparer) { this.playbackPreparer = playbackPreparer; } /** * Sets the {@link ControlDispatcher}. * * @param controlDispatcher The {@link ControlDispatcher}, or null to use * {@link DefaultControlDispatcher}. */ public void setControlDispatcher(@Nullable ControlDispatcher controlDispatcher) { this.controlDispatcher = controlDispatcher == null ? new DefaultControlDispatcher() : controlDispatcher; } /** * Sets the optional {@link ErrorMessageProvider}. * * @param errorMessageProvider The {@link ErrorMessageProvider}. */ public void setErrorMessageProvider( @Nullable ErrorMessageProvider<? super ExoPlaybackException> errorMessageProvider) { this.errorMessageProvider = errorMessageProvider; } // PlayerAdapter implementation. @Override public void onAttachedToHost(PlaybackGlueHost host) { if (host instanceof SurfaceHolderGlueHost) { surfaceHolderGlueHost = ((SurfaceHolderGlueHost) host); surfaceHolderGlueHost.setSurfaceHolderCallback(componentListener); } notifyStateChanged(); player.addListener(componentListener); Player.VideoComponent videoComponent = player.getVideoComponent(); if (videoComponent != null) { videoComponent.addVideoListener(componentListener); } } @Override public void onDetachedFromHost() { player.removeListener(componentListener); Player.VideoComponent videoComponent = player.getVideoComponent(); if (videoComponent != null) { videoComponent.removeVideoListener(componentListener); } if (surfaceHolderGlueHost != null) { surfaceHolderGlueHost.setSurfaceHolderCallback(null); surfaceHolderGlueHost = null; } hasSurface = false; Callback callback = getCallback(); callback.onBufferingStateChanged(this, false); callback.onPlayStateChanged(this); maybeNotifyPreparedStateChanged(callback); } @Override public void setProgressUpdatingEnabled(boolean enabled) { handler.removeCallbacks(updateProgressRunnable); if (enabled) { handler.post(updateProgressRunnable); } } @Override public boolean isPlaying() { int playbackState = player.getPlaybackState(); return playbackState != Player.STATE_IDLE && playbackState != Player.STATE_ENDED && player.getPlayWhenReady(); } @Override public long getDuration() { long durationMs = player.getDuration(); return durationMs == C.TIME_UNSET ? -1 : durationMs; } @Override public long getCurrentPosition() { return player.getPlaybackState() == Player.STATE_IDLE ? -1 : player.getCurrentPosition(); } @Override public void play() { if (player.getPlaybackState() == Player.STATE_IDLE) { if (playbackPreparer != null) { playbackPreparer.preparePlayback(); } } else if (player.getPlaybackState() == Player.STATE_ENDED) { controlDispatcher.dispatchSeekTo(player, player.getCurrentWindowIndex(), C.TIME_UNSET); } if (controlDispatcher.dispatchSetPlayWhenReady(player, true)) { getCallback().onPlayStateChanged(this); } } @Override public void pause() { if (controlDispatcher.dispatchSetPlayWhenReady(player, false)) { getCallback().onPlayStateChanged(this); } } @Override public void seekTo(long positionMs) { controlDispatcher.dispatchSeekTo(player, player.getCurrentWindowIndex(), positionMs); } @Override public long getBufferedPosition() { return player.getBufferedPosition(); } @Override public boolean isPrepared() { return player.getPlaybackState() != Player.STATE_IDLE && (surfaceHolderGlueHost == null || hasSurface); } // Internal methods. /* package */ void setVideoSurface(Surface surface) { hasSurface = surface != null; Player.VideoComponent videoComponent = player.getVideoComponent(); if (videoComponent != null) { videoComponent.setVideoSurface(surface); } maybeNotifyPreparedStateChanged(getCallback()); } /* package */ void notifyStateChanged() { int playbackState = player.getPlaybackState(); Callback callback = getCallback(); maybeNotifyPreparedStateChanged(callback); callback.onPlayStateChanged(this); callback.onBufferingStateChanged(this, playbackState == Player.STATE_BUFFERING); if (playbackState == Player.STATE_ENDED) { callback.onPlayCompleted(this); } } private void maybeNotifyPreparedStateChanged(Callback callback) { boolean isPrepared = isPrepared(); if (lastNotifiedPreparedState != isPrepared) { lastNotifiedPreparedState = isPrepared; callback.onPreparedStateChanged(this); } } private final class ComponentListener extends Player.DefaultEventListener implements SurfaceHolder.Callback, VideoListener { // SurfaceHolder.Callback implementation. @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { setVideoSurface(surfaceHolder.getSurface()); } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) { // Do nothing. } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { setVideoSurface(null); } // Player.EventListener implementation. @Override public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { notifyStateChanged(); } @Override public void onPlayerError(ExoPlaybackException exception) { Callback callback = getCallback(); if (errorMessageProvider != null) { Pair<Integer, String> errorMessage = errorMessageProvider.getErrorMessage(exception); callback.onError(LeanbackPlayerAdapter.this, errorMessage.first, errorMessage.second); } else { callback.onError(LeanbackPlayerAdapter.this, exception.type, context.getString( R.string.lb_media_player_error, exception.type, exception.rendererIndex)); } } @Override public void onTimelineChanged(Timeline timeline, Object manifest, @TimelineChangeReason int reason) { Callback callback = getCallback(); callback.onDurationChanged(LeanbackPlayerAdapter.this); callback.onCurrentPositionChanged(LeanbackPlayerAdapter.this); callback.onBufferedPositionChanged(LeanbackPlayerAdapter.this); } @Override public void onPositionDiscontinuity(@DiscontinuityReason int reason) { Callback callback = getCallback(); callback.onCurrentPositionChanged(LeanbackPlayerAdapter.this); callback.onBufferedPositionChanged(LeanbackPlayerAdapter.this); } // VideoListener implementation. @Override public void onVideoSizeChanged( int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) { getCallback().onVideoSizeChanged(LeanbackPlayerAdapter.this, width, height); } @Override public void onRenderedFirstFrame() { // Do nothing. } } }
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.database; import android.database.sqlite.SQLiteClosable; import android.database.sqlite.SQLiteException; import android.os.Parcel; import kotlin.NotImplementedError; import xyz.nulldev.androidcompat.db.ScrollableResultSet; import java.sql.SQLException; /** * A buffer containing multiple cursor rows. * <p> * A {@link CursorWindow} is read-write when initially created and used locally. * When sent to a remote process (by writing it to a {@link Parcel}), the remote process * receives a read-only view of the cursor window. Typically the cursor window * will be allocated by the producer, filled with data, and then sent to the * consumer for reading. * </p> */ public class CursorWindow extends SQLiteClosable { private ScrollableResultSet resultSet; public CursorWindow(ScrollableResultSet resultSet) { this.resultSet = resultSet; } /** * Clears out the existing contents of the window, making it safe to reuse * for new data. * <p> * The start position ({@link #getStartPosition()}), number of rows ({@link #getNumRows()}), * and number of columns in the cursor are all reset to zero. * </p> */ public void clear() { } /** * Gets the start position of this cursor window. * <p> * The start position is the zero-based index of the first row that this window contains * relative to the entire result set of the {@link Cursor}. * </p> * * @return The zero-based start position. */ public int getStartPosition() { return 0; } /** * Sets the start position of this cursor window. * <p> * The start position is the zero-based index of the first row that this window contains * relative to the entire result set of the {@link Cursor}. * </p> * * @param pos The new zero-based start position. */ public void setStartPosition(int pos) { } /** * Gets the number of rows in this window. * * @return The number of rows in this cursor window. */ public int getNumRows() { return resultSet.getResultSetLength(); } /** * Sets the number of columns in this window. * <p> * This method must be called before any rows are added to the window, otherwise * it will fail to set the number of columns if it differs from the current number * of columns. * </p> * * @param columnNum The new number of columns. * @return True if successful. */ public boolean setNumColumns(int columnNum) { return true; } /** * Allocates a new row at the end of this cursor window. * * @return True if successful, false if the cursor window is out of memory. */ public boolean allocRow() { return true; } /** * Frees the last row in this cursor window. */ public void freeLastRow(){ } /** * Returns true if the field at the specified row and column index * has type {@link Cursor#FIELD_TYPE_NULL}. * * @param row The zero-based row index. * @param column The zero-based column index. * @return True if the field has type {@link Cursor#FIELD_TYPE_NULL}. * @deprecated Use {@link #getType(int, int)} instead. */ @Deprecated public boolean isNull(int row, int column) { return getType(row, column) == Cursor.FIELD_TYPE_NULL; } /** * Returns true if the field at the specified row and column index * has type {@link Cursor#FIELD_TYPE_BLOB} or {@link Cursor#FIELD_TYPE_NULL}. * * @param row The zero-based row index. * @param column The zero-based column index. * @return True if the field has type {@link Cursor#FIELD_TYPE_BLOB} or * {@link Cursor#FIELD_TYPE_NULL}. * @deprecated Use {@link #getType(int, int)} instead. */ @Deprecated public boolean isBlob(int row, int column) { int type = getType(row, column); return type == Cursor.FIELD_TYPE_BLOB || type == Cursor.FIELD_TYPE_NULL; } /** * Returns true if the field at the specified row and column index * has type {@link Cursor#FIELD_TYPE_INTEGER}. * * @param row The zero-based row index. * @param column The zero-based column index. * @return True if the field has type {@link Cursor#FIELD_TYPE_INTEGER}. * @deprecated Use {@link #getType(int, int)} instead. */ @Deprecated public boolean isLong(int row, int column) { return getType(row, column) == Cursor.FIELD_TYPE_INTEGER; } /** * Returns true if the field at the specified row and column index * has type {@link Cursor#FIELD_TYPE_FLOAT}. * * @param row The zero-based row index. * @param column The zero-based column index. * @return True if the field has type {@link Cursor#FIELD_TYPE_FLOAT}. * @deprecated Use {@link #getType(int, int)} instead. */ @Deprecated public boolean isFloat(int row, int column) { return getType(row, column) == Cursor.FIELD_TYPE_FLOAT; } /** * Returns true if the field at the specified row and column index * has type {@link Cursor#FIELD_TYPE_STRING} or {@link Cursor#FIELD_TYPE_NULL}. * * @param row The zero-based row index. * @param column The zero-based column index. * @return True if the field has type {@link Cursor#FIELD_TYPE_STRING} * or {@link Cursor#FIELD_TYPE_NULL}. * @deprecated Use {@link #getType(int, int)} instead. */ @Deprecated public boolean isString(int row, int column) { int type = getType(row, column); return type == Cursor.FIELD_TYPE_STRING || type == Cursor.FIELD_TYPE_NULL; } /** * Returns the type of the field at the specified row and column index. * <p> * The returned field types are: * <ul> * <li>{@link Cursor#FIELD_TYPE_NULL}</li> * <li>{@link Cursor#FIELD_TYPE_INTEGER}</li> * <li>{@link Cursor#FIELD_TYPE_FLOAT}</li> * <li>{@link Cursor#FIELD_TYPE_STRING}</li> * <li>{@link Cursor#FIELD_TYPE_BLOB}</li> * </ul> * </p> * * @param row The zero-based row index. * @param column The zero-based column index. * @return The field type. */ public int getType(int row, int column) { acquireReference(); try { jumpToRow(row); String clazz = resultSet.getMetaData().getColumnClassName(column + 1); resultSet.getObject(column + 1); if(resultSet.wasNull()) return Cursor.FIELD_TYPE_NULL; if(clazz.equals(String.class.getName())) return Cursor.FIELD_TYPE_STRING; else if(clazz.equals(Integer.class.getName()) || clazz.equals(Long.class.getName()) || clazz.equals(Short.class.getName()) || clazz.equals(Byte.class.getName()) || clazz.equals(Boolean.class.getName())) return Cursor.FIELD_TYPE_INTEGER; else if(clazz.equals(Double.class.getName()) || clazz.equals(Float.class.getName())) return Cursor.FIELD_TYPE_FLOAT; else throw new SQLiteException("Unknown field type: " + clazz); } catch (SQLException e) { throw new SQLiteException("Failed to get type of field at: (" + row + ", " + column + ")!", e); } finally { releaseReference(); } } /** * Gets the value of the field at the specified row and column index as a byte array. * <p> * The result is determined as follows: * <ul> * <li>If the field is of type {@link Cursor#FIELD_TYPE_NULL}, then the result * is <code>null</code>.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_BLOB}, then the result * is the blob value.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_STRING}, then the result * is the array of bytes that make up the internal representation of the * string value.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_INTEGER} or * {@link Cursor#FIELD_TYPE_FLOAT}, then a {@link SQLiteException} is thrown.</li> * </ul> * </p> * * @param row The zero-based row index. * @param column The zero-based column index. * @return The value of the field as a byte array. */ public byte[] getBlob(int row, int column) { throw new NotImplementedError("Not implemented!"); } /** * Gets the value of the field at the specified row and column index as a string. * <p> * The result is determined as follows: * <ul> * <li>If the field is of type {@link Cursor#FIELD_TYPE_NULL}, then the result * is <code>null</code>.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_STRING}, then the result * is the string value.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_INTEGER}, then the result * is a string representation of the integer in decimal, obtained by formatting the * value with the <code>printf</code> family of functions using * format specifier <code>%lld</code>.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_FLOAT}, then the result * is a string representation of the floating-point value in decimal, obtained by * formatting the value with the <code>printf</code> family of functions using * format specifier <code>%g</code>.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_BLOB}, then a * {@link SQLiteException} is thrown.</li> * </ul> * </p> * * @param row The zero-based row index. * @param column The zero-based column index. * @return The value of the field as a string. */ public String getString(int row, int column) { acquireReference(); try { jumpToRow(row); return resultSet.getString(column + 1); } finally { releaseReference(); } } /** * Copies the text of the field at the specified row and column index into * a {@link CharArrayBuffer}. * <p> * The buffer is populated as follows: * <ul> * <li>If the buffer is too small for the value to be copied, then it is * automatically resized.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_NULL}, then the buffer * is set to an empty string.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_STRING}, then the buffer * is set to the contents of the string.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_INTEGER}, then the buffer * is set to a string representation of the integer in decimal, obtained by formatting the * value with the <code>printf</code> family of functions using * format specifier <code>%lld</code>.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_FLOAT}, then the buffer is * set to a string representation of the floating-point value in decimal, obtained by * formatting the value with the <code>printf</code> family of functions using * format specifier <code>%g</code>.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_BLOB}, then a * {@link SQLiteException} is thrown.</li> * </ul> * </p> * * @param row The zero-based row index. * @param column The zero-based column index. * @param buffer The {@link CharArrayBuffer} to hold the string. It is automatically * resized if the requested string is larger than the buffer's current capacity. */ public void copyStringToBuffer(int row, int column, CharArrayBuffer buffer) { if (buffer == null) { throw new IllegalArgumentException("CharArrayBuffer should not be null"); } acquireReference(); try { jumpToRow(row); buffer.data = resultSet.getString(column + 1).toCharArray(); } finally { releaseReference(); } } /** * Gets the value of the field at the specified row and column index as a <code>long</code>. * <p> * The result is determined as follows: * <ul> * <li>If the field is of type {@link Cursor#FIELD_TYPE_NULL}, then the result * is <code>0L</code>.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_STRING}, then the result * is the value obtained by parsing the string value with <code>strtoll</code>. * <li>If the field is of type {@link Cursor#FIELD_TYPE_INTEGER}, then the result * is the <code>long</code> value.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_FLOAT}, then the result * is the floating-point value converted to a <code>long</code>.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_BLOB}, then a * {@link SQLiteException} is thrown.</li> * </ul> * </p> * * @param row The zero-based row index. * @param column The zero-based column index. * @return The value of the field as a <code>long</code>. */ public long getLong(int row, int column) { acquireReference(); try { jumpToRow(row); return resultSet.getLong(column + 1); } finally { releaseReference(); } } /** * Gets the value of the field at the specified row and column index as a * <code>double</code>. * <p> * The result is determined as follows: * <ul> * <li>If the field is of type {@link Cursor#FIELD_TYPE_NULL}, then the result * is <code>0.0</code>.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_STRING}, then the result * is the value obtained by parsing the string value with <code>strtod</code>. * <li>If the field is of type {@link Cursor#FIELD_TYPE_INTEGER}, then the result * is the integer value converted to a <code>double</code>.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_FLOAT}, then the result * is the <code>double</code> value.</li> * <li>If the field is of type {@link Cursor#FIELD_TYPE_BLOB}, then a * {@link SQLiteException} is thrown.</li> * </ul> * </p> * * @param row The zero-based row index. * @param column The zero-based column index. * @return The value of the field as a <code>double</code>. */ public double getDouble(int row, int column) { acquireReference(); try { jumpToRow(row); return resultSet.getDouble(column + 1); } finally { releaseReference(); } } /** * Gets the value of the field at the specified row and column index as a * <code>short</code>. * <p> * The result is determined by invoking {@link #getLong} and converting the * result to <code>short</code>. * </p> * * @param row The zero-based row index. * @param column The zero-based column index. * @return The value of the field as a <code>short</code>. */ public short getShort(int row, int column) { return (short) getLong(row, column); } /** * Gets the value of the field at the specified row and column index as an * <code>int</code>. * <p> * The result is determined by invoking {@link #getLong} and converting the * result to <code>int</code>. * </p> * * @param row The zero-based row index. * @param column The zero-based column index. * @return The value of the field as an <code>int</code>. */ public int getInt(int row, int column) { return (int) getLong(row, column); } /** * Gets the value of the field at the specified row and column index as a * <code>float</code>. * <p> * The result is determined by invoking {@link #getDouble} and converting the * result to <code>float</code>. * </p> * * @param row The zero-based row index. * @param column The zero-based column index. * @return The value of the field as an <code>float</code>. */ public float getFloat(int row, int column) { return (float) getDouble(row, column); } /** * Copies a byte array into the field at the specified row and column index. * * @param value The value to store. * @param row The zero-based row index. * @param column The zero-based column index. * @return True if successful. */ public boolean putBlob(byte[] value, int row, int column) { return true; } /** * Copies a string into the field at the specified row and column index. * * @param value The value to store. * @param row The zero-based row index. * @param column The zero-based column index. * @return True if successful. */ public boolean putString(String value, int row, int column) { return true; } /** * Puts a long integer into the field at the specified row and column index. * * @param value The value to store. * @param row The zero-based row index. * @param column The zero-based column index. * @return True if successful. */ public boolean putLong(long value, int row, int column) { return true; } /** * Puts a double-precision floating point value into the field at the * specified row and column index. * * @param value The value to store. * @param row The zero-based row index. * @param column The zero-based column index. * @return True if successful. */ public boolean putDouble(double value, int row, int column) { return true; } /** * Puts a null value into the field at the specified row and column index. * * @param row The zero-based row index. * @param column The zero-based column index. * @return True if successful. */ public boolean putNull(int row, int column) { return true; } @Override protected void onAllReferencesReleased() { } private void jumpToRow(int row) { // TODO Optimize resultSet.first(); for(int i = 0; i < row; i++) { resultSet.next(); } } }
package com.tmtravlr.potioncore; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.attributes.IAttribute; import net.minecraft.entity.ai.attributes.RangedAttribute; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraftforge.fml.common.registry.GameData; import com.tmtravlr.potioncore.effects.*; import com.tmtravlr.potioncore.potion.ItemPotionCorePotion; public class PotionCoreHelper { //Lists used in tick updates public static ArrayList<EntityLivingBase> cureEntities = new ArrayList<EntityLivingBase>(); public static ArrayList<EntityLivingBase> dispelEntities = new ArrayList<EntityLivingBase>(); public static ArrayList<EntityLivingBase> blessEntities = new ArrayList<EntityLivingBase>(); public static ArrayList<EntityLivingBase> curseEntities = new ArrayList<EntityLivingBase>(); public static ArrayList<EntityLivingBase> invertEntities = new ArrayList<EntityLivingBase>(); public static ArrayList<Potion> goodEffectList = new ArrayList<Potion>(); public static ArrayList<Potion> badEffectList = new ArrayList<Potion>(); public static HashMap<Potion, Potion> oppositeEffects = new HashMap<Potion, Potion>(); public static final IAttribute projectileDamage = new RangedAttribute((IAttribute)null, "generic.projectileDamage", 1.0D, 0.0D, 2048.0D); //Loads the opposite effects for the inversion potion public static void loadInversions() { loadInversion(Potion.blindness, Potion.nightVision); loadInversion(Potion.damageBoost, Potion.weakness); loadInversion(Potion.digSpeed, Potion.digSlowdown); loadInversion(Potion.fireResistance, PotionFire.instance); loadInversion(Potion.harm, Potion.heal); loadInversion(Potion.hunger, Potion.saturation); loadInversion(Potion.jump, PotionWeight.instance); loadInversion(Potion.moveSlowdown, Potion.moveSpeed); loadInversion(Potion.poison, PotionAntidote.instance); loadInversion(Potion.regeneration, Potion.wither); loadInversion(Potion.resistance, PotionVulnerable.instance); loadInversion(Potion.waterBreathing, PotionDrown.instance); loadInversion(PotionArchery.instance, PotionKlutz.instance); loadInversion(PotionBless.instance, PotionCurse.instance); loadInversion(PotionCure.instance, PotionDispel.instance); loadInversion(PotionLevitate.instance, PotionSlowfall.instance); loadInversion(PotionRepair.instance, PotionRust.instance); } public static void loadInversion(Potion potion1, Potion potion2) { if(potion1 != null && potion2 != null) { oppositeEffects.put(potion1, potion2); oppositeEffects.put(potion2, potion1); } } /** * Clears all positive effects from the entity */ public static void clearPositiveEffects(EntityLivingBase entity) { Collection<PotionEffect> effects = entity.getActivePotionEffects(); ArrayList<Integer> idsToRemove = new ArrayList<Integer>(); Iterator<PotionEffect> it = effects.iterator(); while(it.hasNext()) { PotionEffect effect = it.next(); if(!Potion.potionTypes[effect.getPotionID()].isBadEffect()) { idsToRemove.add(effect.getPotionID()); } } for(int id : idsToRemove) { entity.removePotionEffect(id); } } /** * Clears all negative effects from the entity */ public static void clearNegativeEffects(EntityLivingBase entity) { Collection<PotionEffect> effects = entity.getActivePotionEffects(); ArrayList<Integer> idsToRemove = new ArrayList<Integer>(); Iterator<PotionEffect> it = effects.iterator(); while(it.hasNext()) { PotionEffect effect = it.next(); if(Potion.potionTypes[effect.getPotionID()].isBadEffect()) { idsToRemove.add(effect.getPotionID()); } } for(int id : idsToRemove) { entity.removePotionEffect(id); } } /** * Adds a random positive effect to the entity */ public static void addPotionEffectPositive(EntityLivingBase entity) { int r = entity.getRNG().nextInt(PotionCoreHelper.goodEffectList.size()); Potion potion = PotionCoreHelper.goodEffectList.get(r); if(potion.isInstant()) { entity.addPotionEffect(new PotionEffect(potion.getId(), 1)); } else { entity.addPotionEffect(new PotionEffect(potion.getId(), 1200)); } } /** * Adds a random negative effect to the entity */ public static void addPotionEffectNegative(EntityLivingBase entity) { int r = entity.getRNG().nextInt(PotionCoreHelper.badEffectList.size()); Potion potion = PotionCoreHelper.badEffectList.get(r); if(potion.isInstant()) { entity.addPotionEffect(new PotionEffect(potion.getId(), 1)); } else { entity.addPotionEffect(new PotionEffect(potion.getId(), 1200)); } } /** * Inverts the potion effects on the entity based on the map above */ public static void invertPotionEffects(EntityLivingBase entity) { PotionEffect[] effects = new PotionEffect[0]; effects = entity.getActivePotionEffects().toArray(effects); for(int i = 0; i < effects.length; i++) { PotionEffect effect = effects[i]; if(effect != null && Potion.potionTypes[effect.getPotionID()] != null && oppositeEffects.containsKey(Potion.potionTypes[effect.getPotionID()])) { Potion potion = oppositeEffects.get(Potion.potionTypes[effect.getPotionID()]); int duration = effect.getDuration(); if(potion.isInstant()) { duration = 1; } entity.removePotionEffect(effect.getPotionID()); entity.addPotionEffect(new PotionEffect(potion.getId(), duration, effect.getAmplifier(), effect.getIsAmbient(), effect.getIsShowParticles())); } } } /** * Turns this potion into an {@link ItemStack} that will have it's effect. * @param potion Potion to use * @param duration Duration of the potion * @param amplifier Amplifier of the potion * @param splash Should this be a splash potion? * @return The {@link ItemStack} which has this effect */ public static ItemStack getItemStack(Potion potion, int duration, int amplifier, boolean splash) { ItemStack toAdd; NBTTagCompound tag; tag = new NBTTagCompound(); tag.setTag("CustomPotionEffects", new NBTTagList()); tag.getTagList("CustomPotionEffects", 0).appendTag(writePotionToTag(potion, duration, amplifier)); toAdd = new ItemStack(ItemPotionCorePotion.instance); if(splash) { toAdd.setItemDamage(ItemPotionCorePotion.SPLASH_META); } toAdd.setTagCompound(tag); return toAdd; } /** * Returns an {@link NBTTagCompound} for an ItemStack for an {@link ItemPotionCorePotion} * @param potion Potion to use * @param duration Duration of the potion * @param amplifier Amplifier of the potion * @return Tag with this effect */ public static NBTTagCompound writePotionToTag(Potion potion, int duration, int amplifier) { NBTTagCompound tag = new NBTTagCompound(); tag.setString("Id", GameData.getPotionRegistry().getNameForObject(potion).toString()); tag.setInteger("Amplifier", amplifier); tag.setInteger("Duration", duration); return tag; } /** * Reads a custom potion effect from a potion item's NBT data, with support * for the new resource locations as the Id. */ public static PotionEffect readPotionEffectFromTag(NBTTagCompound tag) { int id = 0; if(tag.hasKey("Id", 8)) { String idString = tag.getString("Id"); Potion potion = Potion.getPotionFromResourceLocation(idString); if(potion != null) { id = potion.getId(); } else { return null; } } else { id = tag.getByte("Id") & 0xff; } if (id >= 0 && id < Potion.potionTypes.length && Potion.potionTypes[id] != null) { int j = tag.getByte("Amplifier"); int k = tag.getInteger("Duration"); boolean flag = tag.getBoolean("Ambient"); boolean flag1 = true; if (tag.hasKey("ShowParticles", 1)) { flag1 = tag.getBoolean("ShowParticles"); } return new PotionEffect(id, k, j, flag, flag1); } else { return null; } } /** * Given a {@link Collection}<{@link PotionEffect}> will return an Integer color. */ public static int getCustomPotionColor(Collection<PotionEffect> list) { int i = 3694022; if (list != null && !list.isEmpty()) { float red = -1.0F; float green = -1.0F; float blue = -1.0F; float count = 0; Iterator<PotionEffect> iterator = list.iterator(); while (iterator.hasNext()) { PotionEffect potioneffect = iterator.next(); int currentPotionColor = Potion.potionTypes[potioneffect.getPotionID()].getLiquidColor(); float currentRed = (float)(currentPotionColor >> 16 & 255) / 255.0F; float currentGreen = (float)(currentPotionColor >> 8 & 255) / 255.0F; float currentBlue = (float)(currentPotionColor >> 0 & 255) / 255.0F; for(int k = 0; k < potioneffect.getAmplifier()+1; ++k) { if(red < 0) { red = currentRed; green = currentGreen; blue = currentBlue; } else { red += currentRed; green += currentGreen; blue += currentBlue; } count++; } } red = red / count * 255.0F; green = green / count * 255.0F; blue = blue / count * 255.0F; return (int)red << 16 | (int)green << 8 | (int)blue; } else { return i; } } }
package eu.scasefp7.eclipse.servicecomposition.views; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.zest.layouts.algorithms.AbstractLayoutAlgorithm; import org.eclipse.zest.layouts.dataStructures.InternalNode; import org.eclipse.zest.layouts.dataStructures.InternalRelationship; public class MyCustomLayout extends AbstractLayoutAlgorithm { /** * horizontal spacing */ private double horSpacing = 40 * 4; /** * vertical spacing */ private double verSpacing = 60; public MyCustomLayout(int styles) { super(styles); } protected void applyLayoutInternal(InternalNode[] entitiesToLayout, InternalRelationship[] relationshipsToConsider, double boundsX, double boundsY, double boundsWidth, double boundsHeight) { List<InternalNode> entitiesList = asList(entitiesToLayout); List<InternalRelationship> relationshipsList = asList(relationshipsToConsider); // --- build the node matrix without laying out first ---// List<List<GXMoreThanNode>> rows = buildNodeMatrix(entitiesList, relationshipsList); // --- layout the nodes --- // // we're going to put them together bottom - up. Collections.reverse(rows); // the vertical size of a node line int verticalLineSize = (int) (entitiesToLayout[0].getLayoutEntity().getHeightInLayout() + verSpacing); // the vertical location we begin placing the nodes from int heightSoFar = (int) (((rows.size() - 1) * verticalLineSize) + verSpacing); // place bottom most row first - just center it. List<GXMoreThanNode> childRow = rows.get(0); int nodeSpacing = (int) (horSpacing + childRow.get(0).getNode().getLayoutEntity().getWidthInLayout()); int x = (int) ((boundsWidth / 2) - ((childRow.size() / 2) * nodeSpacing)); placeStrand(childRow, x, heightSoFar, nodeSpacing); // place parent rows List<GXMoreThanNode> parentRow; // run through all parent rows for (int i = 1; i < rows.size(); i++) { // initialize stuff we'll need parentRow = rows.get(i); heightSoFar -= verticalLineSize; placeRow(parentRow, heightSoFar); } } /** * Lays out row with respect to it's children. * * @param yLocation * - the vertical location to start placing the nodes. * @param row * - the row who's nodes we'd like to lay out. */ private void placeRow(List<GXMoreThanNode> row, int yLocation) { List<GXMoreThanNode> childlessStrand = new ArrayList<GXMoreThanNode>(); GXMoreThanNode parentLeft = null; // for each parent in this parent row for (int j = 0; j < row.size(); j++) { GXMoreThanNode parentRight = row.get(j); // if the node has children if (!parentRight.getChildren().isEmpty()) { // place the node in the center above his children int parentX = 0; for (GXMoreThanNode child : parentRight.getChildren()) { parentX += child.getX(); } parentX /= parentRight.getChildren().size(); parentRight.setLocation(parentX, yLocation); // and layout the childless strand if (!childlessStrand.isEmpty()) { placeChildless(childlessStrand, parentLeft, parentRight, yLocation); childlessStrand.clear(); } parentLeft = parentRight; } else { // accumulate the childless nodes childlessStrand.add(parentRight); } } // place childless who are extra on the right. as in did not get taken // care of when // the parents were laid out. if (!childlessStrand.isEmpty()) { placeChildless(childlessStrand, parentLeft, null, yLocation); } } /** * Builds the matrix of nodes. each node will be wrapped with necessary * innformation such as who are the direct children and parent (only * visually in the graph not the actual relationships) the returned matrix * is organized more or less as the real tree. * * @param entitiesList * - entities to place in the matrix * @param relationshipsList * - the relationships between the entities given * * @return the matrix - (a list of rows of nodes) */ private List<List<GXMoreThanNode>> buildNodeMatrix(List<InternalNode> entitiesList, List<InternalRelationship> relationshipsList) { List<List<GXMoreThanNode>> rows = new ArrayList<List<GXMoreThanNode>>(); while (!entitiesList.isEmpty()) { InternalNode root = getFirstEntity(entitiesList, relationshipsList); // add root row if necessary if (rows.isEmpty()) { rows.add(new ArrayList<GXMoreThanNode>()); rows.add(new ArrayList<GXMoreThanNode>()); } // lay out the current root node and remove it from the list of // entities left entitiesList.remove(root); GXMoreThanNode moreThanRoot = new GXMoreThanNode(root, null); rows.get(0).add(moreThanRoot); // build the tree that spreads from this current root. builtTreeFromRoot(moreThanRoot, entitiesList, relationshipsList, rows.get(1), rows); } trimEmptyRows(rows); return rows; } /** * Remove rows that are empty. This should only be the last row but since * it's not too expensive better safe than sorry. * * @param rows * - to trim */ private void trimEmptyRows(List<List<GXMoreThanNode>> rows) { List<List<GXMoreThanNode>> rowsCopy = new ArrayList<List<GXMoreThanNode>>(rows); for (List<GXMoreThanNode> row : rowsCopy) { if (row.isEmpty()) { rows.remove(row); } } } /** * A childless stran is a "problem" in general because they break the * evenness of the tree There are three types of such strands, extra nodes * to the left, extra to the right, or extra in between parents. This method * places those strands in spot. * * @param childlessStrand * - the childless node to be laid out. * @param parentLeft * - the nearest parent on the left (or <value>null</value> if * none such exists) * @param parentRight * - the nearest parent on the right (or <value>null</value> if * none such exists) * @param yLoc * - the vertical location to lay out the nodes on. */ private void placeChildless(List<GXMoreThanNode> childlessStrand, GXMoreThanNode parentLeft, GXMoreThanNode parentRight, int yLoc) { int startMark = 0; int spacing = (int) (childlessStrand.get(0).getNode().getLayoutEntity().getWidthInLayout() + horSpacing); // There's only a parent on the right if (parentLeft == null && parentRight != null) { startMark = parentRight.getX() - (spacing * childlessStrand.size()); } // there's a parent on the left else if (parentLeft != null) { startMark = parentLeft.getX() + spacing; // there's a parent on the right as well meaning the childless are // between two parents // we need to make there's enough room to place them if (parentRight != null) { int endMark = startMark + (spacing * childlessStrand.size()); // if there isn't enough room to place the childless between the // parents if (endMark > parentRight.getX()) { // shift everything on the right to the right by the missing // amount of space. shiftTreesRightOfMark(parentRight, endMark - parentRight.getX()); } } } // now the room has been assured, place strand. placeStrand(childlessStrand, startMark, yLoc, spacing); } /** * Shifts the trees right of mark node * * @param mark * to shift from * @param shift * - factor by which to move right by. */ private void shiftTreesRightOfMark(GXMoreThanNode mark, int shift) { mark.setLocation(mark.getX() + shift, mark.getY()); GXMoreThanNode leftMostChild = getRightMostChild(mark); List<GXMoreThanNode> treeRoots = leftMostChild.getRow().subList(leftMostChild.getRow().indexOf(leftMostChild), leftMostChild.getRow().size()); for (GXMoreThanNode root : treeRoots) { shiftTree(root, shift); } } /** * Returns the right most child of parent * * @param parent * * @return the right most child of parent given. */ private GXMoreThanNode getRightMostChild(GXMoreThanNode parent) { GXMoreThanNode rightMost = parent.getChildren().get(0); // run through children for (GXMoreThanNode child : parent.getChildren()) { if (child.getX() < rightMost.getX()) { rightMost = child; } } return rightMost; } /** * Shifts the given tree by the shift factor given to the right. * * @param root * - root of tree to shift * @param shift * - factor to shirt by */ private void shiftTree(GXMoreThanNode root, int shift) { root.setLocation(root.getX() + shift, root.getY()); for (GXMoreThanNode child : root.getChildren()) { shiftTree(child, shift); } } /** * Places the list of nodes horizontally at the given point and spaced on * horizontally by given spacing. * * @param strand * - list of nodes to be laid out. * @param x * - location to begin the placing * @param y * - vertical location to lay out the entire list. * @param spacing * the horizontal spacing between nodes. */ private void placeStrand(List<GXMoreThanNode> strand, int x, int y, int spacing) { for (GXMoreThanNode item : strand) { item.setLocation(x, y); x += spacing; } } /** * follows the root by all its children to wrap the all up with all the * extra info needed and adds the tree to the matrix. * * @param currRoot * - root to go over tree from * @param entitiesList * - entities available * @param relationshipsList * - relationship between the given entities * @param currRow * - the current row in the matrix we are working on * @param rows * - the matrix. */ private void builtTreeFromRoot(GXMoreThanNode currRoot, List<InternalNode> entitiesList, List<InternalRelationship> relationshipsList, List<GXMoreThanNode> currRow, List<List<GXMoreThanNode>> rows) { // this is the first node that comes from the currRoot // we'll use the mark to know where to continue laying out from GXMoreThanNode mark = null; List<InternalRelationship> relationshipsListCopy = new ArrayList<InternalRelationship>(relationshipsList); // Orders the children of the currRoot in the given row (the row under // it) for (InternalRelationship rel : relationshipsListCopy) { if (currRoot.getNode().equals(rel.getSource())) { InternalNode destNode = rel.getDestination(); // if the destination node hasn't been laid out yet if (entitiesList.contains(destNode)) { // place it in the row (as in lay it out) GXMoreThanNode currNode = new GXMoreThanNode(destNode, currRoot.getNode()); currRoot.addChild(currNode); currRow.add(currNode); currNode.addedToRow(currRow); entitiesList.remove(destNode); // if this is the first node, save it as a mark. if (mark == null) { mark = currNode; } // remove the relationship since both of its ends have been // laid out. relationshipsList.remove(rel); } } } // if new children have been added if (mark != null) { // Create a next row if necessary if (rows.size() - 1 <= rows.indexOf(currRow)) { rows.add(new ArrayList<GXMoreThanNode>()); } List<GXMoreThanNode> nextRow = rows.get(rows.indexOf(currRow) + 1); for (int i = currRow.indexOf(mark); i < currRow.size(); i++) { builtTreeFromRoot(currRow.get(i), entitiesList, relationshipsList, nextRow, rows); } } } /** * Currently we will arbitrarily choose the first node that is not a * destination i.e. it's a starting point\ if none such exists we will * choose a random node. * * @param entitiesList * @param relationshipsList */ private InternalNode getFirstEntity(List<InternalNode> entitiesList, List<InternalRelationship> relationshipsList) { List<InternalNode> entitiesLeft = new ArrayList<InternalNode>(entitiesList); for (int i = 0; i < entitiesLeft.size(); i++) { if (entitiesLeft.get(i).toString().equals("StartNode")) return entitiesLeft.get(i); } // go through all the relationships and remove destination nodes for (InternalRelationship rel : relationshipsList) { entitiesLeft.remove(rel.getDestination()); } if (!entitiesLeft.isEmpty()) { // throw in random for fun of it // return // entitiesLeft.get((int)(Math.round(Math.random()*(entitiesLeft.size()-1)))); return entitiesLeft.get(0); } // if all the nodes were destination nodes then return a random node. // return // entitiesList.get((int)(Math.round(Math.random()*(entitiesList.size()-1)))); return entitiesList.get(0); } /** * Returns an ArrayList containing the elements from the given array. It's * in a separate method and to make sure a new ArrayList is created since * Arrays.asList(T ...) returns an unmodifiable array and throws runtime * exceptions when an innocent programmer is trying to manipulate the * resulting list. * * @param <T> * @param entitiesToLayout * @return */ private <T> List<T> asList(T[] entitiesToLayout) { return new ArrayList<T>(Arrays.asList(entitiesToLayout)); } protected int getCurrentLayoutStep() { // do nothing return 0; } protected int getTotalNumberOfLayoutSteps() { // do nothing return 0; } protected boolean isValidConfiguration(boolean asynchronous, boolean continuous) { // do nothing return true; } protected void postLayoutAlgorithm(InternalNode[] entitiesToLayout, InternalRelationship[] relationshipsToConsider) { // do nothing } protected void preLayoutAlgorithm(InternalNode[] entitiesToLayout, InternalRelationship[] relationshipsToConsider, double x, double y, double width, double height) { // do nothing // entitiesToLayout[0].getLayoutEntity(). } public void setLayoutArea(double x, double y, double width, double height) { // do nothing } public double getHorSpacing() { return horSpacing; } public void setHorSpacing(double horSpacing) { this.horSpacing = horSpacing; } public double getVerSpacing() { return verSpacing; } public void setVerSpacing(double verSpacing) { this.verSpacing = verSpacing; } /** * wraps a node with useful info like parent and children etc. */ private class GXMoreThanNode { private InternalNode m_node; private InternalNode m_parent; private List<GXMoreThanNode> m_children; private List<GXMoreThanNode> m_row; private boolean m_located = false; private int m_y; private int m_x; public GXMoreThanNode(InternalNode node, InternalNode parent) { m_node = node; m_parent = parent; m_children = new ArrayList<GXMoreThanNode>(); } public void addedToRow(List<GXMoreThanNode> row) { m_row = row; } public void setLocation(int x, int y) { m_x = x; m_y = y; m_node.setLocation(x, y); setLocated(true); } public void addChild(GXMoreThanNode currNode) { m_children.add(currNode); } public List<GXMoreThanNode> getChildren() { return m_children; } public void setLocated(boolean located) { m_located = located; } public boolean isLocated() { return m_located; } public InternalNode getNode() { return m_node; } public InternalNode getParent() { return m_parent; } public int getY() { return m_y; } public void setY(int y) { m_y = y; } public int getX() { return m_x; } public void setX(int x) { m_x = x; } public List<GXMoreThanNode> getRow() { return m_row; } } }
/** * Copyright 2017-2019 The GreyCat Authors. All rights reserved. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package greycat.memory; import greycat.Constants; import greycat.Container; import greycat.Graph; import greycat.Type; import greycat.chunk.ChunkType; import greycat.chunk.StateChunk; import greycat.internal.CoreConstants; import greycat.internal.tree.KDTree; import greycat.internal.tree.NDTree; import greycat.memory.primary.POffHeapDoubleArray; import greycat.memory.primary.POffHeapIntArray; import greycat.memory.primary.POffHeapLongArray; import greycat.memory.primary.POffHeapString; import greycat.plugin.NodeStateCallback; import greycat.struct.Buffer; import greycat.utility.Base64; class OffHeapStateChunk implements StateChunk, OffHeapContainer { private final OffHeapChunkSpace space; private final long index; private static final int DIRTY = 0; private static final int SIZE = 1; private static final int CAPACITY = 2; private static final int SUBHASH = 3; private static final int OFFSET = 4; private static final int ELEM_SIZE = 3; @Override public final long world() { return space.worldByIndex(index); } @Override public final long time() { return space.timeByIndex(index); } @Override public final long id() { return space.idByIndex(index); } OffHeapStateChunk(final OffHeapChunkSpace p_space, final long p_index) { index = p_index; space = p_space; } Graph graph() { return space.graph(); } @Override public final void lock() { space.lockByIndex(index); } @Override public final void unlock() { space.unlockByIndex(index); } @Override public final long addrByIndex(long elemIndex) { return POffHeapLongArray.get(space.addrByIndex(index), OFFSET + (elemIndex * ELEM_SIZE) + 2); } @Override public void setAddrByIndex(long elemIndex, long newAddr) { POffHeapLongArray.set(space.addrByIndex(index), OFFSET + (elemIndex * ELEM_SIZE) + 2, newAddr); } private static long key(final long addr, final long index) { return POffHeapLongArray.get(addr, OFFSET + (index * ELEM_SIZE)); } private static void setKey(final long addr, final long index, final long insertKey) { POffHeapLongArray.set(addr, OFFSET + (index * ELEM_SIZE), insertKey); } private static byte type(final long addr, final long index) { return (byte) POffHeapLongArray.get(addr, OFFSET + (index * ELEM_SIZE) + 1); } private static void setType(final long addr, final long index, final byte insertType) { POffHeapLongArray.set(addr, OFFSET + (index * ELEM_SIZE) + 1, insertType); } private static long value(final long addr, final long index) { return POffHeapLongArray.get(addr, OFFSET + (index * ELEM_SIZE) + 2); } private static void setValue(final long addr, final long index, final long insertValue) { POffHeapLongArray.set(addr, OFFSET + (index * ELEM_SIZE) + 2, insertValue); } private static double doubleValue(final long addr, final long index) { return POffHeapDoubleArray.get(addr, OFFSET + (index * ELEM_SIZE) + 2); } private static void setDoubleValue(final long addr, final long index, final double insertValue) { POffHeapDoubleArray.set(addr, OFFSET + (index * ELEM_SIZE) + 2, insertValue); } private static long next(final long hashAddr, final long index) { return POffHeapLongArray.get(hashAddr, index); } private static void setNext(final long hashAddr, final long index, final long insertNext) { POffHeapLongArray.set(hashAddr, index, insertNext); } private static long hash(final long hashAddr, final long capacity, final long index) { return POffHeapLongArray.get(hashAddr, capacity + index); } private static void setHash(final long hashAddr, final long capacity, final long index, final long insertHash) { POffHeapLongArray.set(hashAddr, capacity + index, insertHash); } @Override public final byte chunkType() { return ChunkType.STATE_CHUNK; } @Override public final long index() { return index; } @Override public final Object getAt(final int p_key) { Object result = null; lock(); try { final long addr = space.addrByIndex(index); if (addr != OffHeapConstants.NULL_PTR) { final long foundIndex = internal_find(addr, p_key); result = internal_get(addr, foundIndex); } } finally { unlock(); } return result; } @Override public Object getRawAt(int p_key) { return getAt(p_key); } @Override public Object getTypedRawAt(int p_key, byte type) { Object result = null; lock(); try { final long addr = space.addrByIndex(index); if (addr != OffHeapConstants.NULL_PTR) { final long foundIndex = internal_find(addr, p_key); if (foundIndex != OffHeapConstants.NULL_PTR && type(addr, foundIndex) == type) { result = internal_get(addr, foundIndex); } } } finally { unlock(); } return result; } @Override public final Object get(final String key) { return getAt(space.graph().resolver().stringToHash(key, false)); } @Override public final void each(final NodeStateCallback callBack) { // lock(); // try { final long addr = space.addrByIndex(index); if (addr != OffHeapConstants.NULL_PTR) { final long size = POffHeapLongArray.get(addr, SIZE); for (int i = 0; i < size; i++) { Object resolved = internal_get(addr, i); if (resolved != null) { callBack.on((int) key(addr, i), type(addr, i), resolved); } } } // } finally { //unlock(); // } } private Object internal_get(final long addr, final long index) { if (index >= 0) { final byte elemType = type(addr, index); final long rawValue = value(addr, index); switch (type(addr, index)) { case Type.BOOL: return rawValue == 1; case Type.DOUBLE: return doubleValue(addr, index); case Type.LONG: return rawValue; case Type.INT: return (int) rawValue; case Type.STRING: return POffHeapString.asObject(rawValue); case Type.LONG_ARRAY: return new OffHeapLongArray(this, index); case Type.DOUBLE_ARRAY: return new OffHeapDoubleArray(this, index); case Type.INT_ARRAY: return new OffHeapIntArray(this, index); case Type.STRING_ARRAY: return new OffHeapStringArray(this, index); case Type.RELATION: return new OffHeapRelation(this, index); case Type.DMATRIX: return new OffHeapDMatrix(this, index); case Type.LMATRIX: return new OffHeapLMatrix(this, index); case Type.STRING_TO_INT_MAP: return new OffHeapStringIntMap(this, index); case Type.LONG_TO_LONG_MAP: return new OffHeapLongLongMap(this, index); case Type.LONG_TO_LONG_ARRAY_MAP: return new OffHeapLongLongArrayMap(this, index); case Type.RELATION_INDEXED: return new OffHeapRelationIndexed(this, index, space.graph()); case Type.NDTREE: return new NDTree(new OffHeapEGraph(this, index, space.graph())); case Type.KDTREE: return new KDTree(new OffHeapEGraph(this, index, space.graph())); case Type.EGRAPH: return new OffHeapEGraph(this, index, space.graph()); case OffHeapConstants.NULL_PTR: return null; default: throw new RuntimeException("Should never happen " + elemType); } } return null; } private long internal_find(final long addr, final long requestKey) { final long size = POffHeapLongArray.get(addr, SIZE); final long subhash_ptr = POffHeapLongArray.get(addr, SUBHASH); if (size == 0) { return -1; } else if (subhash_ptr == OffHeapConstants.NULL_PTR) { for (int i = 0; i < size; i++) { if (key(addr, i) == requestKey) { return i; } } return -1; } else { final long capacity = POffHeapLongArray.get(addr, CAPACITY); long hashIndex = requestKey % (capacity * 2); if (hashIndex < 0) { hashIndex = hashIndex * -1; } long m = hash(subhash_ptr, capacity, hashIndex); while (m >= 0) { if (requestKey == key(addr, m)) { return m; } else { m = next(subhash_ptr, m); } } return -1; } } @Override public final Object getOrCreateAt(final int requestKey, final byte requestType) { Object result; lock(); try { long addr = space.addrByIndex(index); long foundIndex = OffHeapConstants.NULL_PTR; if (addr != OffHeapConstants.NULL_PTR) { foundIndex = internal_find(addr, requestKey); } if (foundIndex == OffHeapConstants.NULL_PTR || type(addr, foundIndex) != requestType) { foundIndex = internal_set(requestKey, requestType, OffHeapConstants.NULL_PTR, true, false); addr = space.addrByIndex(index); } result = internal_get(addr, foundIndex); } finally { unlock(); } return result; } @Override public final Object getOrCreate(final String key, final byte elemType) { return getOrCreateAt(space.graph().resolver().stringToHash(key, true), elemType); } @Override public final Container setAt(final int p_elementIndex, final byte p_elemType, final Object p_unsafe_elem) { if (p_elemType == Type.LONG_TO_LONG_MAP || p_elemType == Type.LONG_TO_LONG_ARRAY_MAP || p_elemType == Type.STRING_TO_INT_MAP || p_elemType == Type.RELATION || p_elemType == Type.RELATION_INDEXED || p_elemType == Type.DMATRIX || p_elemType == Type.LMATRIX || p_elemType == Type.LONG_ARRAY || p_elemType == Type.DOUBLE_ARRAY || p_elemType == Type.INT_ARRAY || p_elemType == Type.STRING_ARRAY) { throw new RuntimeException("Bad API usage ! Set are forbidden for Maps and Relationship , please use getOrCreate instead"); } lock(); try { internal_set(p_elementIndex, p_elemType, p_unsafe_elem, true, false); } finally { unlock(); } return this; } @Override public Container remove(String name) { return removeAt(space.graph().resolver().stringToHash(name, false)); } @Override public Container removeAt(int index) { return setAt(index, Type.INT, null); } @Override public final Container set(final String key, final byte p_elemType, final Object p_unsafe_elem) { setAt(space.graph().resolver().stringToHash(key, true), p_elemType, p_unsafe_elem); return this; } @Override public final <A> A getWithDefault(final String key, final A defaultValue) { final Object result = get(key); if (result == null) { return defaultValue; } else { return (A) result; } } @Override public <A> A getAtWithDefault(int key, A defaultValue) { final Object result = getAt(key); if (result == null) { return defaultValue; } else { return (A) result; } } @Override public final Container rephase() { return this; } @Override public final byte typeAt(final int p_key) { byte result = (byte) -1; lock(); try { final long addr = space.addrByIndex(index); if (addr != OffHeapConstants.NULL_PTR) { final long index = internal_find(addr, p_key); if (index != OffHeapConstants.NULL_PTR) { result = type(addr, index); } } } finally { unlock(); } return result; } @Override public byte type(final String key) { return typeAt(space.graph().resolver().stringToHash(key, false)); } @Override public final void declareDirty() { final long addr = space.addrByIndex(index); if (POffHeapLongArray.get(addr, DIRTY) != 1) { POffHeapLongArray.set(addr, DIRTY, 1); space.notifyUpdate(index); } } @Override public final void save(final Buffer buffer) { lock(); try { final long addr = space.addrByIndex(index); if (addr != OffHeapConstants.NULL_PTR) { long size = POffHeapLongArray.get(addr, SIZE); Base64.encodeLongToBuffer(size, buffer); for (int i = 0; i < size; i++) { buffer.write(Constants.CHUNK_SEP); final byte type = type(addr, i); Base64.encodeIntToBuffer((int) type, buffer); buffer.write(Constants.CHUNK_SEP); Base64.encodeLongToBuffer(key(addr, i), buffer); buffer.write(Constants.CHUNK_SEP); final long rawValue = value(addr, i); switch (type) { case Type.STRING: POffHeapString.save(rawValue, buffer); break; case Type.BOOL: if (rawValue == 1) { Base64.encodeIntToBuffer(CoreConstants.BOOL_TRUE, buffer); } else { Base64.encodeIntToBuffer(CoreConstants.BOOL_FALSE, buffer); } break; case Type.LONG: Base64.encodeLongToBuffer(rawValue, buffer); break; case Type.DOUBLE: Base64.encodeDoubleToBuffer(doubleValue(addr, i), buffer); break; case Type.INT: Base64.encodeIntToBuffer((int) rawValue, buffer); break; case Type.DOUBLE_ARRAY: OffHeapDoubleArray.save(rawValue, buffer); break; case Type.LONG_ARRAY: OffHeapLongArray.save(rawValue, buffer); break; case Type.INT_ARRAY: OffHeapIntArray.save(rawValue, buffer); break; case Type.STRING_ARRAY: OffHeapStringArray.save(rawValue, buffer); break; case Type.RELATION: OffHeapRelation.save(rawValue, buffer); break; case Type.DMATRIX: OffHeapDMatrix.save(rawValue, buffer); break; case Type.LMATRIX: OffHeapLMatrix.save(rawValue, buffer); break; case Type.STRING_TO_INT_MAP: OffHeapStringIntMap.save(rawValue, buffer); break; case Type.LONG_TO_LONG_MAP: OffHeapLongLongMap.save(rawValue, buffer); break; case Type.RELATION_INDEXED: case Type.LONG_TO_LONG_ARRAY_MAP: OffHeapLongLongArrayMap.save(rawValue, buffer); break; case Type.NDTREE: case Type.KDTREE: case Type.EGRAPH: OffHeapEGraph castedEGraph = new OffHeapEGraph(this, i, space.graph()); int eGSize = castedEGraph.size(); Base64.encodeIntToBuffer(eGSize, buffer); for (int j = 0; j < eGSize; j++) { OffHeapENode eNode = new OffHeapENode(j, castedEGraph, space.graph()); buffer.write(CoreConstants.CHUNK_ENODE_SEP); eNode.save(buffer); } castedEGraph.declareUnDirty(); break; default: break; } } } else { //we save a empty chunk Base64.encodeLongToBuffer(0, buffer); } } finally { unlock(); } } @Override public void saveDiff(Buffer buffer) { save(buffer); } @Override public void loadFrom(final StateChunk origin) { if (origin == null) { return; } lock(); try { OffHeapStateChunk casted = (OffHeapStateChunk) origin; casted.lock(); try { //clean previous if exist long addr = space.addrByIndex(index); if (addr != OffHeapConstants.NULL_PTR) { free(addr, space); } //retrieve to clone address final long castedAddr = space.addrByIndex(casted.index); //nothing set yet, don't clone if (castedAddr == OffHeapConstants.NULL_PTR) { space.setAddrByIndex(index, OffHeapConstants.NULL_PTR); } else { final long castedCapacity = POffHeapLongArray.get(castedAddr, CAPACITY); final long castedSize = POffHeapLongArray.get(castedAddr, SIZE); final long castedSubHash = POffHeapLongArray.get(castedAddr, SUBHASH); addr = POffHeapLongArray.cloneArray(castedAddr, OFFSET + (castedCapacity * ELEM_SIZE)); //clone sub hash if needed if (castedSubHash != OffHeapConstants.NULL_PTR) { POffHeapLongArray.set(addr, SUBHASH, POffHeapLongArray.cloneArray(castedSubHash, castedCapacity * 3)); } //clone complex structures //TODO optimze with a flag to avoid this iteration for (int i = 0; i < castedSize; i++) { switch (type(castedAddr, i)) { case Type.LONG_ARRAY: OffHeapLongArray.clone(value(castedAddr, i)); break; case Type.DOUBLE_ARRAY: OffHeapDoubleArray.clone(value(castedAddr, i)); break; case Type.INT_ARRAY: OffHeapIntArray.clone(value(castedAddr, i)); break; case Type.STRING_ARRAY: OffHeapStringArray.clone(value(castedAddr, i)); break; case Type.STRING: POffHeapString.clone(value(castedAddr, i)); break; case Type.RELATION: setValue(addr, i, OffHeapRelation.clone(value(castedAddr, i))); break; case Type.DMATRIX: setValue(addr, i, OffHeapDMatrix.clone(value(castedAddr, i))); break; case Type.LMATRIX: setValue(addr, i, OffHeapLMatrix.clone(value(castedAddr, i))); break; case Type.LONG_TO_LONG_MAP: setValue(addr, i, OffHeapLongLongMap.clone(value(castedAddr, i))); break; case Type.RELATION_INDEXED: case Type.LONG_TO_LONG_ARRAY_MAP: setValue(addr, i, OffHeapLongLongArrayMap.clone(value(castedAddr, i))); break; case Type.STRING_TO_INT_MAP: setValue(addr, i, OffHeapStringIntMap.clone(value(castedAddr, i))); break; case Type.KDTREE: case Type.NDTREE: case Type.EGRAPH: setValue(addr, i, OffHeapEGraph.clone(value(castedAddr, i))); break; } } space.setAddrByIndex(index, addr); } } finally { casted.unlock(); } } finally { unlock(); } } private long toAddr(final byte p_type, final Object p_unsafe_elem) { long param_elem = -1; if (p_unsafe_elem != null) { try { switch (p_type) { case Type.BOOL: param_elem = ((boolean) p_unsafe_elem) ? 1 : 0; break; case Type.LONG: if (p_unsafe_elem instanceof Long) { param_elem = (long) p_unsafe_elem; } else if (p_unsafe_elem instanceof Double) { param_elem = (long) (double) p_unsafe_elem; } else if (p_unsafe_elem instanceof Float) { param_elem = (long) (float) p_unsafe_elem; } else if (p_unsafe_elem instanceof Integer) { param_elem = (long) (int) p_unsafe_elem; } else if (p_unsafe_elem instanceof Byte) { param_elem = (long) (byte) p_unsafe_elem; } else { param_elem = (long) p_unsafe_elem; } break; case Type.INT: if (p_unsafe_elem instanceof Integer) { param_elem = (int) p_unsafe_elem; } else if (p_unsafe_elem instanceof Double) { param_elem = (int) (double) p_unsafe_elem; } else if (p_unsafe_elem instanceof Float) { param_elem = (int) (float) p_unsafe_elem; } else if (p_unsafe_elem instanceof Long) { param_elem = (int) (long) p_unsafe_elem; } else if (p_unsafe_elem instanceof Byte) { param_elem = (int) (byte) p_unsafe_elem; } else { param_elem = (int) p_unsafe_elem; } break; case Type.STRING: param_elem = POffHeapString.fromObject((String) p_unsafe_elem); break; case Type.LONG_ARRAY: case Type.DOUBLE_ARRAY: case Type.INT_ARRAY: case Type.STRING_ARRAY: case Type.RELATION: case Type.DMATRIX: case Type.LMATRIX: case Type.STRING_TO_INT_MAP: case Type.LONG_TO_LONG_MAP: case Type.RELATION_INDEXED: case Type.LONG_TO_LONG_ARRAY_MAP: case Type.NDTREE: case Type.KDTREE: case Type.EGRAPH: param_elem = OffHeapConstants.NULL_PTR; //empty initial ptr break; default: throw new RuntimeException("Internal Exception, unknown type"); } } catch (Exception e) { throw new RuntimeException("mwDB usage error, set method called with type " + Type.typeName(p_type) + " while param object is " + p_unsafe_elem); } } return param_elem; } private double toDoubleValue(final Object p_unsafe_elem) { if (p_unsafe_elem instanceof Double) { return (double) p_unsafe_elem; } else if (p_unsafe_elem instanceof Integer) { return (double) (int) p_unsafe_elem; } else if (p_unsafe_elem instanceof Float) { return (double) (float) p_unsafe_elem; } else if (p_unsafe_elem instanceof Long) { return (double) (long) p_unsafe_elem; } else if (p_unsafe_elem instanceof Byte) { return (double) (byte) p_unsafe_elem; } return (double) p_unsafe_elem; } private long internal_set(final long p_key, final byte p_type, final Object p_unsafe_elem, boolean replaceIfPresent, boolean initial) { long addr = space.addrByIndex(index); if (addr == OffHeapConstants.NULL_PTR) { addr = allocate(addr, Constants.MAP_INITIAL_CAPACITY); } long entry = -1; long prev_entry = -1; long hashIndex = -1; long size = POffHeapLongArray.get(addr, SIZE); long capacity = POffHeapLongArray.get(addr, CAPACITY); long subhash_ptr = POffHeapLongArray.get(addr, SUBHASH); if (subhash_ptr == OffHeapConstants.NULL_PTR) { for (int i = 0; i < size; i++) { if (key(addr, i) == p_key) { entry = i; break; } } } else { hashIndex = p_key % (capacity * 2); if (hashIndex < 0) { hashIndex = hashIndex * -1; } long m = hash(subhash_ptr, capacity, hashIndex); while (m != -1) { if (key(addr, m) == p_key) { entry = m; break; } prev_entry = m; m = next(subhash_ptr, m); } } //case already present if (entry != -1) { final byte found_type = type(addr, entry); if (replaceIfPresent || (p_type != found_type)) { if (p_unsafe_elem == null) { /* Case: supression of a value */ //freeThePreviousValue freeElement(value(addr, entry), found_type, space); //then clean the acces chain if (subhash_ptr != OffHeapConstants.NULL_PTR) { //unHash previous if (prev_entry != -1) { setNext(subhash_ptr, prev_entry, next(subhash_ptr, entry)); } else { setHash(subhash_ptr, capacity, hashIndex, -1); } } long indexVictim = size - 1; //just pop the last value if (entry == indexVictim) { setKey(addr, entry, OffHeapConstants.NULL_PTR); setValue(addr, entry, OffHeapConstants.NULL_PTR); setType(addr, entry, (byte) OffHeapConstants.NULL_PTR); } else { //we need to reHash the new last element at our place setKey(addr, entry, key(addr, indexVictim)); final byte typeOfVictim = type(addr, indexVictim); if (typeOfVictim == Type.DOUBLE) { final double victimDoubleValue = doubleValue(addr, indexVictim); setDoubleValue(addr, entry, victimDoubleValue); } else { setValue(addr, entry, value(addr, indexVictim)); } setType(addr, entry, typeOfVictim); if (subhash_ptr != OffHeapConstants.NULL_PTR) { setNext(addr, entry, next(subhash_ptr, indexVictim)); long victimHash = key(addr, entry) % (capacity * 2); if (victimHash < 0) { victimHash = victimHash * -1; } long m = hash(subhash_ptr, capacity, victimHash); if (m == indexVictim) { //the victim was the head of hashing list setHash(subhash_ptr, capacity, victimHash, entry); } else { //the victim is in the next, rechain it while (m != -1) { if (next(addr, m) == indexVictim) { setNext(subhash_ptr, m, entry); break; } m = next(subhash_ptr, m); } } } setKey(addr, indexVictim, OffHeapConstants.NULL_PTR); freeElement(value(addr, indexVictim), type(addr, indexVictim), space); setValue(addr, indexVictim, OffHeapConstants.NULL_PTR); setType(addr, indexVictim, (byte) OffHeapConstants.NULL_PTR); } POffHeapLongArray.set(addr, SIZE, size - 1); } else { final long previous_value = value(addr, entry); //freeThePreviousValue if (p_type == Type.DOUBLE) { setDoubleValue(addr, entry, toDoubleValue(p_unsafe_elem)); } else { setValue(addr, entry, toAddr(p_type, p_unsafe_elem)); } freeElement(previous_value, found_type, space); if (found_type != p_type) { setType(addr, entry, p_type); } } } if (!initial) { declareDirty(); } return entry; } if (size >= capacity) { long newCapacity = capacity * 2; addr = allocate(addr, newCapacity); subhash_ptr = POffHeapLongArray.get(addr, SUBHASH); capacity = newCapacity; hashIndex = p_key % (capacity * 2); if (hashIndex < 0) { hashIndex = hashIndex * -1; } } final long insert_index = size; setKey(addr, insert_index, p_key); if (p_type == Type.DOUBLE) { setDoubleValue(addr, insert_index, toDoubleValue(p_unsafe_elem)); } else { setValue(addr, insert_index, toAddr(p_type, p_unsafe_elem)); } setType(addr, insert_index, p_type); if (subhash_ptr != OffHeapConstants.NULL_PTR) { setNext(subhash_ptr, insert_index, hash(subhash_ptr, capacity, hashIndex)); setHash(subhash_ptr, capacity, hashIndex, insert_index); } size++; POffHeapLongArray.set(addr, SIZE, size); if (!initial) { declareDirty(); } return insert_index; } private long allocate(final long addr, final long newCapacity) { if (addr == OffHeapConstants.NULL_PTR) { //nothing before, initial allocation... final long new_addr = POffHeapLongArray.allocate(OFFSET + (newCapacity * ELEM_SIZE)); space.setAddrByIndex(index, new_addr); POffHeapLongArray.set(new_addr, CAPACITY, newCapacity); POffHeapLongArray.set(new_addr, DIRTY, 0); POffHeapLongArray.set(new_addr, SIZE, 0); if (newCapacity > Constants.MAP_INITIAL_CAPACITY) { POffHeapLongArray.set(new_addr, SUBHASH, POffHeapLongArray.allocate(newCapacity * 3)); } else { POffHeapLongArray.set(new_addr, SUBHASH, OffHeapConstants.NULL_PTR); } return new_addr; } else { //reallocation or overallocation final long new_addr = POffHeapLongArray.reallocate(addr, OFFSET + (newCapacity * ELEM_SIZE)); space.setAddrByIndex(index, new_addr); POffHeapLongArray.set(new_addr, CAPACITY, newCapacity); long subHash_ptr = POffHeapLongArray.get(new_addr, SUBHASH); if (subHash_ptr == OffHeapConstants.NULL_PTR) { subHash_ptr = POffHeapLongArray.allocate(newCapacity * 3); } else { subHash_ptr = POffHeapLongArray.reallocate(subHash_ptr, newCapacity * 3); POffHeapLongArray.reset(subHash_ptr, newCapacity * 3); } POffHeapLongArray.set(new_addr, SUBHASH, subHash_ptr); //reHash final long size = POffHeapLongArray.get(new_addr, SIZE); final long hash_capacity = newCapacity * 2; for (long i = 0; i < size; i++) { long keyHash = key(new_addr, i) % hash_capacity; if (keyHash < 0) { keyHash = keyHash * -1; } setNext(subHash_ptr, i, hash(subHash_ptr, newCapacity, keyHash)); setHash(subHash_ptr, newCapacity, keyHash, i); } return new_addr; } } private static final byte LOAD_WAITING_ALLOC = 0; private static final byte LOAD_WAITING_TYPE = 1; private static final byte LOAD_WAITING_KEY = 2; private static final byte LOAD_WAITING_VALUE = 3; @Override public final void load(final Buffer buffer) { if (buffer != null && buffer.length() > 0) { lock(); try { long addr = space.addrByIndex(index); final boolean initial = (addr == OffHeapConstants.NULL_PTR); long capacity = 0; if (addr != OffHeapConstants.NULL_PTR) { capacity = POffHeapLongArray.get(addr, CAPACITY); } final long payloadSize = buffer.length(); long previous = 0; long cursor = 0; byte state = LOAD_WAITING_ALLOC; byte read_type = -1; long read_key = -1; while (cursor < payloadSize) { byte current = buffer.read(cursor); if (current == Constants.CHUNK_SEP) { switch (state) { case LOAD_WAITING_ALLOC: final int stateChunkSize = Base64.decodeToIntWithBounds(buffer, 0, cursor); final int closePowerOfTwo = (int) Math.pow(2, Math.ceil(Math.log(stateChunkSize) / Math.log(2))); if (capacity < closePowerOfTwo) { addr = allocate(addr, closePowerOfTwo); capacity = closePowerOfTwo; } state = LOAD_WAITING_TYPE; cursor++; previous = cursor; break; case LOAD_WAITING_TYPE: read_type = (byte) Base64.decodeToIntWithBounds(buffer, previous, cursor); state = LOAD_WAITING_KEY; cursor++; previous = cursor; break; case LOAD_WAITING_KEY: read_key = Base64.decodeToLongWithBounds(buffer, previous, cursor); //primitive default loader switch (read_type) { //primitive types case Type.BOOL: case Type.INT: case Type.DOUBLE: case Type.LONG: case Type.STRING: state = LOAD_WAITING_VALUE; cursor++; previous = cursor; break; case Type.LONG_ARRAY: OffHeapLongArray longArray = new OffHeapLongArray(this, internal_set(read_key, read_type, null, true, initial)); cursor++; cursor = longArray.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_SEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.DOUBLE_ARRAY: OffHeapDoubleArray doubleArray = new OffHeapDoubleArray(this, internal_set(read_key, read_type, null, true, initial)); cursor++; cursor = doubleArray.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_SEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.INT_ARRAY: OffHeapIntArray intArray = new OffHeapIntArray(this, internal_set(read_key, read_type, null, true, initial)); cursor++; cursor = intArray.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_SEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.STRING_ARRAY: OffHeapStringArray stringArray = new OffHeapStringArray(this, internal_set(read_key, read_type, null, true, initial)); cursor++; cursor = stringArray.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_SEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.RELATION: OffHeapRelation relation = new OffHeapRelation(this, internal_set(read_key, read_type, null, true, initial)); cursor++; cursor = relation.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_SEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.DMATRIX: OffHeapDMatrix dmatrix = new OffHeapDMatrix(this, internal_set(read_key, read_type, null, true, initial)); cursor++; cursor = dmatrix.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_SEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.LMATRIX: OffHeapLMatrix lmatrix = new OffHeapLMatrix(this, internal_set(read_key, read_type, null, true, initial)); cursor++; cursor = lmatrix.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_SEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.LONG_TO_LONG_MAP: OffHeapLongLongMap l2lmap = new OffHeapLongLongMap(this, internal_set(read_key, read_type, null, true, initial)); cursor++; cursor = l2lmap.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_SEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.LONG_TO_LONG_ARRAY_MAP: OffHeapLongLongArrayMap l2lrmap = new OffHeapLongLongArrayMap(this, internal_set(read_key, read_type, null, true, initial)); cursor++; cursor = l2lrmap.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_SEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.RELATION_INDEXED: OffHeapRelationIndexed relationIndexed = new OffHeapRelationIndexed(this, internal_set(read_key, read_type, null, true, initial), space.graph()); cursor++; cursor = relationIndexed.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_SEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.STRING_TO_INT_MAP: OffHeapStringIntMap s2lmap = new OffHeapStringIntMap(this, internal_set(read_key, read_type, null, true, initial)); cursor++; cursor = s2lmap.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_SEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; case Type.NDTREE: case Type.KDTREE: case Type.EGRAPH: OffHeapEGraph eGraph = new OffHeapEGraph(this, internal_set(read_key, read_type, null, true, initial), this.graph()); cursor++; cursor = eGraph.load(buffer, cursor, payloadSize); if (cursor < payloadSize) { current = buffer.read(cursor); if (current == Constants.CHUNK_SEP && cursor < payloadSize) { state = LOAD_WAITING_TYPE; cursor++; previous = cursor; } } break; default: throw new RuntimeException("Not implemented yet!!!"); } break; case LOAD_WAITING_VALUE: load_primitive(read_key, read_type, buffer, previous, cursor, initial); state = LOAD_WAITING_TYPE; cursor++; previous = cursor; break; } } else { cursor++; } } if (state == LOAD_WAITING_VALUE) { load_primitive(read_key, read_type, buffer, previous, cursor, initial); } } finally { unlock(); } } } private void load_primitive(final long read_key, final byte read_type, final Buffer buffer, final long previous, final long cursor, final boolean initial) { switch (read_type) { case Type.BOOL: internal_set(read_key, read_type, (((byte) Base64.decodeToIntWithBounds(buffer, previous, cursor)) == CoreConstants.BOOL_TRUE), true, initial); break; case Type.INT: internal_set(read_key, read_type, Base64.decodeToIntWithBounds(buffer, previous, cursor), true, initial); break; case Type.DOUBLE: internal_set(read_key, read_type, Base64.decodeToDoubleWithBounds(buffer, previous, cursor), true, initial); break; case Type.LONG: internal_set(read_key, read_type, Base64.decodeToLongWithBounds(buffer, previous, cursor), true, initial); break; case Type.STRING: internal_set(read_key, read_type, Base64.decodeToStringWithBounds(buffer, previous, cursor), true, initial); break; } } @Override public void loadDiff(Buffer buffer) { load(buffer); } static void free(final long addr, final OffHeapChunkSpace space) { if (addr != OffHeapConstants.NULL_PTR) { final long subhash_ptr = POffHeapLongArray.get(addr, SUBHASH); final long size = POffHeapLongArray.get(addr, SIZE); for (long i = 0; i < size; i++) { freeElement(value(addr, i), type(addr, i), space); } if (subhash_ptr != OffHeapConstants.NULL_PTR) { POffHeapLongArray.free(subhash_ptr); } POffHeapLongArray.free(addr); } } private static void freeElement(final long addr, final byte elemType, final OffHeapChunkSpace space) { switch (elemType) { case Type.STRING: POffHeapString.free(addr); break; case Type.RELATION: OffHeapRelation.free(addr); break; case Type.DMATRIX: OffHeapDMatrix.free(addr); break; case Type.LMATRIX: OffHeapLMatrix.free(addr); break; case Type.LONG_ARRAY: OffHeapLongArray.free(addr); break; case Type.INT_ARRAY: OffHeapIntArray.free(addr); break; case Type.DOUBLE_ARRAY: OffHeapDoubleArray.free(addr); break; case Type.STRING_ARRAY: OffHeapStringArray.free(addr); break; case Type.STRING_TO_INT_MAP: OffHeapStringIntMap.free(addr); break; case Type.LONG_TO_LONG_MAP: OffHeapLongLongMap.free(addr); break; case Type.RELATION_INDEXED: case Type.LONG_TO_LONG_ARRAY_MAP: OffHeapLongLongArrayMap.free(addr); break; case Type.NDTREE: case Type.KDTREE: case Type.EGRAPH: OffHeapEGraph.freeByAddr(addr); } } }
package net.bytebuddy.utility.dispatcher; import net.bytebuddy.ClassFileVersion; import net.bytebuddy.test.utility.JavaVersionRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.MethodRule; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.security.Permission; import java.security.PermissionCollection; import java.security.ProtectionDomain; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(Parameterized.class) public class JavaDispatcherTest { @Rule public MethodRule javaVersionRule = new JavaVersionRule(); private final boolean generate; public JavaDispatcherTest(boolean generate) { this.generate = generate; } @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {true}, {false} }); } @Test public void testConstructor() throws Exception { assertThat(JavaDispatcher.of(Constructor.class, null, generate).run().make(), instanceOf(Object.class)); } @Test public void testStaticDispatcher() throws Exception { assertThat(JavaDispatcher.of(StaticSample.class, null, generate).run().forName(Object.class.getName()), is((Object) Object.class)); } @Test public void testStaticAdjustedDispatcher() throws Exception { assertThat(JavaDispatcher.of(StaticAdjustedSample.class, null, generate).run().forName(Object.class.getName()), is((Object) Object.class)); } @Test(expected = IllegalStateException.class) public void testStaticAdjustedIllegalDispatcher() throws Exception { assertThat(JavaDispatcher.of(StaticAdjustedIllegalSample.class, null, generate).run().forName(null), is((Object) Object.class)); } @Test public void testNonStaticDispatcher() throws Exception { assertThat(JavaDispatcher.of(NonStaticSample.class, null, generate).run().getName(Object.class), is(Object.class.getName())); } @Test public void testNonStaticAdjustedDispatcher() throws Exception { assertThat(JavaDispatcher.of(NonStaticAdjustedSample.class, null, generate).run().getMethod(Object.class, "equals", new Class<?>[]{Object.class}), is(Object.class.getMethod("equals", Object.class))); } @Test(expected = IllegalStateException.class) public void testNonStaticAdjustedIllegalDispatcher() throws Exception { JavaDispatcher.of(NonStaticAdjustedIllegalSample.class, null, generate).run().getMethod(Object.class, "equals", null); } @Test public void testNonStaticRenamedDispatcher() throws Exception { assertThat(JavaDispatcher.of(NonStaticRenamedSample.class, null, generate).run().getNameRenamed(Object.class), is(Object.class.getName())); } @Test public void testIsInstance() throws Exception { IsInstanceSample sample = JavaDispatcher.of(IsInstanceSample.class, null, generate).run(); assertThat(sample.isInstance(Object.class), is(true)); assertThat(sample.isInstance(new Object()), is(false)); } @Test(expected = IllegalStateException.class) public void testIsInstanceIllegal() throws Exception { JavaDispatcher.of(IsInstanceIllegalSample.class, null, generate).run().isInstance(null); } @Test public void testContainer() throws Exception { Class<?>[] array = JavaDispatcher.of(ContainerSample.class, null, generate).run().toArray(1); assertThat(array.length, is(1)); assertThat(array[0], nullValue(Class.class)); } @Test(expected = IllegalStateException.class) public void testContainerIllegal() throws Exception { JavaDispatcher.of(IllegalContainerSample.class, null, generate).run().toArray(null); } @Test(expected = IllegalStateException.class) public void testNonExistentType() throws Exception { JavaDispatcher.of(NonExistentTypeSample.class, null, generate).run().foo(); } @Test(expected = IllegalStateException.class) public void testNonExistentMethod() throws Exception { JavaDispatcher.of(NonExistentMethodSample.class, null, generate).run().foo(); } @Test(expected = IllegalArgumentException.class) public void testNonInterface() throws Exception { JavaDispatcher.of(Object.class, null, generate); } @Test(expected = IllegalArgumentException.class) public void testNonAnnotated() throws Exception { JavaDispatcher.of(Runnable.class, null, generate); } @Test(expected = IOException.class) public void testDeclaredException() throws Exception { File file = mock(File.class); when(file.getCanonicalPath()).thenThrow(new IOException()); JavaDispatcher.of(DeclaredExceptionSample.class, null, generate).run().getCanonicalPath(file); } @Test(expected = IllegalStateException.class) public void testUndeclaredException() throws Exception { JavaDispatcher.of(UndeclaredExceptionSample.class, null, generate).run().getCanonicalPath(mock(File.class)); } @Test public void testProxy() { assertThat(Proxy.isProxyClass(JavaDispatcher.of(StaticSample.class, null, generate).run().getClass()), is(!generate)); } @Test(expected = IllegalArgumentException.class) public void testJavaSecurity() { JavaDispatcher.of(ProtectionDomain.class, null, generate); } @JavaVersionRule.Enforce(9) @Test(expected = UnsupportedOperationException.class) public void testMethodHandleLookup() { JavaDispatcher.of(MethodHandles.class, null, generate).run().lookup(); } @Test @JavaVersionRule.Enforce(9) public void testCallerSeparateClassLoader() throws Exception { Class<?> caller = JavaDispatcher.of(JavaDispatcherCaller.class, JavaDispatcherTest.class.getClassLoader(), generate).run().caller(); assertThat(caller.getClassLoader(), not(sameInstance(JavaDispatcher.class.getClassLoader()))); } @Test @JavaVersionRule.Enforce(9) public void testCallerInheritsPermissions() throws Exception { Class<?> caller = JavaDispatcher.of(JavaDispatcherCaller.class, JavaDispatcherTest.class.getClassLoader(), generate).run().caller(); PermissionCollection permissions = caller.getProtectionDomain().getPermissions(); Enumeration<Permission> enumeration = JavaDispatcher.class.getProtectionDomain().getPermissions().elements(); while (enumeration.hasMoreElements()) { assertThat(permissions.implies(enumeration.nextElement()), is(true)); } } @Test @JavaVersionRule.Enforce(9) public void testCallerDoesNotEscalatePermissions() throws Exception { Class<?> caller = JavaDispatcher.of(JavaDispatcherCaller.class, JavaDispatcherTest.class.getClassLoader(), generate).run().caller(); PermissionCollection permissions = JavaDispatcher.class.getProtectionDomain().getPermissions(); Enumeration<Permission> enumeration = caller.getProtectionDomain().getPermissions().elements(); while (enumeration.hasMoreElements()) { assertThat(permissions.implies(enumeration.nextElement()), is(true)); } } @Test public void testDynamicClassLoaderResolverType() throws Exception { Field resolver = JavaDispatcher.class.getDeclaredField("RESOLVER"); resolver.setAccessible(true); assertThat(resolver.get(null), instanceOf(ClassFileVersion.ofThisVm().isAtLeast(ClassFileVersion.JAVA_V9) ? JavaDispatcher.DynamicClassLoader.Resolver.ForModuleSystem.class : JavaDispatcher.DynamicClassLoader.Resolver.NoOp.class)); } @SuppressWarnings({"unchecked", "unused"}) public static Class<?> caller() throws Exception { Class<?> type = Class.forName("java.lang.StackWalker"); Class<?> option = Class.forName("java.lang.StackWalker$Option"); return (Class<?>) type.getMethod("getCallerClass").invoke(type.getMethod("getInstance", option).invoke( null, Enum.valueOf((Class) option, "RETAIN_CLASS_REFERENCE"))); } @JavaDispatcher.Proxied("java.lang.Object") public interface Constructor { @JavaDispatcher.IsConstructor Object make(); } @JavaDispatcher.Proxied("java.lang.Class") public interface StaticSample { @JavaDispatcher.IsStatic Class<?> forName(String name) throws ClassNotFoundException; } @JavaDispatcher.Proxied("java.lang.Class") public interface StaticAdjustedSample { @JavaDispatcher.IsStatic Class<?> forName(@JavaDispatcher.Proxied("java.lang.String") Object name) throws ClassNotFoundException; } @JavaDispatcher.Proxied("java.lang.Class") public interface StaticAdjustedIllegalSample { @JavaDispatcher.IsStatic Class<?> forName(@JavaDispatcher.Proxied("java.lang.String") Void name); } @JavaDispatcher.Proxied("java.lang.Class") public interface NonStaticSample { String getName(Class<?> target); } @JavaDispatcher.Proxied("java.lang.Class") public interface NonStaticAdjustedSample { Method getMethod(Class<?> target, @JavaDispatcher.Proxied("java.lang.String") Object name, @JavaDispatcher.Proxied("java.lang.Class") Object[] argument) throws Exception; } @JavaDispatcher.Proxied("java.lang.Class") public interface NonStaticAdjustedIllegalSample { Method getMethod(Class<?> target, @JavaDispatcher.Proxied("java.lang.String") Object name, @JavaDispatcher.Proxied("java.lang.Class") Void[] argument); } @JavaDispatcher.Proxied("java.lang.Class") public interface NonStaticRenamedSample { @JavaDispatcher.Proxied("getName") String getNameRenamed(Class<?> target); } @JavaDispatcher.Proxied("java.lang.Class") public interface IsInstanceSample { @JavaDispatcher.Instance boolean isInstance(Object target); } @JavaDispatcher.Proxied("java.lang.Class") public interface IsInstanceIllegalSample { @JavaDispatcher.Instance boolean isInstance(Void target); } @JavaDispatcher.Proxied("java.lang.Class") public interface ContainerSample { @JavaDispatcher.Container Class<?>[] toArray(int arity); } @JavaDispatcher.Proxied("java.lang.Class") public interface IllegalContainerSample { @JavaDispatcher.Container Class<?>[] toArray(Void arity); } @JavaDispatcher.Proxied("does.not.Exist") public interface NonExistentTypeSample { void foo(); } @JavaDispatcher.Proxied("java.lang.Object") public interface NonExistentMethodSample { void foo(); } @JavaDispatcher.Proxied("java.io.File") public interface DeclaredExceptionSample { String getCanonicalPath(Object target) throws IOException; } @JavaDispatcher.Proxied("java.io.File") public interface UndeclaredExceptionSample { String getCanonicalPath(Object target); } @JavaDispatcher.Proxied("java.lang.invoke.MethodHandles") public interface MethodHandles { @JavaDispatcher.IsStatic Object lookup(); } @JavaDispatcher.Proxied("net.bytebuddy.utility.dispatcher.JavaDispatcherTest") public interface JavaDispatcherCaller { @JavaDispatcher.IsStatic Class<?> caller() throws Exception; } }
/* * Copyright (C) 2020 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 androidx.media3.common; import static androidx.media3.common.util.Assertions.checkIndex; import static androidx.media3.common.util.Assertions.checkState; import android.util.SparseBooleanArray; import androidx.annotation.Nullable; import androidx.media3.common.util.UnstableApi; import androidx.media3.common.util.Util; /** * A set of integer flags. * * <p>Intended for usages where the number of flags may exceed 32 and can no longer be represented * by an IntDef. * * <p>Instances are immutable. */ @UnstableApi public final class FlagSet { /** A builder for {@link FlagSet} instances. */ public static final class Builder { private final SparseBooleanArray flags; private boolean buildCalled; /** Creates a builder. */ public Builder() { flags = new SparseBooleanArray(); } /** * Adds a flag. * * @param flag A flag. * @return This builder. * @throws IllegalStateException If {@link #build()} has already been called. */ public Builder add(int flag) { checkState(!buildCalled); flags.append(flag, /* value= */ true); return this; } /** * Adds a flag if the provided condition is true. Does nothing otherwise. * * @param flag A flag. * @param condition A condition. * @return This builder. * @throws IllegalStateException If {@link #build()} has already been called. */ public Builder addIf(int flag, boolean condition) { if (condition) { return add(flag); } return this; } /** * Adds flags. * * @param flags The flags to add. * @return This builder. * @throws IllegalStateException If {@link #build()} has already been called. */ public Builder addAll(int... flags) { for (int flag : flags) { add(flag); } return this; } /** * Adds {@link FlagSet flags}. * * @param flags The set of flags to add. * @return This builder. * @throws IllegalStateException If {@link #build()} has already been called. */ public Builder addAll(FlagSet flags) { for (int i = 0; i < flags.size(); i++) { add(flags.get(i)); } return this; } /** * Removes a flag. * * @param flag A flag. * @return This builder. * @throws IllegalStateException If {@link #build()} has already been called. */ public Builder remove(int flag) { checkState(!buildCalled); flags.delete(flag); return this; } /** * Removes a flag if the provided condition is true. Does nothing otherwise. * * @param flag A flag. * @param condition A condition. * @return This builder. * @throws IllegalStateException If {@link #build()} has already been called. */ public Builder removeIf(int flag, boolean condition) { if (condition) { return remove(flag); } return this; } /** * Removes flags. * * @param flags The flags to remove. * @return This builder. * @throws IllegalStateException If {@link #build()} has already been called. */ public Builder removeAll(int... flags) { for (int flag : flags) { remove(flag); } return this; } /** * Builds an {@link FlagSet} instance. * * @throws IllegalStateException If this method has already been called. */ public FlagSet build() { checkState(!buildCalled); buildCalled = true; return new FlagSet(flags); } } // A SparseBooleanArray is used instead of a Set to avoid auto-boxing the flag values. private final SparseBooleanArray flags; private FlagSet(SparseBooleanArray flags) { this.flags = flags; } /** * Returns whether the set contains the given flag. * * @param flag The flag. * @return Whether the set contains the flag. */ public boolean contains(int flag) { return flags.get(flag); } /** * Returns whether the set contains at least one of the given flags. * * @param flags The flags. * @return Whether the set contains at least one of the flags. */ public boolean containsAny(int... flags) { for (int flag : flags) { if (contains(flag)) { return true; } } return false; } /** Returns the number of flags in this set. */ public int size() { return flags.size(); } /** * Returns the flag at the given index. * * @param index The index. Must be between 0 (inclusive) and {@link #size()} (exclusive). * @return The flag at the given index. * @throws IndexOutOfBoundsException If index is outside the allowed range. */ public int get(int index) { checkIndex(index, /* start= */ 0, /* limit= */ size()); return flags.keyAt(index); } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (!(o instanceof FlagSet)) { return false; } FlagSet that = (FlagSet) o; if (Util.SDK_INT < 24) { // SparseBooleanArray.equals() is not implemented on API levels below 24. if (size() != that.size()) { return false; } for (int i = 0; i < size(); i++) { if (get(i) != that.get(i)) { return false; } } return true; } else { return flags.equals(that.flags); } } @Override public int hashCode() { if (Util.SDK_INT < 24) { // SparseBooleanArray.hashCode() is not implemented on API levels below 24. int hashCode = size(); for (int i = 0; i < size(); i++) { hashCode = 31 * hashCode + get(i); } return hashCode; } else { return flags.hashCode(); } } }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2019 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * 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.pentaho.di.core.logging; import java.util.Date; import java.util.Queue; import java.util.Map; import org.pentaho.di.core.Const; import org.pentaho.di.core.util.Utils; import org.pentaho.di.core.metrics.MetricsSnapshot; import org.pentaho.di.core.metrics.MetricsSnapshotInterface; import org.pentaho.di.core.metrics.MetricsSnapshotType; public class LogChannel implements LogChannelInterface { public static LogChannelInterface GENERAL = new LogChannel( "General" ); public static LogChannelInterface METADATA = new LogChannel( "Metadata" ); public static LogChannelInterface UI = new LogChannel( "GUI" ); private String logChannelId; private LogLevel logLevel; private String containerObjectId; private boolean gatheringMetrics; private boolean forcingSeparateLogging; private static MetricsRegistry metricsRegistry = MetricsRegistry.getInstance(); private String filter; private LogChannelFileWriterBuffer fileWriter; public LogChannel( Object subject ) { logLevel = DefaultLogLevel.getLogLevel(); logChannelId = LoggingRegistry.getInstance().registerLoggingSource( subject ); } public LogChannel( Object subject, boolean gatheringMetrics ) { this( subject ); this.gatheringMetrics = gatheringMetrics; } public LogChannel( Object subject, LoggingObjectInterface parentObject ) { if ( parentObject != null ) { this.logLevel = parentObject.getLogLevel(); this.containerObjectId = parentObject.getContainerObjectId(); } else { this.logLevel = DefaultLogLevel.getLogLevel(); this.containerObjectId = null; } logChannelId = LoggingRegistry.getInstance().registerLoggingSource( subject ); } public LogChannel( Object subject, LoggingObjectInterface parentObject, boolean gatheringMetrics ) { this( subject, parentObject ); this.gatheringMetrics = gatheringMetrics; } @Override public String toString() { return logChannelId; } @Override public String getLogChannelId() { return logChannelId; } /** * * @param logMessage * @param channelLogLevel */ public void println( LogMessageInterface logMessage, LogLevel channelLogLevel ) { String subject = null; LogLevel logLevel = logMessage.getLevel(); if ( !logLevel.isVisible( channelLogLevel ) ) { return; // not for our eyes. } if ( subject == null ) { subject = "Kettle"; } // Are the message filtered? // if ( !logLevel.isError() && !Utils.isEmpty( filter ) ) { if ( subject.indexOf( filter ) < 0 && logMessage.toString().indexOf( filter ) < 0 ) { return; // "filter" not found in row: don't show! } } // Let's not keep everything... // if ( channelLogLevel.getLevel() >= logLevel.getLevel() ) { KettleLoggingEvent loggingEvent = new KettleLoggingEvent( logMessage, System.currentTimeMillis(), logLevel ); KettleLogStore.getAppender().addLogggingEvent( loggingEvent ); if ( this.fileWriter == null ) { this.fileWriter = LoggingRegistry.getInstance().getLogChannelFileWriterBuffer( logChannelId ); } // add to buffer if ( this.fileWriter != null ) { this.fileWriter.addEvent( loggingEvent ); } } } public void println( LogMessageInterface message, Throwable e, LogLevel channelLogLevel ) { println( message, channelLogLevel ); String stackTrace = Const.getStackTracker( e ); LogMessage traceMessage = new LogMessage( stackTrace, message.getLogChannelId(), LogLevel.ERROR ); println( traceMessage, channelLogLevel ); } @Override public void logMinimal( String s ) { println( new LogMessage( s, logChannelId, LogLevel.MINIMAL ), logLevel ); } @Override public void logBasic( String s ) { println( new LogMessage( s, logChannelId, LogLevel.BASIC ), logLevel ); } @Override public void logError( String s ) { println( new LogMessage( s, logChannelId, LogLevel.ERROR ), logLevel ); } @Override public void logError( String s, Throwable e ) { println( new LogMessage( s, logChannelId, LogLevel.ERROR ), e, logLevel ); } @Override public void logBasic( String s, Object... arguments ) { println( new LogMessage( s, logChannelId, arguments, LogLevel.BASIC ), logLevel ); } @Override public void logDetailed( String s, Object... arguments ) { println( new LogMessage( s, logChannelId, arguments, LogLevel.DETAILED ), logLevel ); } @Override public void logError( String s, Object... arguments ) { println( new LogMessage( s, logChannelId, arguments, LogLevel.ERROR ), logLevel ); } @Override public void logDetailed( String s ) { println( new LogMessage( s, logChannelId, LogLevel.DETAILED ), logLevel ); } @Override public void logDebug( String s ) { println( new LogMessage( s, logChannelId, LogLevel.DEBUG ), logLevel ); } @Override public void logDebug( String message, Object... arguments ) { println( new LogMessage( message, logChannelId, arguments, LogLevel.DEBUG ), logLevel ); } @Override public void logRowlevel( String s ) { println( new LogMessage( s, logChannelId, LogLevel.ROWLEVEL ), logLevel ); } @Override public void logMinimal( String message, Object... arguments ) { println( new LogMessage( message, logChannelId, arguments, LogLevel.MINIMAL ), logLevel ); } @Override public void logRowlevel( String message, Object... arguments ) { println( new LogMessage( message, logChannelId, arguments, LogLevel.ROWLEVEL ), logLevel ); } @Override public boolean isBasic() { return logLevel.isBasic(); } @Override public boolean isDebug() { return logLevel.isDebug(); } @Override public boolean isDetailed() { try { return logLevel.isDetailed(); } catch ( NullPointerException ex ) { // System.out.println( "Oops!" ); return false; } } @Override public boolean isRowLevel() { return logLevel.isRowlevel(); } @Override public boolean isError() { return logLevel.isError(); } @Override public LogLevel getLogLevel() { return logLevel; } @Override public void setLogLevel( LogLevel logLevel ) { this.logLevel = logLevel; } /** * @return the containerObjectId */ @Override public String getContainerObjectId() { return containerObjectId; } /** * @param containerObjectId * the containerObjectId to set */ @Override public void setContainerObjectId( String containerObjectId ) { this.containerObjectId = containerObjectId; } /** * @return the gatheringMetrics */ @Override public boolean isGatheringMetrics() { return gatheringMetrics; } /** * @param gatheringMetrics * the gatheringMetrics to set */ @Override public void setGatheringMetrics( boolean gatheringMetrics ) { this.gatheringMetrics = gatheringMetrics; } @Override public boolean isForcingSeparateLogging() { return forcingSeparateLogging; } @Override public void setForcingSeparateLogging( boolean forcingSeparateLogging ) { this.forcingSeparateLogging = forcingSeparateLogging; } @Override public void snap( MetricsInterface metric, long... value ) { snap( metric, null, value ); } @Override public void snap( MetricsInterface metric, String subject, long... value ) { if ( !isGatheringMetrics() ) { return; } String key = MetricsSnapshot.getKey( metric, subject ); Map<String, MetricsSnapshotInterface> metricsMap = null; MetricsSnapshotInterface snapshot = null; Queue<MetricsSnapshotInterface> metricsList = null; switch ( metric.getType() ) { case MAX: // Calculate and store the maximum value for this metric // if ( value.length != 1 ) { break; // ignore } metricsMap = metricsRegistry.getSnapshotMap( logChannelId ); snapshot = metricsMap.get( key ); if ( snapshot != null ) { if ( value[0] > snapshot.getValue() ) { snapshot.setValue( value[0] ); snapshot.setDate( new Date() ); } } else { snapshot = new MetricsSnapshot( MetricsSnapshotType.MAX, metric, subject, value[0], logChannelId ); metricsMap.put( key, snapshot ); } break; case MIN: // Calculate and store the minimum value for this metric // if ( value.length != 1 ) { break; // ignore } metricsMap = metricsRegistry.getSnapshotMap( logChannelId ); snapshot = metricsMap.get( key ); if ( snapshot != null ) { if ( value[0] < snapshot.getValue() ) { snapshot.setValue( value[0] ); snapshot.setDate( new Date() ); } } else { snapshot = new MetricsSnapshot( MetricsSnapshotType.MIN, metric, subject, value[0], logChannelId ); metricsMap.put( key, snapshot ); } break; case SUM: metricsMap = metricsRegistry.getSnapshotMap( logChannelId ); snapshot = metricsMap.get( key ); if ( snapshot != null ) { snapshot.setValue( snapshot.getValue() + value[0] ); } else { snapshot = new MetricsSnapshot( MetricsSnapshotType.SUM, metric, subject, value[0], logChannelId ); metricsMap.put( key, snapshot ); } break; case COUNT: metricsMap = metricsRegistry.getSnapshotMap( logChannelId ); snapshot = metricsMap.get( key ); if ( snapshot != null ) { snapshot.setValue( snapshot.getValue() + 1L ); } else { snapshot = new MetricsSnapshot( MetricsSnapshotType.COUNT, metric, subject, 1L, logChannelId ); metricsMap.put( key, snapshot ); } break; case START: metricsList = metricsRegistry.getSnapshotList( logChannelId ); snapshot = new MetricsSnapshot( MetricsSnapshotType.START, metric, subject, 1L, logChannelId ); metricsList.add( snapshot ); break; case STOP: metricsList = metricsRegistry.getSnapshotList( logChannelId ); snapshot = new MetricsSnapshot( MetricsSnapshotType.STOP, metric, subject, 1L, logChannelId ); metricsList.add( snapshot ); break; default: break; } } @Override public String getFilter() { return filter; } @Override public void setFilter( String filter ) { this.filter = filter; } }
/* This file is part of SableCC ( http://sablecc.org ). * * See the NOTICE file distributed with this work for copyright information. * * 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.sablecc.sablecc.semantics; import java.util.*; import org.sablecc.exception.*; import org.sablecc.sablecc.syntax3.node.*; public class Grammar extends Declaration { private AGrammar declaration; private Map<Node, Object> nodeMap = new HashMap<>(); private Map<TIdentifier, Declaration> declarationResolutionMap = new HashMap<>(); private Map<Token, Expression> inlinedExpressionResolutionMap = new HashMap<>(); private Map<TIdentifier, Alternative> alternativeResolutionMap = new HashMap<>(); private Map<PAlternativeReference, AlternativeReference> alternativeReferenceResolutionMap = new HashMap<>(); private Map<PElementReference, ElementReference> elementReferenceResolutionMap = new HashMap<>(); private Map<PElementBody, Type> typeResolutionMap = new HashMap<>(); private Map<PTransformationElement, TransformationElement> transformationElementMap = new HashMap<>(); private NameSpace parserNameSpace = new NameSpace(); private NameSpace treeNameSpace = new NameSpace(); private int nextInternalNameIndex = 1; // Cached values private String name; private Token location; Grammar( AGrammar declaration) { this.declaration = declaration; if (this.nodeMap.containsKey(declaration)) { throw new InternalException("it was already added."); } this.nodeMap.put(declaration, this); this.parserNameSpace.add(this); this.treeNameSpace.add(this); } @Override public String getName() { if (this.name == null) { this.name = getLocation().getText(); } return this.name; } @Override public String getLookupName() { return getName(); } @Override public String getDisplayName() { return getLocation().getText(); } @Override public Token getLocation() { if (this.location == null) { this.location = this.declaration.getName(); } return this.location; } public Expression getExpression( Node declaration) { return (Expression) this.nodeMap.get(declaration); } public Production getProduction( PParserProduction declaration) { return (Production) this.nodeMap.get(declaration); } public Production getProduction( PTreeProduction declaration) { return (Production) this.nodeMap.get(declaration); } public Alternative getAlternative( PAlternative declaration) { return (Alternative) this.nodeMap.get(declaration); } public Element getElement( PElement declaration) { return (Element) this.nodeMap.get(declaration); } public Declaration getDeclarationResolution( TIdentifier identifier) { return this.declarationResolutionMap.get(identifier); } public Expression getExpressionResolution( TIdentifierChar node) { return this.inlinedExpressionResolutionMap.get(node); } public Expression getExpressionResolution( TChar node) { return this.inlinedExpressionResolutionMap.get(node); } public Expression getExpressionResolution( TIdentifierString node) { return this.inlinedExpressionResolutionMap.get(node); } public Expression getExpressionResolution( TString node) { return this.inlinedExpressionResolutionMap.get(node); } public Expression getExpressionResolution( TEndKeyword node) { return this.inlinedExpressionResolutionMap.get(node); } public Alternative getAlternativeResolution( TIdentifier identifier) { return this.alternativeResolutionMap.get(identifier); } public AlternativeReference getAlternativeReferenceResolution( PAlternativeReference alternativeReference) { return this.alternativeReferenceResolutionMap.get(alternativeReference); } public ElementReference getElementReferenceResolution( PElementReference elementReference) { return this.elementReferenceResolutionMap.get(elementReference); } public Type getTypeResolution( PElementBody elementBody) { return this.typeResolutionMap.get(elementBody); } public TransformationElement getTransformationElementResolution( PTransformationElement transformationElement) { return this.transformationElementMap.get(transformationElement); } public Production getTreeProduction( String name) { return (Production) this.treeNameSpace.get(name); } void addExpression( Node declaration) { Expression expression = new Expression(this, declaration); expression.setInternalName(expression.getName()); if (this.nodeMap.containsKey(declaration)) { throw new InternalException("it was already added."); } this.nodeMap.put(declaration, expression); this.parserNameSpace.add(expression); this.treeNameSpace.add(expression); } void addInlinedExpression( Node declaration) { Expression expression = new Expression(this, declaration); String name = expression.getName(); if (name != null) { expression.setInternalName(name); } else { expression.setInternalName("." + this.nextInternalNameIndex++); } Declaration previousDeclaration = this.parserNameSpace.get(expression.getLookupName()); // only add new expression if it's a new declaration or if it redeclares // a normal expression if (previousDeclaration == null || previousDeclaration.getLocation() instanceof TIdentifier) { if (this.nodeMap.containsKey(declaration)) { throw new InternalException("it was already added."); } this.nodeMap.put(declaration, expression); this.parserNameSpace.add(expression); this.treeNameSpace.add(expression); } else { if (this.nodeMap.containsKey(declaration)) { throw new InternalException("it was already added."); } this.nodeMap.put(declaration, previousDeclaration); } } void addProduction( AParserProduction declaration) { Production production = new Production(this, declaration); production.setInternalName(production.getName()); if (this.nodeMap.containsKey(declaration)) { throw new InternalException("it was already added."); } this.nodeMap.put(declaration, production); this.parserNameSpace.add(production); } void addProduction( ATreeProduction declaration) { Production production = new Production(this, declaration); production.setInternalName(production.getName()); if (this.nodeMap.containsKey(declaration)) { throw new InternalException("it was already added."); } this.nodeMap.put(declaration, production); this.treeNameSpace.add(production); } void addAlternative( Production production, AAlternative declaration) { Alternative alternative = new Alternative(this, production, declaration); if (this.nodeMap.containsKey(declaration)) { throw new InternalException("it was already added."); } this.nodeMap.put(declaration, alternative); } void addElement( Alternative alternative, AElement declaration) { Element element = new Element(this, alternative, declaration); if (this.nodeMap.containsKey(declaration)) { throw new InternalException("it was already added."); } this.nodeMap.put(declaration, element); } void resolveExpression( ANameExpression nameExpression) { TIdentifier nameIdentifier = nameExpression.getIdentifier(); String name = nameIdentifier.getText(); Declaration declaration = this.parserNameSpace.get(name); if (declaration == null) { declaration = this.treeNameSpace.get(name); if (declaration == null) { throw SemanticException.semanticError( "No \"" + name + "\" has been declared.", nameIdentifier); } if (!(declaration instanceof Expression)) { throw SemanticException.semanticError( "\"" + name + "\" is not an expression.", nameIdentifier); } throw new InternalException( "an expression must be in both parser and tree name spaces"); } if (!(declaration instanceof Expression)) { throw SemanticException.semanticError( "\"" + name + "\" is not an expression.", nameIdentifier); } if (this.declarationResolutionMap.containsKey(nameIdentifier)) { throw new InternalException("it was already resolved."); } this.declarationResolutionMap.put(nameIdentifier, declaration); } void resolveTreeNameUnit( ANameUnit nameUnit) { TIdentifier nameIdentifier = nameUnit.getIdentifier(); String name = nameIdentifier.getText(); Declaration declaration = this.treeNameSpace.get(name); if (declaration == null) { declaration = this.parserNameSpace.get(name); if (declaration == null) { throw SemanticException.semanticError( "No \"" + name + "\" has been declared.", nameIdentifier); } throw SemanticException.semanticError( "\"" + name + "\" is not a tree production.", nameIdentifier); } if (this.declarationResolutionMap.containsKey(nameIdentifier)) { throw new InternalException("it was already resolved."); } this.declarationResolutionMap.put(nameIdentifier, declaration); } void resolveIdentifierCharUnit( AIdentifierCharUnit identifierCharUnit) { TIdentifierChar identifierChar = identifierCharUnit.getIdentifierChar(); String text = identifierChar.getText(); String name = text.substring(1, text.length() - 1); resolveInlinedExpression(name, identifierChar); } void resolveCharUnit( ACharUnit charUnit) { TChar charToken = charUnit.getChar(); String name = charToken.getText(); resolveInlinedExpression(name, charToken); } void resolveIdentifierStringUnit( AIdentifierStringUnit identifierStringUnit) { TIdentifierString identifierString = identifierStringUnit.getIdentifierString(); String text = identifierString.getText(); String name = text.substring(1, text.length() - 1); resolveInlinedExpression(name, identifierString); } void resolveStringUnit( AStringUnit stringUnit) { TString stringToken = stringUnit.getString(); String name = stringToken.getText(); resolveInlinedExpression(name, stringToken); } void resolveEndUnit( AEndUnit endUnit) { TEndKeyword endKeyword = endUnit.getEndKeyword(); resolveInlinedExpression("end", endKeyword); } void resolveParserIdentifier( TIdentifier identifier) { String name = identifier.getText(); Declaration declaration = this.parserNameSpace.get(name); if (declaration == null) { declaration = this.treeNameSpace.get(name); if (declaration == null) { throw SemanticException.semanticError( "No \"" + name + "\" has been declared.", identifier); } throw SemanticException.semanticError( "\"" + name + "\" is not a parser production.", identifier); } if (!(declaration instanceof Production) && !(declaration instanceof Expression)) { throw SemanticException.semanticError( "\"" + name + "\" is not a production or an expression.", identifier); } if (this.declarationResolutionMap.containsKey(identifier)) { throw new InternalException("it was already resolved."); } this.declarationResolutionMap.put(identifier, declaration); } void resolveTreeIdentifier( TIdentifier identifier) { String name = identifier.getText(); Declaration declaration = this.treeNameSpace.get(name); if (declaration == null) { declaration = this.parserNameSpace.get(name); if (declaration == null) { throw SemanticException.semanticError( "No \"" + name + "\" has been declared.", identifier); } throw SemanticException.semanticError( "\"" + name + "\" is not a tree production.", identifier); } if (!(declaration instanceof Production) && !(declaration instanceof Expression)) { throw SemanticException.semanticError( "\"" + name + "\" is not a production or an expression.", identifier); } if (this.declarationResolutionMap.containsKey(identifier)) { throw new InternalException("it was already resolved."); } this.declarationResolutionMap.put(identifier, declaration); } void resolveAlternativeIdentifiers( Production production, LinkedList<TIdentifier> identifiers) { for (TIdentifier identifier : identifiers) { resolveAlternativeIdentifier(production, identifier); } } void resolveAlternativeIdentifier( Production production, TIdentifier identifier) { String name = identifier.getText(); Alternative alternative = production.getAlternative(name); if (alternative == null) { if (production.hasAlternative(name)) { throw SemanticException.semanticError( "Production \"" + production.getName() + "\" has two \"" + name + "\" alternatives (or more).", identifier); } throw SemanticException.semanticError( "\"" + name + "\" is not an alternative of production \"" + production.getName() + "\".", identifier); } if (this.alternativeResolutionMap.containsKey(identifier)) { throw new InternalException("it was already resolved."); } this.alternativeResolutionMap.put(identifier, alternative); } void resolveAlternativeReference( AUnnamedAlternativeReference alternativeReference) { Production production = (Production) getDeclarationResolution( alternativeReference.getProduction()); Alternative alternative = production.getAlternative(""); if (alternative == null) { throw SemanticException.semanticError( "The alternative name is missing.", alternativeReference.getProduction()); } if (this.alternativeReferenceResolutionMap .containsKey(alternativeReference)) { throw new InternalException("It was already resolved."); } this.alternativeReferenceResolutionMap.put(alternativeReference, AlternativeReference.createDeclaredAlternativeReference(this, alternative, alternativeReference.getProduction())); } void resolveAlternativeReference( ANamedAlternativeReference alternativeReference) { if (this.alternativeReferenceResolutionMap .containsKey(alternativeReference)) { throw new InternalException("It was already resolved."); } this.alternativeReferenceResolutionMap.put(alternativeReference, AlternativeReference.createDeclaredAlternativeReference(this, getAlternativeResolution( alternativeReference.getAlternative()), alternativeReference.getProduction())); } void resolveElementReference( ANaturalElementReference elementReference) { if (this.elementReferenceResolutionMap.containsKey(elementReference)) { throw new InternalException("It was already resolved."); } this.elementReferenceResolutionMap.put(elementReference, ElementReference.createDeclaredElementReference(this, elementReference)); } void resolveElementReference( ATransformedElementReference elementReference) { if (this.elementReferenceResolutionMap.containsKey(elementReference)) { throw new InternalException("It was already resolved."); } this.elementReferenceResolutionMap.put(elementReference, ElementReference.createDeclaredElementReference(this, elementReference)); } void resolveType( PElementBody node) { if (this.typeResolutionMap.containsKey(node)) { throw new InternalException("It was already resolved."); } this.typeResolutionMap.put(node, new Type(this, node)); } void resolveTransformationElement( ANullTransformationElement node) { if (this.transformationElementMap.containsKey(node)) { throw new InternalException("It was already resolved."); } this.transformationElementMap.put(node, TransformationElement .createDeclaredNullTransformationElement(this, node)); } void resolveTransformationElement( AReferenceTransformationElement node) { if (this.transformationElementMap.containsKey(node)) { throw new InternalException("It was already resolved."); } this.transformationElementMap.put(node, TransformationElement .createDeclaredReferenceTransformationElement(this, node)); } void resolveTransformationElement( ADeleteTransformationElement node) { if (this.transformationElementMap.containsKey(node)) { throw new InternalException("It was already resolved."); } this.transformationElementMap.put(node, TransformationElement .createDeclaredDeleteTransformationElement(this, node)); } void resolveTransformationElement( ANewTransformationElement node) { if (this.transformationElementMap.containsKey(node)) { throw new InternalException("It was already resolved."); } this.transformationElementMap.put(node, TransformationElement .createDeclaredNewTransformationElement(this, node)); } void resolveTransformationElement( AListTransformationElement node) { if (this.transformationElementMap.containsKey(node)) { throw new InternalException("It was already resolved."); } this.transformationElementMap.put(node, TransformationElement .createDeclaredListTransformationElement(this, node)); } void resolveTransformationElement( ALeftTransformationElement node) { if (this.transformationElementMap.containsKey(node)) { throw new InternalException("It was already resolved."); } this.transformationElementMap.put(node, TransformationElement .createDeclaredLeftTransformationElement(this, node)); } void resolveTransformationElement( ARightTransformationElement node) { if (this.transformationElementMap.containsKey(node)) { throw new InternalException("It was already resolved."); } this.transformationElementMap.put(node, TransformationElement .createDeclaredRightTransformationElement(this, node)); } private void resolveInlinedExpression( String name, Token location) { Declaration declaration = this.parserNameSpace.get(name); if (declaration == null) { declaration = this.treeNameSpace.get(name); if (declaration == null) { throw SemanticException.semanticError( "No \"" + name + "\" has been declared.", location); } if (!(declaration instanceof Expression)) { throw SemanticException.semanticError( "\"" + name + "\" is not an expression.", location); } throw new InternalException( "an expression must be in both parser and tree name spaces"); } if (!(declaration instanceof Expression)) { throw SemanticException.semanticError( "\"" + name + "\" is not an expression.", location); } if (this.inlinedExpressionResolutionMap.containsKey(location)) { throw new InternalException("it was already resolved."); } this.inlinedExpressionResolutionMap.put(location, (Expression) declaration); } }
/* * Copyright 2015 RandomAltThing (@TheDiamondYT) * * 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 wr iting, 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.mineserver.math; public class Vector3 { public int x = 0; public int y = 0; public int z = 0; public Vector3() {} public Vector3(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public int getX() { return x; } public int getY() { return y; } public int getZ() { return z; } public int getFloorX() { return (int) Math.floor(x); } public int getFloorY() { return (int) Math.floor(y); } public int getFloorZ() { return (int) Math.floor(z); } public int getRight() { return x; } public int getUp() { return y; } public int getForward() { return z; } public int getSouth() { return x; } public int getWest() { return z; } public Vector3 add(int x, int y, int z) { return new Vector3(this.x + x, this.y + y, this.z + z); } public Vector3 subtract(int x, int y, int z) { return add(-x, -y, -z); } public Vector3 multiply(int number) { return new Vector3(x * number, y * number, z * number); } public Vector3 divide(int number) { return new Vector3(x / number, y / number, z / number); } public Vector3 ceil() { return new Vector3((int) Math.ceil(x), (int) Math.ceil(y), (int) Math.ceil(z)); } public Vector3 floor() { return new Vector3((int) Math.floor(x), (int) Math.floor(y), (int) Math.floor(z)); } public Vector3 round() { return new Vector3((int) Math.round(x), (int) Math.round(y), (int) Math.round(z)); } public Vector3 abs() { return new Vector3(Math.abs(x), Math.abs(y), Math.abs(z)); } public Vector3 getSide(int face, int step) { switch((int) face) { case BlockFace.DOWN: return new Vector3(x, y - step, z); case BlockFace.UP: return new Vector3(x, y + step, z); case BlockFace.NORTH: return new Vector3(x, y, z - step); case BlockFace.SOUTH: return new Vector3(x, y, z + step); case BlockFace.WEST: return new Vector3(x - step, y, z); case BlockFace.EAST: return new Vector3(x + step, y, z); default: return this; } } public static int getOppositeSide(int face) { switch((int) face){ case BlockFace.DOWN: return BlockFace.UP; case BlockFace.UP: return BlockFace.DOWN; case BlockFace.NORTH: return BlockFace.SOUTH; case BlockFace.SOUTH: return BlockFace.NORTH; case BlockFace.WEST: return BlockFace.EAST; case BlockFace.EAST: return BlockFace.WEST; default: return -1; } } public double distance(Vector3 pos) { return Math.sqrt(distanceSquared(pos)); } public double distanceSquared(Vector3 pos) { return Math.pow(x - pos.x, 2) + Math.pow(y - pos.y, 2) + Math.pow(z - pos.z, 2); } public int maxPlainDistance(int x, int z) { return Math.max(Math.abs(this.x - x), Math.abs(this.z - z)); } public double length() { return Math.sqrt(lengthSquared()); } public int lengthSquared() { return x * x + y * y + z * z; } public Vector3 normalize() { int len = lengthSquared(); if(len > 0) return divide((int) Math.sqrt(len)); return new Vector3(0, 0, 0); } public int dot(Vector3 v) { return x * v.x + y * v.y + z * v.z; } public Vector3 cross(Vector3 v) { return new Vector3( y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x ); } public boolean equals(Vector3 v) { return x == v.x && y == v.y && z == v.z; } public Vector3 getIntermediateWithXValue(Vector3 v, int x) { int xDiff = v.x - this.x; int yDiff = v.y - y; int zDiff = v.z - z; if((xDiff * xDiff) < 0.0000001) return null; int f = (x - this.x) / xDiff; if(f < 0 || f > 1) return null; else return new Vector3(this.x + xDiff * f, y + yDiff * f, z + zDiff * f); } public Vector3 getIntermediateWithYValue(Vector3 v, int y) { int xDiff = v.x - x; int yDiff = v.y - this.y; int zDiff = v.z - z; if((yDiff * yDiff) < 0.0000001) return null; int f = (y - this.y) / yDiff; if(f < 0 || f > 1) return null; else return new Vector3(x + xDiff * f, this.y + yDiff * f, z + zDiff * f); } public Vector3 getIntermediateWithZValue(Vector3 v, int z){ int xDiff = v.x - x; int yDiff = v.y - y; int zDiff = v.z - this.z; if((zDiff * zDiff) < 0.0000001) return null; int f = (z - this.z) / zDiff; if(f < 0 || f > 1) return null; else return new Vector3(x + xDiff * f, y + yDiff * f, this.z + zDiff * f); } public Vector3 setComponents(int x, int y, int z){ this.x = x; this.y = y; this.z = z; return this; } public String toString(){ return "Vector3(X=" + x + ", Y=" + y + ", Z=" + z + ")"; } }
package org.dbflute.erflute.editor.view.dialog.columngroup; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.dbflute.erflute.Activator; import org.dbflute.erflute.core.DisplayMessages; import org.dbflute.erflute.core.dialog.AbstractDialog; import org.dbflute.erflute.core.widgets.CompositeFactory; import org.dbflute.erflute.editor.model.ERDiagram; import org.dbflute.erflute.editor.model.diagram_contents.not_element.group.ColumnGroup; import org.dbflute.erflute.editor.model.diagram_contents.not_element.group.ColumnGroupSet; import org.dbflute.erflute.editor.model.diagram_contents.not_element.group.CopyColumnGroup; import org.dbflute.erflute.editor.model.diagram_contents.not_element.group.GlobalColumnGroupSet; import org.dbflute.erflute.editor.view.dialog.column.real.GroupColumnDialog; import org.dbflute.erflute.editor.view.dialog.table.ERTableComposite; import org.dbflute.erflute.editor.view.dialog.table.ERTableCompositeHolder; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; /** * @author modified by jflute (originated in ermaster) */ public class ColumnGroupManageDialog extends AbstractDialog implements ERTableCompositeHolder { private static final int HEIGHT = 360; private static final int GROUP_LIST_HEIGHT = 230; private Text groupNameText; private org.eclipse.swt.widgets.List groupList; private Button groupUpdateButton; private Button groupCancelButton; private Button groupAddButton; private Button groupEditButton; private Button groupDeleteButton; private Button addToGlobalGroupButton; private final List<CopyColumnGroup> copyGroups; private int editTargetIndex = -1; private CopyColumnGroup copyData; private final ERDiagram diagram; private final boolean globalGroup; private ERTableComposite tableComposite; public ColumnGroupManageDialog(Shell parentShell, ColumnGroupSet columnGroups, ERDiagram diagram, boolean globalGroup, int editTargetIndex) { super(parentShell, 2); this.copyGroups = new ArrayList<>(); for (final ColumnGroup columnGroup : columnGroups) { copyGroups.add(new CopyColumnGroup(columnGroup)); } this.diagram = diagram; this.globalGroup = globalGroup; this.editTargetIndex = editTargetIndex; } @Override protected void initComponent(Composite composite) { createGroupListComposite(composite); createGroupDetailComposite(composite); setGroupEditEnabled(false); } private void createGroupListComposite(Composite parent) { final GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 3; gridLayout.verticalSpacing = 10; final GridData gridData = new GridData(); gridData.heightHint = HEIGHT; final Composite composite = new Composite(parent, SWT.BORDER); composite.setLayoutData(gridData); composite.setLayout(gridLayout); createGroup(composite); groupAddButton = new Button(composite, SWT.NONE); groupAddButton.setText(DisplayMessages.getMessage("label.button.group.add")); groupEditButton = new Button(composite, SWT.NONE); groupEditButton.setText(DisplayMessages.getMessage("label.button.group.edit")); this.groupDeleteButton = new Button(composite, SWT.NONE); groupDeleteButton.setText(DisplayMessages.getMessage("label.button.group.delete")); this.addToGlobalGroupButton = new Button(composite, SWT.NONE); addToGlobalGroupButton.setText(DisplayMessages.getMessage("label.button.add.to.global.group")); final GridData gridData3 = new GridData(); gridData3.horizontalSpan = 3; addToGlobalGroupButton.setLayoutData(gridData3); if (globalGroup) { addToGlobalGroupButton.setVisible(false); } setButtonEnabled(false); } private void createGroupDetailComposite(Composite parent) { final GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; final GridData gridData = new GridData(); gridData.heightHint = HEIGHT; final Composite composite = new Composite(parent, SWT.BORDER); composite.setLayout(gridLayout); composite.setLayoutData(gridData); this.groupNameText = CompositeFactory.createText(this, composite, "label.group.name", 1, 200, true); final GroupColumnDialog columnDialog = new GroupColumnDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), diagram); this.tableComposite = new ERTableComposite(this, composite, diagram, null, null, columnDialog, this, 2, true, true); createComposite3(composite); } private void createGroup(Composite parent) { final GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 3; final GridData gridData1 = new GridData(); gridData1.horizontalSpan = 3; final GridData gridData2 = new GridData(); gridData2.widthHint = 200; gridData2.horizontalSpan = 3; gridData2.heightHint = GROUP_LIST_HEIGHT; final Group group = new Group(parent, SWT.NONE); group.setText(DisplayMessages.getMessage("label.group.list")); group.setLayoutData(gridData1); group.setLayout(gridLayout); groupList = new org.eclipse.swt.widgets.List(group, SWT.BORDER | SWT.V_SCROLL); groupList.setLayoutData(gridData2); initGroupList(); } private void initGroupList() { Collections.sort(copyGroups); groupList.removeAll(); for (final ColumnGroup columnGroup : copyGroups) { groupList.add(columnGroup.getGroupName()); } } @SuppressWarnings("unchecked") private void initColumnGroup() { String text = copyData.getGroupName(); if (text == null) { text = ""; } groupNameText.setText(text); @SuppressWarnings("rawtypes") final List columns = copyData.getColumns(); // to avoid generic headache tableComposite.setColumnList(columns); } private void setGroupEditEnabled(boolean enabled) { tableComposite.setEnabled(enabled); groupUpdateButton.setEnabled(enabled); groupCancelButton.setEnabled(enabled); groupNameText.setEnabled(enabled); groupList.setEnabled(!enabled); groupAddButton.setEnabled(!enabled); if (groupList.getSelectionIndex() != -1 && !enabled) { setButtonEnabled(true); } else { setButtonEnabled(false); } if (enabled) { groupNameText.setFocus(); } else { groupList.setFocus(); } enabledButton(!enabled); } private void createComposite3(Composite parent) { final GridData gridData = new GridData(); gridData.horizontalSpan = 2; final GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; final Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(gridLayout); composite.setLayoutData(gridData); final GridData gridData1 = new GridData(); gridData1.widthHint = 80; this.groupUpdateButton = new Button(composite, SWT.NONE); groupUpdateButton.setText(DisplayMessages.getMessage("label.button.update")); groupUpdateButton.setLayoutData(gridData1); this.groupCancelButton = new Button(composite, SWT.NONE); groupCancelButton.setText(DisplayMessages.getMessage("label.button.cancel")); groupCancelButton.setLayoutData(gridData1); } @Override protected String getTitle() { if (globalGroup) { return "dialog.title.manage.global.group"; } return "dialog.title.manage.group"; } @Override protected void setupData() { if (isEdit()) { groupList.setSelection(editTargetIndex); this.copyData = new CopyColumnGroup(copyGroups.get(editTargetIndex)); initColumnGroup(); setGroupEditEnabled(true); } } private boolean isEdit() { return this.editTargetIndex != -1; } public List<CopyColumnGroup> getCopyColumnGroups() { return copyGroups; } private void setButtonEnabled(boolean enabled) { groupEditButton.setEnabled(enabled); groupDeleteButton.setEnabled(enabled); addToGlobalGroupButton.setEnabled(enabled); } @Override public void selectGroup(ColumnGroup selectedColumn) { // do nothing } @Override protected void addListener() { super.addListener(); groupAddButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editTargetIndex = -1; copyData = new CopyColumnGroup(new ColumnGroup()); initColumnGroup(); setGroupEditEnabled(true); } }); groupEditButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editTargetIndex = groupList.getSelectionIndex(); if (editTargetIndex == -1) { return; } setGroupEditEnabled(true); } }); groupDeleteButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editTargetIndex = groupList.getSelectionIndex(); if (editTargetIndex == -1) { return; } copyGroups.remove(editTargetIndex); initGroupList(); if (copyGroups.size() == 0) { editTargetIndex = -1; } else if (editTargetIndex >= copyGroups.size()) { editTargetIndex = copyGroups.size() - 1; } if (editTargetIndex != -1) { groupList.setSelection(editTargetIndex); copyData = new CopyColumnGroup(copyGroups.get(editTargetIndex)); initColumnGroup(); } else { copyData = new CopyColumnGroup(new ColumnGroup()); initColumnGroup(); setButtonEnabled(false); } } }); addToGlobalGroupButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { editTargetIndex = groupList.getSelectionIndex(); if (editTargetIndex == -1) { return; } final Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); final MessageBox messageBox = new MessageBox(shell, SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL); messageBox.setText(DisplayMessages.getMessage("label.button.add.to.global.group")); messageBox.setMessage(DisplayMessages.getMessage("dialog.message.add.to.global.group")); if (messageBox.open() == SWT.OK) { final CopyColumnGroup columnGroup = copyGroups.get(editTargetIndex); final ColumnGroupSet columnGroups = GlobalColumnGroupSet.load(); columnGroups.add(columnGroup); GlobalColumnGroupSet.save(columnGroups); } } }); groupList.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent e) { editTargetIndex = groupList.getSelectionIndex(); if (editTargetIndex == -1) { return; } setGroupEditEnabled(true); } }); groupList.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { try { editTargetIndex = groupList.getSelectionIndex(); if (editTargetIndex == -1) { return; } copyData = new CopyColumnGroup(copyGroups.get(editTargetIndex)); initColumnGroup(); setButtonEnabled(true); } catch (final Exception ex) { Activator.showExceptionDialog(ex); } } }); groupUpdateButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { try { if (validate()) { final String text = groupNameText.getText().trim(); copyData.setGroupName(text); if (editTargetIndex == -1) { copyGroups.add(copyData); } else { copyGroups.remove(editTargetIndex); copyData = (CopyColumnGroup) copyData.restructure(null); copyGroups.add(editTargetIndex, copyData); } setGroupEditEnabled(false); initGroupList(); for (int i = 0; i < copyGroups.size(); i++) { final ColumnGroup columnGroup = copyGroups.get(i); if (columnGroup == copyData) { groupList.setSelection(i); copyData = new CopyColumnGroup(copyGroups.get(i)); initColumnGroup(); setButtonEnabled(true); break; } } } } catch (final Exception ex) { Activator.showExceptionDialog(ex); } } }); groupCancelButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setGroupEditEnabled(false); if (editTargetIndex != -1) { copyData = new CopyColumnGroup(copyGroups.get(editTargetIndex)); initColumnGroup(); } } }); } // =================================================================================== // Validation // ========== @Override protected String doValidate() { if (groupNameText.getEnabled()) { final String groupName = groupNameText.getText().trim(); if (groupName.equals("")) { return "error.group.name.empty"; } if (copyGroups != null && !isEdit()) { // just in case for (final CopyColumnGroup existingGroup : copyGroups) { final String existingName = existingGroup.getGroupName(); if (existingName.equalsIgnoreCase(groupName)) { return "The column group name already exists: " + groupName; // #for_erflute } } } } return null; } // =================================================================================== // Perform OK // ========== @Override protected void performOK() { } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.sql.planner.iterative.rule; import com.google.common.collect.ImmutableList; import io.trino.sql.planner.iterative.rule.test.BaseRuleTest; import io.trino.sql.tree.ComparisonExpression; import io.trino.sql.tree.FunctionCall; import io.trino.sql.tree.IfExpression; import io.trino.sql.tree.LongLiteral; import io.trino.sql.tree.QualifiedName; import org.testng.annotations.Test; import static io.trino.sql.planner.assertions.PlanMatchPattern.filter; import static io.trino.sql.planner.assertions.PlanMatchPattern.values; import static io.trino.sql.planner.iterative.rule.test.PlanBuilder.expression; import static io.trino.sql.tree.ComparisonExpression.Operator.EQUAL; public class TestSimplifyFilterPredicate extends BaseRuleTest { @Test public void testSimplifyIfExpression() { // true result iff the condition is true tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("IF(a, true, false)"), p.values(p.symbol("a")))) .matches( filter( "a", values("a"))); // true result iff the condition is true tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("IF(a, true)"), p.values(p.symbol("a")))) .matches( filter( "a", values("a"))); // true result iff the condition is null or false tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("IF(a, false, true)"), p.values(p.symbol("a")))) .matches( filter( "a IS NULL OR NOT a", values("a"))); // true result iff the condition is null or false tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("IF(a, null, true)"), p.values(p.symbol("a")))) .matches( filter( "a IS NULL OR NOT a", values("a"))); // always true tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("IF(a, true, true)"), p.values(p.symbol("a")))) .matches( filter( "true", values("a"))); // always false tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("IF(a, false, false)"), p.values(p.symbol("a")))) .matches( filter( "false", values("a"))); // both results equal tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("IF(a, b > 0, b > 0)"), p.values(p.symbol("a"), p.symbol("b")))) .matches( filter( "b > 0", values("a", "b"))); // both results are equal non-deterministic expressions FunctionCall randomFunction = new FunctionCall( tester().getMetadata().resolveFunction(tester().getSession(), QualifiedName.of("random"), ImmutableList.of()).toQualifiedName(), ImmutableList.of()); tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( new IfExpression( expression("a"), new ComparisonExpression(EQUAL, randomFunction, new LongLiteral("0")), new ComparisonExpression(EQUAL, randomFunction, new LongLiteral("0"))), p.values(p.symbol("a")))) .doesNotFire(); // always null (including the default) -> simplified to FALSE tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("IF(a, null)"), p.values(p.symbol("a")))) .matches( filter( "false", values("a"))); // condition is true -> first branch tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("IF(true, a, NOT a)"), p.values(p.symbol("a")))) .matches( filter( "a", values("a"))); // condition is true -> second branch tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("IF(false, a, NOT a)"), p.values(p.symbol("a")))) .matches( filter( "NOT a", values("a"))); // condition is true, no second branch -> the result is null, simplified to FALSE tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("IF(false, a)"), p.values(p.symbol("a")))) .matches( filter( "false", values("a"))); // not known result (`b`) - cannot optimize tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("IF(a, true, b)"), p.values(p.symbol("a"), p.symbol("b")))) .doesNotFire(); } @Test public void testSimplifyNullIfExpression() { // NULLIF(x, y) returns true if and only if: x != y AND x = true tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("NULLIF(a, b)"), p.values(p.symbol("a"), p.symbol("b")))) .matches( filter( "a AND (b IS NULL OR NOT b)", values("a", "b"))); } @Test public void testSimplifySearchedCaseExpression() { tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE " + " WHEN a < 0 THEN true " + " WHEN a = 0 THEN false " + " WHEN a > 0 THEN true " + " ELSE false " + " END"), p.values(p.symbol("a")))) .doesNotFire(); // all results true tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE " + " WHEN a < 0 THEN true " + " WHEN a = 0 THEN true " + " WHEN a > 0 THEN true " + " ELSE true " + " END"), p.values(p.symbol("a")))) .matches( filter( "true", values("a"))); // all results not true tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE " + " WHEN a < 0 THEN false " + " WHEN a = 0 THEN null " + " WHEN a > 0 THEN false " + " ELSE false " + " END"), p.values(p.symbol("a")))) .matches( filter( "false", values("a"))); // all results not true (including default null result) tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE " + " WHEN a < 0 THEN false " + " WHEN a = 0 THEN null " + " WHEN a > 0 THEN false " + " END"), p.values(p.symbol("a")))) .matches( filter( "false", values("a"))); // one result true, and remaining results not true tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE " + " WHEN a < 0 THEN false " + " WHEN a = 0 THEN null " + " WHEN a > 0 THEN true " + " ELSE false " + " END"), p.values(p.symbol("a")))) .matches( filter( "((a < 0) IS NULL OR NOT (a < 0)) AND ((a = 0) IS NULL OR NOT (a = 0)) AND (a > 0)", values("a"))); // first result true, and remaining results not true tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE " + " WHEN a < 0 THEN true " + " WHEN a = 0 THEN null " + " WHEN a > 0 THEN false " + " ELSE false " + " END"), p.values(p.symbol("a")))) .matches( filter( "a < 0", values("a"))); // all results not true, and default true tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE " + " WHEN a < 0 THEN false " + " WHEN a = 0 THEN null " + " WHEN a > 0 THEN false " + " ELSE true " + " END"), p.values(p.symbol("a")))) .matches( filter( "((a < 0) IS NULL OR NOT (a < 0)) AND ((a = 0) IS NULL OR NOT (a = 0)) AND ((a > 0) IS NULL OR NOT (a > 0))", values("a"))); // all conditions not true - return the default tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE " + " WHEN false THEN a " + " WHEN false THEN a " + " WHEN null THEN a " + " ELSE b " + " END"), p.values(p.symbol("a"), p.symbol("b")))) .matches( filter( "b", values("a", "b"))); // all conditions not true, no default specified - return false tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE " + " WHEN false THEN a " + " WHEN false THEN NOT a " + " WHEN null THEN a " + " END"), p.values(p.symbol("a")))) .matches( filter( "false", values("a"))); // not true conditions preceding true condition - return the result associated with the true condition tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE " + " WHEN false THEN a " + " WHEN null THEN NOT a " + " WHEN true THEN b " + " END"), p.values(p.symbol("a"), p.symbol("b")))) .matches( filter( "b", values("a", "b"))); // remove not true condition and move the result associated with the first true condition to default tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE " + " WHEN false THEN a " + " WHEN b THEN NOT a " + " WHEN true THEN b " + " END"), p.values(p.symbol("a"), p.symbol("b")))) .matches( filter( "CASE WHEN b THEN NOT a ELSE b END", values("a", "b"))); // move the result associated with the first true condition to default tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE " + " WHEN b < 0 THEN a " + " WHEN b > 0 THEN NOT a " + " WHEN true THEN b " + " WHEN true THEN NOT b " + " END"), p.values(p.symbol("a"), p.symbol("b")))) .matches( filter( "CASE " + " WHEN b < 0 THEN a " + " WHEN b > 0 THEN NOT a " + " ELSE b " + " END", values("a", "b"))); // cannot remove any clause tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE " + " WHEN b < 0 THEN a " + " WHEN b > 0 THEN NOT a " + " ELSE b " + " END"), p.values(p.symbol("a"), p.symbol("b")))) .doesNotFire(); } @Test public void testSimplifySimpleCaseExpression() { tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE a" + " WHEN b THEN true " + " WHEN b + 1 THEN false " + " ELSE true " + " END"), p.values(p.symbol("a"), p.symbol("b")))) .doesNotFire(); // comparison with null returns null - no WHEN branch matches, return default value tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE null" + " WHEN null THEN true " + " WHEN a THEN false " + " ELSE b " + " END"), p.values(p.symbol("a"), p.symbol("b")))) .matches( filter( "b", values("a", "b"))); // comparison with null returns null - no WHEN branch matches, the result is default null, simplified to FALSE tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE null" + " WHEN null THEN true " + " WHEN a THEN false " + " END"), p.values(p.symbol("a")))) .matches( filter( "false", values("a"))); // all results true tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE a" + " WHEN b + 1 THEN true " + " WHEN b + 2 THEN true " + " ELSE true " + " END"), p.values(p.symbol("a"), p.symbol("b")))) .matches( filter( "true", values("a", "b"))); // all results not true tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE a" + " WHEN b + 1 THEN false " + " WHEN b + 2 THEN null " + " ELSE false " + " END"), p.values(p.symbol("a"), p.symbol("b")))) .matches( filter( "false", values("a", "b"))); // all results not true (including default null result) tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("CASE a" + " WHEN b + 1 THEN false " + " WHEN b + 2 THEN null " + " END"), p.values(p.symbol("a"), p.symbol("b")))) .matches( filter( "false", values("a", "b"))); } @Test public void testCastNull() { tester().assertThat(new SimplifyFilterPredicate(tester().getMetadata())) .on(p -> p.filter( expression("IF(a, CAST(CAST(CAST(null AS boolean) AS bigint) AS boolean), false)"), p.values(p.symbol("a")))) .matches( filter( "false", values("a"))); } }
/* * 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.ode.daohib.bpel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ode.bpel.dao.BpelDAOConnection; import org.apache.ode.bpel.dao.BpelDAOConnectionFactoryJDBC; import org.apache.ode.daohib.DataSourceConnectionProvider; import org.apache.ode.daohib.HibernateTransactionManagerLookup; import org.apache.ode.daohib.SessionManager; import org.hibernate.HibernateException; import org.hibernate.cfg.Environment; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.DialectFactory; import javax.sql.DataSource; import javax.transaction.TransactionManager; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.util.HashMap; import java.util.Properties; import java.util.Enumeration; /** * Hibernate-based {@link org.apache.ode.bpel.dao.BpelDAOConnectionFactory} * implementation. */ public class BpelDAOConnectionFactoryImpl implements BpelDAOConnectionFactoryJDBC { private static final Log __log = LogFactory .getLog(BpelDAOConnectionFactoryImpl.class); protected SessionManager _sessionManager; private DataSource _ds; private TransactionManager _tm; /** * Constructor. */ public BpelDAOConnectionFactoryImpl() { } public BpelDAOConnection getConnection() { try { return new BpelDAOConnectionImpl(_sessionManager); } catch (HibernateException e) { __log.error("DbError", e); throw e; } } /** * @see org.apache.ode.bpel.dao.BpelDAOConnectionFactory#init(java.util.Properties) */ @SuppressWarnings("unchecked") public void init(Properties initialProps) { if (_ds == null) { String errmsg = "setDataSource() not called!"; __log.fatal(errmsg); throw new IllegalStateException(errmsg); } if (_tm == null) { String errmsg = "setTransactionManager() not called!"; __log.fatal(errmsg); throw new IllegalStateException(errmsg); } if (initialProps == null) initialProps = new Properties(); // Don't want to pollute original properties Properties properties = new Properties(); for (Object prop : initialProps.keySet()) { properties.put(prop, initialProps.get(prop)); } // Note that we don't allow the following properties to be overriden by // the client. if (properties.containsKey(Environment.CONNECTION_PROVIDER)) __log.warn("Ignoring user-specified Hibernate property: " + Environment.CONNECTION_PROVIDER); if (properties.containsKey(Environment.TRANSACTION_MANAGER_STRATEGY)) __log.warn("Ignoring user-specified Hibernate property: " + Environment.TRANSACTION_MANAGER_STRATEGY); if (properties.containsKey(Environment.SESSION_FACTORY_NAME)) __log.warn("Ignoring user-specified Hibernate property: " + Environment.SESSION_FACTORY_NAME); properties.put(Environment.CONNECTION_PROVIDER, DataSourceConnectionProvider.class.getName()); properties.put(Environment.TRANSACTION_MANAGER_STRATEGY, HibernateTransactionManagerLookup.class.getName()); properties.put(Environment.TRANSACTION_STRATEGY, "org.hibernate.transaction.JTATransactionFactory"); properties.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "jta"); // Guess Hibernate dialect if not specified in hibernate.properties if (properties.get(Environment.DIALECT) == null) { try { properties.put(Environment.DIALECT, guessDialect(_ds)); } catch (Exception ex) { String errmsg = "Unable to detect Hibernate dialect!"; if (__log.isDebugEnabled()) __log.debug(errmsg, ex); __log.error(errmsg); } } // Isolation levels override; when you use a ConnectionProvider, this // has no effect String level = System.getProperty("ode.connection.isolation", "2"); properties.put(Environment.ISOLATION, level); if (__log.isDebugEnabled()) { Enumeration names = properties.propertyNames(); __log.debug("Properties passed to Hibernate:"); while (names.hasMoreElements()) { String name = (String) names.nextElement(); __log.debug(name + "=" + properties.getProperty(name)); } } _sessionManager = createSessionManager(properties, _ds, _tm); } protected SessionManager createSessionManager(Properties properties, DataSource ds, TransactionManager tm) { return new SessionManager(properties, ds, tm); } private static final String DEFAULT_HIBERNATE_DIALECT = "org.hibernate.dialect.DerbyDialect"; private static final HashMap<String, DialectFactory.VersionInsensitiveMapper> HIBERNATE_DIALECTS = new HashMap<String, DialectFactory.VersionInsensitiveMapper>(); static { // Hibernate has a nice table that resolves the dialect from the // database // product name, // but doesn't include all the drivers. So this is supplementary, and // some // day in the // future they'll add more drivers and we can get rid of this. // Drivers already recognized by Hibernate: // HSQL Database Engine // DB2/NT // MySQL // PostgreSQL // Microsoft SQL Server Database, Microsoft SQL Server // Sybase SQL Server // Informix Dynamic Server // Oracle 8 and Oracle >8 HIBERNATE_DIALECTS.put("Apache Derby", new DialectFactory.VersionInsensitiveMapper( "org.hibernate.dialect.DerbyDialect")); HIBERNATE_DIALECTS.put("INGRES", new DialectFactory.VersionInsensitiveMapper( "org.hibernate.dialect.IngresDialect")); } public void shutdown() { // Not too much to do for hibernate. } private String guessDialect(DataSource dataSource) throws Exception { String dialect = null; // Open a connection and use that connection to figure out database // product name/version number in order to decide which Hibernate // dialect to use. Connection conn = dataSource.getConnection(); try { DatabaseMetaData metaData = conn.getMetaData(); if (metaData != null) { String dbProductName = metaData.getDatabaseProductName(); int dbMajorVer = metaData.getDatabaseMajorVersion(); __log.info("Using database " + dbProductName + " major version " + dbMajorVer); DialectFactory.DatabaseDialectMapper mapper = HIBERNATE_DIALECTS .get(dbProductName); if (mapper != null) { dialect = mapper.getDialectClass(dbMajorVer); } else { Dialect hbDialect = DialectFactory.determineDialect( dbProductName, dbMajorVer); if (hbDialect != null) dialect = hbDialect.getClass().getName(); } } } finally { conn.close(); } if (dialect == null) { __log.info("Cannot determine hibernate dialect for this database: using the default one."); dialect = DEFAULT_HIBERNATE_DIALECT; } return dialect; } public void setDataSource(DataSource ds) { _ds = ds; } public DataSource getDataSource() { return _ds; } public void setTransactionManager(Object tm) { _tm = (TransactionManager) tm; } public void setUnmanagedDataSource(DataSource ds) { // Hibernate doesn't use this. } }
package com.thaiopensource.relaxng.pattern; import com.thaiopensource.relaxng.parse.BuildException; import com.thaiopensource.relaxng.parse.Context; import com.thaiopensource.relaxng.parse.DataPatternBuilder; import com.thaiopensource.relaxng.parse.Div; import com.thaiopensource.relaxng.parse.ElementAnnotationBuilder; import com.thaiopensource.relaxng.parse.Grammar; import com.thaiopensource.relaxng.parse.GrammarSection; import com.thaiopensource.relaxng.parse.IllegalSchemaException; import com.thaiopensource.relaxng.parse.Include; import com.thaiopensource.relaxng.parse.IncludedGrammar; import com.thaiopensource.relaxng.parse.ParseReceiver; import com.thaiopensource.relaxng.parse.Parseable; import com.thaiopensource.relaxng.parse.ParsedPatternFuture; import com.thaiopensource.relaxng.parse.SchemaBuilder; import com.thaiopensource.relaxng.parse.Scope; import com.thaiopensource.relaxng.parse.SubParseable; import com.thaiopensource.relaxng.parse.SubParser; import com.thaiopensource.util.Localizer; import com.thaiopensource.util.VoidValue; import com.thaiopensource.xml.util.Name; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.DatatypeBuilder; import org.relaxng.datatype.DatatypeException; import org.relaxng.datatype.DatatypeLibrary; import org.relaxng.datatype.DatatypeLibraryFactory; import org.relaxng.datatype.ValidationContext; import org.xml.sax.ErrorHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class SchemaBuilderImpl extends AnnotationsImpl implements ElementAnnotationBuilder<Locator, VoidValue, CommentListImpl>, SchemaBuilder<Pattern, NameClass, Locator, VoidValue, CommentListImpl, AnnotationsImpl> { private final SchemaBuilderImpl parent; private boolean hadError = false; private final SubParser<Pattern, NameClass, Locator, VoidValue, CommentListImpl, AnnotationsImpl> subParser; private final SchemaPatternBuilder pb; private final DatatypeLibraryFactory datatypeLibraryFactory; private final String inheritNs; private final ErrorHandler eh; private final OpenIncludes openIncludes; private final AttributeNameClassChecker attributeNameClassChecker = new AttributeNameClassChecker(); static final Localizer localizer = new Localizer(SchemaBuilderImpl.class); static class OpenIncludes { final String uri; final OpenIncludes parent; OpenIncludes(String uri, OpenIncludes parent) { this.uri = uri; this.parent = parent; } } static public Pattern parse(Parseable<Pattern, NameClass, Locator, VoidValue, CommentListImpl, AnnotationsImpl> parseable, ErrorHandler eh, DatatypeLibraryFactory datatypeLibraryFactory, SchemaPatternBuilder pb, boolean isAttributesPattern) throws IllegalSchemaException, IOException, SAXException { try { SchemaBuilderImpl sb = new SchemaBuilderImpl(parseable, eh, new BuiltinDatatypeLibraryFactory(datatypeLibraryFactory), pb); Pattern pattern = parseable.parse(sb, new RootScope(sb)); if (isAttributesPattern) pattern = sb.wrapAttributesPattern(pattern); return sb.expandPattern(pattern); } catch (BuildException e) { throw unwrapBuildException(e); } } static public PatternFuture installHandlers(ParseReceiver<Pattern, NameClass, Locator, VoidValue, CommentListImpl, AnnotationsImpl> parser, XMLReader xr, ErrorHandler eh, DatatypeLibraryFactory dlf, SchemaPatternBuilder pb) throws SAXException { final SchemaBuilderImpl sb = new SchemaBuilderImpl(parser, eh, new BuiltinDatatypeLibraryFactory(dlf), pb); final ParsedPatternFuture<Pattern> pf = parser.installHandlers(xr, sb, new RootScope(sb)); return new PatternFuture() { public Pattern getPattern(boolean isAttributesPattern) throws IllegalSchemaException, SAXException, IOException { try { Pattern pattern = pf.getParsedPattern(); if (isAttributesPattern) pattern = sb.wrapAttributesPattern(pattern); return sb.expandPattern(pattern); } catch (BuildException e) { throw unwrapBuildException(e); } } }; } static public RuntimeException unwrapBuildException(BuildException e) throws SAXException, IllegalSchemaException, IOException { Throwable t = e.getCause(); if (t instanceof IOException) throw (IOException)t; if (t instanceof RuntimeException) return (RuntimeException)t; if (t instanceof IllegalSchemaException) throw new IllegalSchemaException(); if (t instanceof SAXException) throw (SAXException)t; if (t instanceof Exception) throw new SAXException((Exception)t); throw new SAXException(t.getClass().getName() + " thrown"); } private Pattern wrapAttributesPattern(Pattern pattern) { // XXX where can we get a locator from? return makeElement(makeAnyName(null, null), pattern, null, null); } private Pattern expandPattern(Pattern pattern) throws IllegalSchemaException, BuildException { if (!hadError) { try { pattern.checkRecursion(0); pattern = pattern.expand(pb); pattern.checkRestrictions(Pattern.START_CONTEXT, null, null); if (!hadError) return pattern; } catch (SAXParseException e) { error(e); } catch (SAXException e) { throw new BuildException(e); } catch (RestrictionViolationException e) { if (e.getName() != null) error(e.getMessageId(), NameFormatter.format(e.getName()), e.getLocator()); else if (e.getNamespaceUri() != null) error(e.getMessageId(), e.getNamespaceUri(), e.getLocator()); else error(e.getMessageId(), e.getLocator()); } } throw new IllegalSchemaException(); } private SchemaBuilderImpl(SubParser<Pattern, NameClass, Locator, VoidValue, CommentListImpl, AnnotationsImpl> subParser, ErrorHandler eh, DatatypeLibraryFactory datatypeLibraryFactory, SchemaPatternBuilder pb) { this.parent = null; this.subParser = subParser; this.eh = eh; this.datatypeLibraryFactory = datatypeLibraryFactory; this.pb = pb; this.inheritNs = ""; this.openIncludes = null; } private SchemaBuilderImpl(String inheritNs, String uri, SchemaBuilderImpl parent) { this.parent = parent; this.subParser = parent.subParser; this.eh = parent.eh; this.datatypeLibraryFactory = parent.datatypeLibraryFactory; this.pb = parent.pb; this.inheritNs = parent.resolveInherit(inheritNs); this.openIncludes = new OpenIncludes(uri, parent.openIncludes); } public Pattern makeChoice(List<Pattern> patterns, Locator loc, AnnotationsImpl anno) throws BuildException { int nPatterns = patterns.size(); if (nPatterns <= 0) throw new IllegalArgumentException(); Pattern result = patterns.get(0); for (int i = 1; i < nPatterns; i++) result = pb.makeChoice(result, patterns.get(i)); return result; } public Pattern makeInterleave(List<Pattern> patterns, Locator loc, AnnotationsImpl anno) throws BuildException { int nPatterns = patterns.size(); if (nPatterns <= 0) throw new IllegalArgumentException(); Pattern result = patterns.get(0); for (int i = 1; i < nPatterns; i++) result = pb.makeInterleave(result, patterns.get(i)); return result; } public Pattern makeGroup(List<Pattern> patterns, Locator loc, AnnotationsImpl anno) throws BuildException { int nPatterns = patterns.size(); if (nPatterns <= 0) throw new IllegalArgumentException(); Pattern result = patterns.get(0); for (int i = 1; i < nPatterns; i++) result = pb.makeGroup(result, patterns.get(i)); return result; } public Pattern makeOneOrMore(Pattern p, Locator loc, AnnotationsImpl anno) throws BuildException { return pb.makeOneOrMore(p); } public Pattern makeZeroOrMore(Pattern p, Locator loc, AnnotationsImpl anno) throws BuildException { return pb.makeZeroOrMore(p); } public Pattern makeOptional(Pattern p, Locator loc, AnnotationsImpl anno) throws BuildException { return pb.makeOptional(p); } public Pattern makeList(Pattern p, Locator loc, AnnotationsImpl anno) throws BuildException { return pb.makeList(p, loc); } public Pattern makeMixed(Pattern p, Locator loc, AnnotationsImpl anno) throws BuildException { return pb.makeMixed(p); } public Pattern makeEmpty(Locator loc, AnnotationsImpl anno) { return pb.makeEmpty(); } public Pattern makeNotAllowed(Locator loc, AnnotationsImpl anno) { return pb.makeUnexpandedNotAllowed(); } public Pattern makeText(Locator loc, AnnotationsImpl anno) { return pb.makeText(); } public Pattern makeErrorPattern() { return pb.makeError(); } public NameClass makeErrorNameClass() { return new ErrorNameClass(); } public Pattern makeAttribute(NameClass nc, Pattern p, Locator loc, AnnotationsImpl anno) throws BuildException { String messageId = attributeNameClassChecker.checkNameClass(nc); if (messageId != null) error(messageId, loc); return pb.makeAttribute(nc, p, loc, (anno != null ? anno.defaultValue : null)); } public Pattern makeElement(NameClass nc, Pattern p, Locator loc, AnnotationsImpl anno) throws BuildException { return pb.makeElement(nc, p, loc); } private class DummyDataPatternBuilder implements DataPatternBuilder<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl> { public void addParam(String name, String value, Context context, String ns, Locator loc, AnnotationsImpl anno) throws BuildException { } public void annotation(VoidValue ea) throws BuildException { } public Pattern makePattern(Locator loc, AnnotationsImpl anno) throws BuildException { return pb.makeError(); } public Pattern makePattern(Pattern except, Locator loc, AnnotationsImpl anno) throws BuildException { return pb.makeError(); } } private class ValidationContextImpl implements ValidationContext { private final ValidationContext vc; private final String ns; ValidationContextImpl(ValidationContext vc, String ns) { this.vc = vc; this.ns = ns.length() == 0 ? null : ns; } public String resolveNamespacePrefix(String prefix) { String result = prefix.length() == 0 ? ns : vc.resolveNamespacePrefix(prefix); if (result == INHERIT_NS) { if (inheritNs.length() == 0) return null; return inheritNs; } return result; } public String getBaseUri() { return vc.getBaseUri(); } public boolean isUnparsedEntity(String entityName) { return vc.isUnparsedEntity(entityName); } public boolean isNotation(String notationName) { return vc.isNotation(notationName); } } private class DataPatternBuilderImpl implements DataPatternBuilder<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl> { private final DatatypeBuilder dtb; private final Name dtName; private final List<String> params = new ArrayList<String>(); DataPatternBuilderImpl(DatatypeBuilder dtb, Name dtName) { this.dtb = dtb; this.dtName = dtName; } public void addParam(String name, String value, Context context, String ns, Locator loc, AnnotationsImpl anno) throws BuildException { try { dtb.addParameter(name, value, new ValidationContextImpl(context, ns)); params.add(name); params.add(value); } catch (DatatypeException e) { String detail = e.getMessage(); int pos = e.getIndex(); String displayedParam; if (pos == DatatypeException.UNKNOWN) displayedParam = null; else displayedParam = displayParam(value, pos); if (displayedParam != null) { if (detail != null) error("invalid_param_detail_display", detail, displayedParam, loc); else error("invalid_param_display", displayedParam, loc); } else if (detail != null) error("invalid_param_detail", detail, loc); else error("invalid_param", loc); } } public void annotation(VoidValue ea) throws BuildException { } String displayParam(String value, int pos) { if (pos < 0) pos = 0; else if (pos > value.length()) pos = value.length(); return localizer.message("display_param", value.substring(0, pos), value.substring(pos)); } public Pattern makePattern(Locator loc, AnnotationsImpl anno) throws BuildException { try { return pb.makeData(dtb.createDatatype(), dtName, params); } catch (DatatypeException e) { String detail = e.getMessage(); if (detail != null) error("invalid_params_detail", detail, loc); else error("invalid_params", loc); return pb.makeError(); } } public Pattern makePattern(Pattern except, Locator loc, AnnotationsImpl anno) throws BuildException { try { return pb.makeDataExcept(dtb.createDatatype(), dtName, params, except, loc); } catch (DatatypeException e) { String detail = e.getMessage(); if (detail != null) error("invalid_params_detail", detail, loc); else error("invalid_params", loc); return pb.makeError(); } } } public DataPatternBuilder<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl> makeDataPatternBuilder(String datatypeLibrary, String type, Locator loc) throws BuildException { DatatypeLibrary dl = datatypeLibraryFactory.createDatatypeLibrary(datatypeLibrary); if (dl == null) error("unrecognized_datatype_library", datatypeLibrary, loc); else { try { return new DataPatternBuilderImpl(dl.createDatatypeBuilder(type), new Name(datatypeLibrary, type)); } catch (DatatypeException e) { String detail = e.getMessage(); if (detail != null) error("unsupported_datatype_detail", datatypeLibrary, type, detail, loc); else error("unrecognized_datatype", datatypeLibrary, type, loc); } } return new DummyDataPatternBuilder(); } public Pattern makeValue(String datatypeLibrary, String type, String value, Context context, String ns, Locator loc, AnnotationsImpl anno) throws BuildException { DatatypeLibrary dl = datatypeLibraryFactory.createDatatypeLibrary(datatypeLibrary); if (dl == null) error("unrecognized_datatype_library", datatypeLibrary, loc); else { try { DatatypeBuilder dtb = dl.createDatatypeBuilder(type); try { Datatype dt = dtb.createDatatype(); Object obj = dt.createValue(value, new ValidationContextImpl(context, ns)); if (obj != null) return pb.makeValue(dt, new Name(datatypeLibrary, type), obj, value); error("invalid_value", value, loc); } catch (DatatypeException e) { String detail = e.getMessage(); if (detail != null) error("datatype_requires_param_detail", detail, loc); else error("datatype_requires_param", loc); } } catch (DatatypeException e) { error("unrecognized_datatype", datatypeLibrary, type, loc); } } return pb.makeError(); } static class GrammarImpl implements Grammar<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl>, Div<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl>, IncludedGrammar<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl> { private final SchemaBuilderImpl sb; private final Map<String, RefPattern> defines; private final RefPattern startRef; private final Scope<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl> parent; private GrammarImpl(SchemaBuilderImpl sb, Scope<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl> parent) { this.sb = sb; this.parent = parent; this.defines = new HashMap<String, RefPattern>(); this.startRef = new RefPattern(null); } protected GrammarImpl(SchemaBuilderImpl sb, GrammarImpl g) { this.sb = sb; parent = g.parent; startRef = g.startRef; defines = g.defines; } public Pattern endGrammar(Locator loc, AnnotationsImpl anno) throws BuildException { for (String name : defines.keySet()) { RefPattern rp = defines.get(name); if (rp.getPattern() == null) { sb.error("reference_to_undefined", name, rp.getRefLocator()); rp.setPattern(sb.pb.makeError()); } } Pattern start = startRef.getPattern(); if (start == null) { sb.error("missing_start_element", loc); start = sb.pb.makeError(); } return start; } public void endDiv(Locator loc, AnnotationsImpl anno) throws BuildException { // nothing to do } public Pattern endIncludedGrammar(Locator loc, AnnotationsImpl anno) throws BuildException { return null; } public void define(String name, GrammarSection.Combine combine, Pattern pattern, Locator loc, AnnotationsImpl anno) throws BuildException { define(lookup(name), combine, pattern, loc); } private void define(RefPattern rp, GrammarSection.Combine combine, Pattern pattern, Locator loc) throws BuildException { switch (rp.getReplacementStatus()) { case RefPattern.REPLACEMENT_KEEP: if (combine == null) { if (rp.isCombineImplicit()) { if (rp.getName() == null) sb.error("duplicate_start", loc); else sb.error("duplicate_define", rp.getName(), loc); } else rp.setCombineImplicit(); } else { byte combineType = (combine == COMBINE_CHOICE ? RefPattern.COMBINE_CHOICE : RefPattern.COMBINE_INTERLEAVE); if (rp.getCombineType() != RefPattern.COMBINE_NONE && rp.getCombineType() != combineType) { if (rp.getName() == null) sb.error("conflict_combine_start", loc); else sb.error("conflict_combine_define", rp.getName(), loc); } rp.setCombineType(combineType); } if (rp.getPattern() == null) rp.setPattern(pattern); else if (rp.getCombineType() == RefPattern.COMBINE_INTERLEAVE) rp.setPattern(sb.pb.makeInterleave(rp.getPattern(), pattern)); else rp.setPattern(sb.pb.makeChoice(rp.getPattern(), pattern)); break; case RefPattern.REPLACEMENT_REQUIRE: rp.setReplacementStatus(RefPattern.REPLACEMENT_IGNORE); break; case RefPattern.REPLACEMENT_IGNORE: break; } } public void topLevelAnnotation(VoidValue ea) throws BuildException { } public void topLevelComment(CommentListImpl comments) throws BuildException { } private RefPattern lookup(String name) { if (name == START) return startRef; return lookup1(name); } private RefPattern lookup1(String name) { RefPattern p = defines.get(name); if (p == null) { p = new RefPattern(name); defines.put(name, p); } return p; } public Pattern makeRef(String name, Locator loc, AnnotationsImpl anno) throws BuildException { RefPattern p = lookup1(name); if (p.getRefLocator() == null && loc != null) p.setRefLocator(loc); return p; } public Pattern makeParentRef(String name, Locator loc, AnnotationsImpl anno) throws BuildException { if (parent == null) { sb.error("parent_ref_outside_grammar", loc); return sb.makeErrorPattern(); } return parent.makeRef(name, loc, anno); } public Div<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl> makeDiv() { return this; } public Include<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl> makeInclude() { return new IncludeImpl(sb, this); } } static class RootScope implements Scope<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl> { private final SchemaBuilderImpl sb; RootScope(SchemaBuilderImpl sb) { this.sb = sb; } public Pattern makeParentRef(String name, Locator loc, AnnotationsImpl anno) throws BuildException { sb.error("parent_ref_outside_grammar", loc); return sb.makeErrorPattern(); } public Pattern makeRef(String name, Locator loc, AnnotationsImpl anno) throws BuildException { sb.error("ref_outside_grammar", loc); return sb.makeErrorPattern(); } } static class Override { Override(RefPattern prp, Override next) { this.prp = prp; this.next = next; } final RefPattern prp; final Override next; byte replacementStatus; } private static class IncludeImpl implements Include<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl>, Div<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl> { private final SchemaBuilderImpl sb; private Override overrides; private final GrammarImpl grammar; private IncludeImpl(SchemaBuilderImpl sb, GrammarImpl grammar) { this.sb = sb; this.grammar = grammar; } public void define(String name, GrammarSection.Combine combine, Pattern pattern, Locator loc, AnnotationsImpl anno) throws BuildException { RefPattern rp = grammar.lookup(name); overrides = new Override(rp, overrides); grammar.define(rp, combine, pattern, loc); } public void endDiv(Locator loc, AnnotationsImpl anno) throws BuildException { // nothing to do } public void topLevelAnnotation(VoidValue ea) throws BuildException { // nothing to do } public void topLevelComment(CommentListImpl comments) throws BuildException { } public Div<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl> makeDiv() { return this; } public void endInclude(String href, String base, String ns, Locator loc, AnnotationsImpl anno) throws BuildException { SubParseable<Pattern, NameClass, Locator, VoidValue, CommentListImpl, AnnotationsImpl> subParseable = sb.subParser.createSubParseable(href, base); String uri = subParseable.getUri(); for (OpenIncludes inc = sb.openIncludes; inc != null; inc = inc.parent) { if (inc.uri.equals(uri)) { sb.error("recursive_include", uri, loc); return; } } for (Override o = overrides; o != null; o = o.next) { o.replacementStatus = o.prp.getReplacementStatus(); o.prp.setReplacementStatus(RefPattern.REPLACEMENT_REQUIRE); } try { SchemaBuilderImpl isb = new SchemaBuilderImpl(ns, uri, sb); subParseable.parseAsInclude(isb, new GrammarImpl(isb, grammar)); for (Override o = overrides; o != null; o = o.next) { if (o.prp.getReplacementStatus() == RefPattern.REPLACEMENT_REQUIRE) { if (o.prp.getName() == null) sb.error("missing_start_replacement", loc); else sb.error("missing_define_replacement", o.prp.getName(), loc); } } } catch (IllegalSchemaException e) { sb.noteError(); } finally { for (Override o = overrides; o != null; o = o.next) o.prp.setReplacementStatus(o.replacementStatus); } } public Include<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl> makeInclude() { return null; } } public Grammar<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl> makeGrammar(Scope<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl> parent) { return new GrammarImpl(this, parent); } public Pattern makeExternalRef(String href, String base, String ns, Scope<Pattern, Locator, VoidValue, CommentListImpl, AnnotationsImpl> scope, Locator loc, AnnotationsImpl anno) throws BuildException { SubParseable<Pattern, NameClass, Locator, VoidValue, CommentListImpl, AnnotationsImpl> subParseable = subParser.createSubParseable(href, base); String uri = subParseable.getUri(); for (OpenIncludes inc = openIncludes; inc != null; inc = inc.parent) { if (inc.uri.equals(uri)) { error("recursive_include", uri, loc); return pb.makeError(); } } try { return subParseable.parse(new SchemaBuilderImpl(ns, uri, this), scope); } catch (IllegalSchemaException e) { noteError(); return pb.makeError(); } } public NameClass makeNameClassChoice(List<NameClass> nameClasses, Locator loc, AnnotationsImpl anno) { int nNameClasses = nameClasses.size(); if (nNameClasses <= 0) throw new IllegalArgumentException(); NameClass result = nameClasses.get(0); for (int i = 1; i < nNameClasses; i++) result = new ChoiceNameClass(result, nameClasses.get(i)); return result; } public NameClass makeName(String ns, String localName, String prefix, Locator loc, AnnotationsImpl anno) { return new SimpleNameClass(new Name(resolveInherit(ns), localName)); } public NameClass makeNsName(String ns, Locator loc, AnnotationsImpl anno) { return new NsNameClass(resolveInherit(ns)); } public NameClass makeNsName(String ns, NameClass except, Locator loc, AnnotationsImpl anno) { return new NsNameExceptNameClass(resolveInherit(ns), except); } public NameClass makeAnyName(Locator loc, AnnotationsImpl anno) { return new AnyNameClass(); } public NameClass makeAnyName(NameClass except, Locator loc, AnnotationsImpl anno) { return new AnyNameExceptNameClass(except); } public AnnotationsImpl makeAnnotations(CommentListImpl comments, Context context) { return new AnnotationsImpl(); } public VoidValue makeElementAnnotation() throws BuildException { return VoidValue.VOID; } public void addText(String value, Locator loc, CommentListImpl comments) throws BuildException { } public ElementAnnotationBuilder<Locator, VoidValue, CommentListImpl> makeElementAnnotationBuilder(String ns, String localName, String prefix, Locator loc, CommentListImpl comments, Context context) { return this; } public CommentListImpl makeCommentList() { return this; } public boolean usesComments() { return false; } public Pattern annotatePattern(Pattern p, AnnotationsImpl anno) throws BuildException { return p; } public NameClass annotateNameClass(NameClass nc, AnnotationsImpl anno) throws BuildException { return nc; } public Pattern annotateAfterPattern(Pattern p, VoidValue e) throws BuildException { return p; } public NameClass annotateAfterNameClass(NameClass nc, VoidValue e) throws BuildException { return nc; } public Pattern commentAfterPattern(Pattern p, CommentListImpl comments) throws BuildException { return p; } public NameClass commentAfterNameClass(NameClass nc, CommentListImpl comments) throws BuildException { return nc; } private String resolveInherit(String ns) { if (ns == INHERIT_NS) return inheritNs; return ns; } private class LocatorImpl implements Locator { private final String systemId; private final int lineNumber; private final int columnNumber; private LocatorImpl(String systemId, int lineNumber, int columnNumber) { this.systemId = systemId; this.lineNumber = lineNumber; this.columnNumber = columnNumber; } public String getPublicId() { return null; } public String getSystemId() { return systemId; } public int getLineNumber() { return lineNumber; } public int getColumnNumber() { return columnNumber; } } public Locator makeLocation(String systemId, int lineNumber, int columnNumber) { return new LocatorImpl(systemId, lineNumber, columnNumber); } private void error(SAXParseException message) throws BuildException { noteError(); try { if (eh != null) eh.error(message); } catch (SAXException e) { throw new BuildException(e); } } /* private void warning(SAXParseException message) throws BuildException { try { if (eh != null) eh.warning(message); } catch (SAXException e) { throw new BuildException(e); } } */ private void error(String key, Locator loc) throws BuildException { error(new SAXParseException(localizer.message(key), loc)); } private void error(String key, String arg, Locator loc) throws BuildException { error(new SAXParseException(localizer.message(key, arg), loc)); } private void error(String key, String arg1, String arg2, Locator loc) throws BuildException { error(new SAXParseException(localizer.message(key, arg1, arg2), loc)); } private void error(String key, String arg1, String arg2, String arg3, Locator loc) throws BuildException { error(new SAXParseException(localizer.message(key, new Object[]{arg1, arg2, arg3}), loc)); } private void noteError() { if (!hadError && parent != null) parent.noteError(); hadError = true; } }
/** * Copyright 2012 Netflix, 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.netflix.frigga; import com.netflix.frigga.conventions.labeledvariables.LabeledVariables; import com.netflix.frigga.conventions.labeledvariables.LabeledVariablesNamingConvention; import com.netflix.frigga.conventions.labeledvariables.LabeledVariablesNamingResult; import com.netflix.frigga.extensions.NamingConvention; import java.util.Objects; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Class that can deconstruct information about AWS Auto Scaling Groups, Load Balancers, Launch Configurations, and * Security Groups created by Asgard based on their name. */ public class Names { private static final Pattern PUSH_PATTERN = Pattern.compile( "^([" + NameConstants.NAME_HYPHEN_CHARS + "]*)-(" + NameConstants.PUSH_FORMAT + ")$"); private static final Pattern NAME_PATTERN = Pattern.compile( "^([" + NameConstants.NAME_CHARS + "]+)(?:-([" + NameConstants.NAME_CHARS + "]*)(?:-([" + NameConstants.NAME_HYPHEN_CHARS + "]*?))?)?$"); private static final LabeledVariablesNamingConvention LABELED_VARIABLES_CONVENTION = new LabeledVariablesNamingConvention(); private final String group; private final String cluster; private final String app; private final String stack; private final String detail; private final String push; private final Integer sequence; private final AtomicReference<LabeledVariablesNamingResult> labeledVariables = new AtomicReference<>(); protected Names(String name) { String group = null; String cluster = null; String app = null; String stack = null; String detail = null; String push = null; Integer sequence = null; if (name != null && !name.trim().isEmpty()) { Matcher pushMatcher = PUSH_PATTERN.matcher(name); boolean hasPush = pushMatcher.matches(); String theCluster = hasPush ? pushMatcher.group(1) : name; Matcher nameMatcher = NAME_PATTERN.matcher(theCluster); if (nameMatcher.matches()) { group = name; cluster = theCluster; push = hasPush ? pushMatcher.group(2) : null; String sequenceString = hasPush ? pushMatcher.group(3) : null; if (sequenceString != null) { sequence = Integer.parseInt(sequenceString); } app = nameMatcher.group(1); stack = checkEmpty(nameMatcher.group(2)); detail = checkEmpty(nameMatcher.group(3)); } } this.group = group; this.cluster = cluster; this.app = app; this.stack = stack; this.detail = detail; this.push = push; this.sequence = sequence; } /** * Breaks down the name of an auto scaling group, security group, or load balancer created by Asgard into its * component parts. * * @param name the name of an auto scaling group, security group, or load balancer * @return bean containing the component parts of the compound name */ public static Names parseName(String name) { return new Names(name); } private String checkEmpty(String input) { return (input != null && !input.isEmpty()) ? input : null; } public String getGroup() { return group; } public String getCluster() { return cluster; } public String getApp() { return app; } public String getStack() { return stack; } public String getDetail() { return detail; } public String getPush() { return push; } public Integer getSequence() { return sequence; } public String getCountries() { return getLabeledVariable(LabeledVariables::getCountries); } public String getDevPhase() { return getLabeledVariable(LabeledVariables::getDevPhase); } public String getHardware() { return getLabeledVariable(LabeledVariables::getHardware); } public String getPartners() { return getLabeledVariable(LabeledVariables::getPartners); } public String getRevision() { return getLabeledVariable(LabeledVariables::getRevision); } public String getUsedBy() { return getLabeledVariable(LabeledVariables::getUsedBy); } public String getRedBlackSwap() { return getLabeledVariable(LabeledVariables::getRedBlackSwap); } public String getZone() { return getLabeledVariable(LabeledVariables::getZone); } private <T> T getLabeledVariable(Function<LabeledVariables, T> extractor) { LabeledVariablesNamingResult result = labeledVariables.get(); if (result == null) { LabeledVariablesNamingResult applied = LABELED_VARIABLES_CONVENTION.extractNamingConvention(cluster); if (labeledVariables.compareAndSet(null, applied)) { result = applied; } else { result = labeledVariables.get(); } } return result.getResult().map(extractor).orElse(null); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Names names = (Names) o; return Objects.equals(group, names.group); } @Override public int hashCode() { return Objects.hash(group); } @Override public String toString() { return "Names{" + "group='" + group + '\'' + ", cluster='" + cluster + '\'' + ", app='" + app + '\'' + ", stack='" + stack + '\'' + ", detail='" + detail + '\'' + ", push='" + push + '\'' + ", sequence=" + sequence + '}'; } }
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sample.actuator; import java.util.Arrays; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import static org.assertj.core.api.Assertions.assertThat; /** * Basic integration tests for service demo application. * * @author Dave Syer * @author Stephane Nicoll */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) class SampleActuatorApplicationTests { @Autowired private TestRestTemplate restTemplate; @Autowired private ApplicationContext applicationContext; @Test void testHomeIsSecure() { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = this.restTemplate.getForEntity("/", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); assertThat(body.get("error")).isEqualTo("Unauthorized"); assertThat(entity.getHeaders()).doesNotContainKey("Set-Cookie"); } @Test void testMetricsIsSecure() { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = this.restTemplate.getForEntity("/actuator/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); entity = this.restTemplate.getForEntity("/actuator/metrics/", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); entity = this.restTemplate.getForEntity("/actuator/metrics/foo", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); entity = this.restTemplate.getForEntity("/actuator/metrics.json", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); } @Test void testHome() { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = this.restTemplate .withBasicAuth("user", getPassword()).getForEntity("/", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); assertThat(body.get("message")).isEqualTo("Hello Phil"); } @SuppressWarnings("unchecked") @Test void testMetrics() { testHome(); // makes sure some requests have been made @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = this.restTemplate .withBasicAuth("user", getPassword()) .getForEntity("/actuator/metrics", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); Map<String, Object> body = entity.getBody(); assertThat(body).containsKey("names"); assertThat((List<String>) body.get("names")).contains("jvm.buffer.count"); } @Test void testEnv() { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = this.restTemplate .withBasicAuth("user", getPassword()) .getForEntity("/actuator/env", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); assertThat(body).containsKey("propertySources"); } @Test void healthInsecureByDefault() { ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/health", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("\"status\":\"UP\""); assertThat(entity.getBody()).doesNotContain("\"hello\":\"1\""); } @Test void infoInsecureByDefault() { ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/info", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()) .contains("\"artifact\":\"spring-boot-sample-actuator\""); assertThat(entity.getBody()).contains("\"someKey\":\"someValue\""); assertThat(entity.getBody()).contains("\"java\":{", "\"source\":\"1.8\"", "\"target\":\"1.8\""); assertThat(entity.getBody()).contains("\"encoding\":{", "\"source\":\"UTF-8\"", "\"reporting\":\"UTF-8\""); } @Test void testErrorPage() { ResponseEntity<String> entity = this.restTemplate .withBasicAuth("user", getPassword()).getForEntity("/foo", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); String body = entity.getBody(); assertThat(body).contains("\"error\":"); } @Test void testHtmlErrorPage() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); HttpEntity<?> request = new HttpEntity<Void>(headers); ResponseEntity<String> entity = this.restTemplate .withBasicAuth("user", getPassword()) .exchange("/foo", HttpMethod.GET, request, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); String body = entity.getBody(); assertThat(body).as("Body was null").isNotNull(); assertThat(body).contains("This application has no explicit mapping for /error"); } @Test void testErrorPageDirectAccess() { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = this.restTemplate .withBasicAuth("user", getPassword()).getForEntity("/error", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); assertThat(body.get("error")).isEqualTo("None"); assertThat(body.get("status")).isEqualTo(999); } @Test @SuppressWarnings("unchecked") public void testBeans() { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = this.restTemplate .withBasicAuth("user", getPassword()) .getForEntity("/actuator/beans", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).containsOnlyKeys("contexts"); } @SuppressWarnings("unchecked") @Test void testConfigProps() { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = this.restTemplate .withBasicAuth("user", getPassword()) .getForEntity("/actuator/configprops", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); Map<String, Object> body = entity.getBody(); Map<String, Object> contexts = (Map<String, Object>) body.get("contexts"); Map<String, Object> context = (Map<String, Object>) contexts .get(this.applicationContext.getId()); Map<String, Object> beans = (Map<String, Object>) context.get("beans"); assertThat(beans) .containsKey("spring.datasource-" + DataSourceProperties.class.getName()); } private String getPassword() { return "password"; } }
package net.ssehub.easy.reasoning.core.reasoner; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Set; import net.ssehub.easy.basics.messages.Status; import net.ssehub.easy.varModel.confModel.DisplayNameProvider; import net.ssehub.easy.varModel.confModel.IDecisionVariable; import net.ssehub.easy.varModel.cst.ConstraintSyntaxTree; import net.ssehub.easy.varModel.management.CommentResource; import net.ssehub.easy.varModel.management.ModelCommentsPersistencer; import net.ssehub.easy.varModel.model.AbstractVariable; import net.ssehub.easy.varModel.model.Constraint; import net.ssehub.easy.varModel.model.ModelElement; import net.ssehub.easy.varModel.model.Project; import net.ssehub.easy.varModel.model.datatypes.TypeQueries; import net.ssehub.easy.varModel.persistency.StringProvider; /** * Part of the {@link ReasoningResult} class, expressing on error/warning of a complete {@link ReasoningResult}. Takes * a series of lists, which shall be consistent in size. Complex textual representations are calculated on demand * when requesting the respective information (rather than calculating this without need beforehand in a reasoner). * * @author El-Sharkawy * @author Sizonenko */ public class Message extends net.ssehub.easy.basics.messages.Message { // TODO refactor to a single, consistent list of entries. Left it for compatibility private List<ModelElement> conflictingElements; private List<Set<AbstractVariable>> variablesInConstraints; private List<Set<IDecisionVariable>> problemVariables; private List<ConstraintSyntaxTree> problemConstraintParts = new ArrayList<ConstraintSyntaxTree>(); private List<Constraint> problemConstraints; private List<Project> conflictingElementProjects; private List<SuggestionType> conflictingElementSuggestions; private List<IDecisionVariable> constraintVariables; private List<Integer> errorClassification; /** * Defines supported suggestion types. Please check {@link Message#getConflictSuggestions()} for turning them * into text. * * @author Holger Eichelberger */ public enum SuggestionType { PROBLEM_POINTS, REASSIGNMENT } /** * Sole constructor for multiple conflicting elements. * @param explanation A textual representation of this message * @param conflictingElements A list of model elements which lead to the current message, or <tt>null</tt> * @param status The status of this message, e. g. Error or Warning */ public Message(String explanation, List<ModelElement> conflictingElements, Status status) { super(explanation, status); // Avoid NullpointerExceptions this.conflictingElements = new ArrayList<ModelElement>(); if (null != conflictingElements) { this.conflictingElements.addAll(conflictingElements); } } /** * Creates a list with on element. * * @param element the element to put into the list * @return the list with <code>element</code> as member if <code><b>null</b> != element</code>, <b>null</b> else */ public static final List<ModelElement> createList(ModelElement element) { List<ModelElement> result; if (null != element) { result = new ArrayList<ModelElement>(); result.add(element); } else { result = null; } return result; } /** * Returns the list of conflicting items. * @return The list of conflicting items */ public List<ModelElement> getConflicts() { return conflictingElements; } /** * Returns the number of conflicting elements. * @return Number of conflicting elements. */ public int getConflictsCount() { return conflictingElements.size(); } /** * Returns the minimum of the three given integer values. * * @param v1 the first value * @param v2 the second value * @param v3 the third value * @return the minimum of the three given integer values */ private static int min(int v1, int v2, int v3) { return Math.min(Math.min(v1, v2), v3); } /** * Returns the minimum of the four given integer values. * * @param v1 the first value * @param v2 the second value * @param v3 the third value * @param v4 the fourth value * @return the minimum of the four given integer values */ private static int min(int v1, int v2, int v3, int v4) { return Math.min(Math.min(v1, v2), Math.min(v3, v4)); } /** * Returns the list of conflicting item labels. * * @return The list of conflicting item labels. The number of entries depends on the minimum number of * conflicting element suggestions, conflicting elements, constraint variables and variables in constraints. */ public List<String> getConflictLabels() { List<String> result; if (null == conflictingElementSuggestions) { result = null; } else { result = new ArrayList<String>(); for (int i = 0, n = min(conflictingElementSuggestions.size(), conflictingElements.size(), constraintVariables.size(), variablesInConstraints.size()); i < n; i++) { String text; switch (conflictingElementSuggestions.get(i)) { case PROBLEM_POINTS: text = toString(conflictingElements.get(i), constraintVariables.get(i)) + " Please check: " + problemPointsToString(variablesInConstraints.get(i)); break; case REASSIGNMENT: text = toString(conflictingElements.get(i), null); break; default: text = "none"; break; } result.add(text); } } return result; } /** * Returns the list of conflicting item comments. * * @return The list of conflicting item comments. The number of entries depends on the minimum number of * conflicting element suggestions, conflicting elements, and constraint variables. */ public List<String> getConflictComments() { List<String> result; if (null == conflictingElementSuggestions) { result = null; } else { result = new ArrayList<String>(); for (int i = 0, n = min(conflictingElementSuggestions.size(), conflictingElements.size(), constraintVariables.size()); i < n; i++) { String text; switch (conflictingElementSuggestions.get(i)) { case PROBLEM_POINTS: text = toString(conflictingElements.get(i), constraintVariables.get(i)); break; case REASSIGNMENT: text = toString(conflictingElements.get(i), null); break; default: text = "none"; break; } result.add(text); } } return result; } /** * Turns a constraint into a string representation. If a named variable is given, use comment or name instead. * * @param constraint the constraint * @param namedVariable the related named variable (may be <b>null</b>) * @return the string representation */ private String toString(Constraint constraint, IDecisionVariable namedVariable) { String result = ""; if (namedVariable != null) { AbstractVariable decl = namedVariable.getDeclaration(); if (TypeQueries.isConstraint(decl.getType())) { String comment = decl.getComment(); if (null == comment) { result = decl.getName(); } else { result = decl.getComment(); } } } if (noResult(result)) { result = constraint.getComment(); if (noResult(result)) { CommentResource cr = null; try { cr = ModelCommentsPersistencer.getComments(constraint.getProject()); } catch (IOException e) { } result = CommentResourceVisitor.visit(constraint, cr); } } return result; } private static boolean noResult(String result) { return null == result || result.length() == 0; } /** * Turns a model element into a string representation. Considers {@link DisplayNameProvider} and * {@link #toString(Constraint, IDecisionVariable)}. * * @param elt the element to be turned into a string representation * @param namedVariable the related named variable (may be <b>null</b>) * @return the string representation */ private String toString(ModelElement elt, IDecisionVariable namedVariable) { String result; if (elt instanceof AbstractVariable) { result = DisplayNameProvider.getInstance().getDisplayName((AbstractVariable) elt); } else if (elt instanceof IDecisionVariable) { result = DisplayNameProvider.getInstance().getDisplayName((IDecisionVariable) elt); } else if (elt instanceof Constraint) { result = toString((Constraint) elt, namedVariable); } else { result = elt.getName(); } return result + " (" + traceToTop(elt) + " )"; } /** * Method for creating a msg of trace to the top element * of constraint or variable that fail in the reasoning. * @param element Constraint of Variable. * @return text text of the trace. */ private String traceToTop(ModelElement element) { String text = ""; if (element.getParent() != null) { text = " -> " + element.getParent().getName(); ModelElement mElement = (ModelElement) element.getParent(); text = text + traceToTop(mElement); } return text; } /** * Method for adding conflicting element Suggestions. * @param conflictingElementSuggestions conflicting element Suggestions. */ public void addConflictingElementSuggestions(List<SuggestionType> conflictingElementSuggestions) { this.conflictingElementSuggestions = new ArrayList<SuggestionType>(); if (null != conflictingElementSuggestions) { this.conflictingElementSuggestions.addAll(conflictingElementSuggestions); } } /** * Returns the list of conflicting item suggestion types. * @return The list of conflicting item suggestion types. */ public List<SuggestionType> getConflictSuggestionTypes() { return conflictingElementSuggestions; } /** * Returns the list of conflicting item Suggestions. * * @return The list of conflicting item Suggestions. The number of entries depends on the minimum number of * conflicting element suggestions and variables in constraints. */ public List<String> getConflictSuggestions() { List<String> result; if (null == conflictingElementSuggestions) { result = null; } else { result = new ArrayList<String>(); for (int i = 0, n = Math.min(conflictingElementSuggestions.size(), variablesInConstraints.size()); i < n; i++) { String text; switch (conflictingElementSuggestions.get(i)) { case PROBLEM_POINTS: text = "Please check: " + problemPointsToString(variablesInConstraints.get(i)); break; case REASSIGNMENT: text = "Check for variable reassignments in the same Project scope"; break; default: text = "none"; break; } result.add(text); } } return result; } /** * Turns given variables into a problem points description. * * @param vars the variables * @return the description */ private String problemPointsToString(java.util.Set<AbstractVariable> vars) { String problemPoints = ""; int count = 0; for (AbstractVariable variable : vars) { if (count > 0) { if (count == vars.size() - 1) { problemPoints += " or "; } else { problemPoints += ", "; } } String displayVarName = DisplayNameProvider.getInstance().getDisplayName(variable); String displayParentName = DisplayNameProvider.getInstance().getParentNames(variable); if (displayParentName != null) { problemPoints = problemPoints + "\"" + displayVarName + "\" in " + displayParentName; } else { problemPoints = problemPoints + "\"" + displayVarName + "\""; } count++; } return problemPoints; } /** * Method for adding conflicting element Projects. * @param conflictingElementProjects conflicting element Projects. */ public void addConflictingElementProjects(List<Project> conflictingElementProjects) { this.conflictingElementProjects = new ArrayList<Project>(); if (null != conflictingElementProjects) { this.conflictingElementProjects.addAll(conflictingElementProjects); } } /** * Returns the list of conflicting item Projects. * @return The list of conflicting item Projects. */ public List<Project> getConflictProjects() { return conflictingElementProjects; } /** * Method for adding a list of {@link AbstractVariable}s that are involved in each failed constraint. * @param variables List of variables. */ public void addConstraintVariables(List<Set<AbstractVariable>> variables) { this.variablesInConstraints = new ArrayList<Set<AbstractVariable>>(); if (null != variablesInConstraints) { this.variablesInConstraints.addAll(variables); } } /** * Method for returning a list of {@link AbstractVariable}s that are involved in each failed constraint. * @return List of variables. */ public List<Set<AbstractVariable>> getConstraintVariables() { return variablesInConstraints; } /** * Method for adding a list of {@link IDecisionVariable}s that are involved in each failed constraint. * @param variables List of variables. */ public void addProblemVariables(List<Set<IDecisionVariable>> variables) { this.problemVariables = new ArrayList<Set<IDecisionVariable>>(); if (null != problemVariables) { this.problemVariables.addAll(variables); } } /** * Method for returning a list of {@link IDecisionVariable}s that are involved in each failed constraint. * @return List of variables. */ public List<Set<IDecisionVariable>> getProblemVariables() { return problemVariables; } /** * Method for adding a list of partial {@link ConstraintSyntaxTree}s that are involved in each failed constraint. * @param constraints List of constraint trees (elements may be <tt>null</tt>). The entries in this * list must correspond to {@link #addProblemConstraints(List)}. */ public void addProblemConstraintParts(List<ConstraintSyntaxTree> constraints) { if (null != constraints) { this.problemConstraintParts.addAll(constraints); } } /** * Method for adding a list of {@link Constraint}s that are involved in each failed constraint. The entries in this * list must correspond to {@link #addProblemConstraintParts(List)}. * @param constraints List of constraints. */ public void addProblemConstraints(List<Constraint> constraints) { this.problemConstraints = new ArrayList<Constraint>(); if (null != problemConstraints) { this.problemConstraints.addAll(constraints); } } /** * Method for returning a list of partial {@link ConstraintSyntaxTree}s that are involved in each failed constraint. * The result must correspond to {@link #getProblemConstraints()}. * @return List of constraint syntax trees. */ public List<ConstraintSyntaxTree> getProblemConstraintParts() { return problemConstraintParts; } /** * Method for returning a list of full {@link Constraint}s that are involved in each failed constraint. * The result must correspond to {@link #getProblemConstraintParts()}. * @return List of constraints. */ public List<Constraint> getProblemConstraints() { return problemConstraints; } /** * Method for adding a list of ConstraintVariables of a failed constraint. Null if non. * @param constraintVariables ConstraintVariable or null. */ public void addNamedConstraintVariables(List<IDecisionVariable> constraintVariables) { this.constraintVariables = new ArrayList<IDecisionVariable>(); if (null != constraintVariables) { this.constraintVariables.addAll(constraintVariables); } } /** * Method for returning a list of ConstraintVariables of a failed constraint. Null if none. * @return List of ConstraintVariable or null. */ public List<IDecisionVariable> getNamedConstraintVariables() { return constraintVariables; } /** * Method for adding a list of reasoning error classifiers Null if non. * @param errorClassification defined error codes or null. */ public void addErrorClassification(List<Integer> errorClassification) { this.errorClassification = new ArrayList<Integer>(); if (null != errorClassification) { this.errorClassification.addAll(errorClassification); } } /** * Method for returning a list of reasoning error classifiers. Null if none. * @return List of error codes or null. */ public List<Integer> getErrorClassification() { return errorClassification; } @Override public String toString() { String res = ""; List<String> labels = getConflictLabels(); List<String> comments = getConflictComments(); List<Project> projects = getConflictProjects(); List<String> suggestions = getConflictSuggestions(); List<Set<IDecisionVariable>> vars = getProblemVariables(); List<ConstraintSyntaxTree> parts = getProblemConstraintParts(); List<IDecisionVariable> namedVars = getNamedConstraintVariables(); List<Integer> codes = getErrorClassification(); for (int i = 0; i < getConflictsCount(); i++) { ModelElement conflict = getConflicts().get(i); if (i > 0) { res += "\n"; } if (conflict instanceof Constraint) { Constraint constraint = (Constraint) conflict; res = append(res, "Failed element (EP): " + StringProvider.toIvmlString(constraint.getConsSyntax())); } else { res = append(res, "Failed element (EP): " + StringProvider.toIvmlString(conflict)); } res = append(res, "Failed elements label (CT): " + labels.get(i)); res = append(res, "Failed elements comment: " + comments.get(i)); res = append(res, "Failed elements project: " + projects.get(i).getName()); res = append(res, "Failed elements suggestion: " + suggestions.get(i)); res = append(res, "Failed elements variables: " + vars.get(i)); if (parts.get(i) != null) { res = append(res, "Failed elements problem constraint parts: " + StringProvider.toIvmlString(parts.get(i))); } res = append(res, "Failed elements constraint variable: " + namedVars.get(i)); res = append(res, "Reasoning error code: " + codes.get(i)); } return res; } /** * Appends <code>text</code> and a line end to <code>res</code>. * * @param res the text to append to * @param text the text to append * @return the combined text */ private String append(String res, String text) { return res + text + "\n"; } }
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.sdk; import com.intellij.execution.ExecutionException; import com.intellij.facet.ui.FacetEditorValidator; import com.intellij.facet.ui.FacetValidatorsManager; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.platform.LocationNameFieldsBinding; import com.intellij.ui.DocumentAdapter; import com.intellij.ui.components.JBCheckBox; import com.intellij.util.PathUtil; import com.intellij.util.PlatformUtils; import com.intellij.webcore.packaging.PackageManagementService; import com.intellij.webcore.packaging.PackagesNotificationPanel; import com.jetbrains.python.PyBundle; import com.jetbrains.python.packaging.PyPackageService; import com.jetbrains.python.packaging.ui.PyPackageManagementService; import com.jetbrains.python.sdk.flavors.VirtualEnvSdkFlavor; import com.jetbrains.python.ui.IdeaDialog; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.DocumentEvent; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.Collections; import java.util.List; public abstract class AbstractCreateVirtualEnvDialog extends IdeaDialog { @Nullable protected Project myProject; protected JPanel myMainPanel; protected JTextField myName; protected TextFieldWithBrowseButton myDestination; protected JBCheckBox myMakeAvailableToAllProjectsCheckbox; protected String myInitialPath; public interface VirtualEnvCallback { void virtualEnvCreated(Sdk sdk, boolean associateWithProject); } public static void setupVirtualEnvSdk(final String path, boolean associateWithProject, VirtualEnvCallback callback) { final VirtualFile sdkHome = ApplicationManager.getApplication().runWriteAction(new Computable<VirtualFile>() { @Nullable public VirtualFile compute() { return LocalFileSystem.getInstance().refreshAndFindFileByPath(path); } }); if (sdkHome != null) { final Sdk sdk = SdkConfigurationUtil.createAndAddSDK(FileUtil.toSystemDependentName(sdkHome.getPath()), PythonSdkType.getInstance()); callback.virtualEnvCreated(sdk, associateWithProject); } } public AbstractCreateVirtualEnvDialog(Project project, final List<Sdk> allSdks) { super(project); setupDialog(project, allSdks); } public AbstractCreateVirtualEnvDialog(Component owner, final List<Sdk> allSdks) { super(owner); setupDialog(null, allSdks); } void setupDialog(Project project, final List<Sdk> allSdks) { myProject = project; final GridBagLayout layout = new GridBagLayout(); myMainPanel = new JPanel(layout); myName = new JTextField(); myDestination = new TextFieldWithBrowseButton(); myMakeAvailableToAllProjectsCheckbox = new JBCheckBox(PyBundle.message("sdk.create.venv.dialog.make.available.to.all.projects")); if (project == null || project.isDefault() || !PlatformUtils.isPyCharm()) { myMakeAvailableToAllProjectsCheckbox.setSelected(true); myMakeAvailableToAllProjectsCheckbox.setVisible(false); } layoutPanel(allSdks); init(); setOKActionEnabled(false); registerValidators(new FacetValidatorsManager() { public void registerValidator(FacetEditorValidator validator, JComponent... componentsToWatch) { } public void validate() { checkValid(); } }); myMainPanel.setPreferredSize(new Dimension(300, 50)); checkValid(); setInitialDestination(); addUpdater(myName); new LocationNameFieldsBinding(project, myDestination, myName, myInitialPath, PyBundle.message("sdk.create.venv.dialog.select.venv.location")); } protected void setInitialDestination() { myInitialPath = ""; final VirtualFile file = VirtualEnvSdkFlavor.getDefaultLocation(); if (file != null) { myInitialPath = file.getPath(); } else { final String savedPath = PyPackageService.getInstance().getVirtualEnvBasePath(); if (!StringUtil.isEmptyOrSpaces(savedPath)) { myInitialPath = savedPath; } else if (myProject != null) { final VirtualFile baseDir = myProject.getBaseDir(); if (baseDir != null) { myInitialPath = baseDir.getPath(); } } } } protected void registerValidators(final FacetValidatorsManager validatorsManager) { myDestination.getTextField().getDocument().addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { validatorsManager.validate(); } }); myDestination.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { validatorsManager.validate(); } }); myName.addCaretListener(new CaretListener() { @Override public void caretUpdate(CaretEvent event) { validatorsManager.validate(); } }); myDestination.getTextField().addCaretListener(new CaretListener() { @Override public void caretUpdate(CaretEvent event) { validatorsManager.validate(); } }); } protected void checkValid() { final String projectName = myName.getText(); final File destFile = new File(getDestination()); if (destFile.exists()) { final String[] content = destFile.list(); if (content != null && content.length != 0) { setOKActionEnabled(false); setErrorText(PyBundle.message("sdk.create.venv.dialog.error.not.empty.directory")); return; } } if (StringUtil.isEmptyOrSpaces(projectName)) { setOKActionEnabled(false); setErrorText(PyBundle.message("sdk.create.venv.dialog.error.empty.venv.name")); return; } if (!PathUtil.isValidFileName(projectName)) { setOKActionEnabled(false); setErrorText(PyBundle.message("sdk.create.venv.dialog.error.invalid.directory.name")); return; } if (StringUtil.isEmptyOrSpaces(myDestination.getText())) { setOKActionEnabled(false); setErrorText(PyBundle.message("sdk.create.venv.dialog.error.empty.venv.location")); return; } setOKActionEnabled(true); setErrorText(null); } abstract protected void layoutPanel(final List<Sdk> allSdks); @Override protected JComponent createCenterPanel() { return myMainPanel; } @Nullable abstract public Sdk getSdk(); abstract public boolean useGlobalSitePackages(); public String getDestination() { return myDestination.getText(); } public String getName() { return myName.getText(); } public boolean associateWithProject() { return !myMakeAvailableToAllProjectsCheckbox.isSelected(); } public void createVirtualEnv(final VirtualEnvCallback callback) { final ProgressManager progman = ProgressManager.getInstance(); final Sdk basicSdk = getSdk(); final Task.Modal createTask = new Task.Modal(myProject, PyBundle.message("sdk.create.venv.dialog.creating.venv"), false) { String myPath; public void run(@NotNull final ProgressIndicator indicator) { try { indicator.setText(PyBundle.message("sdk.create.venv.dialog.creating.venv")); myPath = createEnvironment(basicSdk); } catch (final ExecutionException e) { ApplicationManager.getApplication().invokeLater(() -> { final PackageManagementService.ErrorDescription description = PyPackageManagementService.toErrorDescription(Collections.singletonList(e), basicSdk); if (description != null) { PackagesNotificationPanel.showError(PyBundle.message("sdk.create.venv.dialog.error.failed.to.create.venv"), description); } }, ModalityState.any()); } } @Override public void onSuccess() { if (myPath != null) { ApplicationManager.getApplication().invokeLater(() -> setupVirtualEnvSdk(myPath, associateWithProject(), callback)); } } }; progman.run(createTask); } abstract protected String createEnvironment(Sdk basicSdk) throws ExecutionException; @Override public JComponent getPreferredFocusedComponent() { return myName; } @Override protected void doOKAction() { super.doOKAction(); VirtualFile baseDir = myProject != null ? myProject.getBaseDir() : null; if (!myDestination.getText().startsWith(myInitialPath) && (baseDir == null || !myDestination.getText().startsWith(baseDir.getPath()))) { String path = myDestination.getText(); PyPackageService.getInstance().setVirtualEnvBasePath(!path.contains(File.separator) ? path : path.substring(0, path.lastIndexOf(File.separator))); } } }
/* 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.activiti.engine.impl; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.activiti.engine.ActivitiIllegalArgumentException; import org.activiti.engine.impl.context.Context; import org.activiti.engine.impl.interceptor.CommandContext; import org.activiti.engine.impl.interceptor.CommandExecutor; import org.activiti.engine.impl.persistence.entity.ExecutionEntity; import org.activiti.engine.impl.persistence.entity.SuspensionState; import org.activiti.engine.runtime.Execution; import org.activiti.engine.runtime.ExecutionQuery; import org.flowable.engine.DynamicBpmnConstants; import org.flowable.engine.repository.ProcessDefinition; /** * @author Joram Barrez * @author Frederik Heremans * @author Daniel Meyer */ public class ExecutionQueryImpl extends AbstractVariableQueryImpl<ExecutionQuery, Execution> implements ExecutionQuery { private static final long serialVersionUID = 1L; protected String processDefinitionId; protected String processDefinitionKey; protected String processDefinitionCategory; protected String processDefinitionName; protected Integer processDefinitionVersion; protected String activityId; protected String executionId; protected String parentId; protected String processInstanceId; protected List<EventSubscriptionQueryValue> eventSubscriptions; protected String tenantId; protected String tenantIdLike; protected boolean withoutTenantId; protected String locale; protected boolean withLocalizationFallback; // Not used by end-users, but needed for dynamic ibatis query protected String superProcessInstanceId; protected String subProcessInstanceId; protected boolean excludeSubprocesses; protected SuspensionState suspensionState; protected String businessKey; protected boolean includeChildExecutionsWithBusinessKeyQuery; protected boolean isActive; protected String involvedUser; protected Set<String> processDefinitionKeys; protected Set<String> processDefinitionIds; // Not exposed in API, but here for the ProcessInstanceQuery support, since the name lives on the // Execution entity/table protected String name; protected String nameLike; protected String nameLikeIgnoreCase; protected String deploymentId; protected List<String> deploymentIds; protected List<ExecutionQueryImpl> orQueryObjects = new ArrayList<>(); public ExecutionQueryImpl() { } public ExecutionQueryImpl(CommandContext commandContext) { super(commandContext); } public ExecutionQueryImpl(CommandExecutor commandExecutor) { super(commandExecutor); } public boolean isProcessInstancesOnly() { return false; // see dynamic query } @Override public ExecutionQueryImpl processDefinitionId(String processDefinitionId) { if (processDefinitionId == null) { throw new ActivitiIllegalArgumentException("Process definition id is null"); } this.processDefinitionId = processDefinitionId; return this; } @Override public ExecutionQueryImpl processDefinitionKey(String processDefinitionKey) { if (processDefinitionKey == null) { throw new ActivitiIllegalArgumentException("Process definition key is null"); } this.processDefinitionKey = processDefinitionKey; return this; } @Override public ExecutionQuery processDefinitionCategory(String processDefinitionCategory) { if (processDefinitionCategory == null) { throw new ActivitiIllegalArgumentException("Process definition category is null"); } this.processDefinitionCategory = processDefinitionCategory; return this; } @Override public ExecutionQuery processDefinitionName(String processDefinitionName) { if (processDefinitionName == null) { throw new ActivitiIllegalArgumentException("Process definition name is null"); } this.processDefinitionName = processDefinitionName; return this; } @Override public ExecutionQuery processDefinitionVersion(Integer processDefinitionVersion) { if (processDefinitionVersion == null) { throw new ActivitiIllegalArgumentException("Process definition version is null"); } this.processDefinitionVersion = processDefinitionVersion; return this; } @Override public ExecutionQueryImpl processInstanceId(String processInstanceId) { if (processInstanceId == null) { throw new ActivitiIllegalArgumentException("Process instance id is null"); } this.processInstanceId = processInstanceId; return this; } @Override public ExecutionQuery processInstanceBusinessKey(String businessKey) { if (businessKey == null) { throw new ActivitiIllegalArgumentException("Business key is null"); } this.businessKey = businessKey; return this; } @Override public ExecutionQuery processInstanceBusinessKey(String processInstanceBusinessKey, boolean includeChildExecutions) { if (!includeChildExecutions) { return processInstanceBusinessKey(processInstanceBusinessKey); } else { if (processInstanceBusinessKey == null) { throw new ActivitiIllegalArgumentException("Business key is null"); } this.businessKey = processInstanceBusinessKey; this.includeChildExecutionsWithBusinessKeyQuery = includeChildExecutions; return this; } } @Override public ExecutionQuery processDefinitionKeys(Set<String> processDefinitionKeys) { if (processDefinitionKeys == null) { throw new ActivitiIllegalArgumentException("Process definition keys is null"); } this.processDefinitionKeys = processDefinitionKeys; return this; } @Override public ExecutionQueryImpl executionId(String executionId) { if (executionId == null) { throw new ActivitiIllegalArgumentException("Execution id is null"); } this.executionId = executionId; return this; } @Override public ExecutionQueryImpl activityId(String activityId) { this.activityId = activityId; if (activityId != null) { isActive = true; } return this; } @Override public ExecutionQueryImpl parentId(String parentId) { if (parentId == null) { throw new ActivitiIllegalArgumentException("Parent id is null"); } this.parentId = parentId; return this; } @Override public ExecutionQueryImpl executionTenantId(String tenantId) { if (tenantId == null) { throw new ActivitiIllegalArgumentException("execution tenant id is null"); } this.tenantId = tenantId; return this; } @Override public ExecutionQueryImpl executionTenantIdLike(String tenantIdLike) { if (tenantIdLike == null) { throw new ActivitiIllegalArgumentException("execution tenant id is null"); } this.tenantIdLike = tenantIdLike; return this; } @Override public ExecutionQueryImpl executionWithoutTenantId() { this.withoutTenantId = true; return this; } @Override public ExecutionQuery signalEventSubscription(String signalName) { return eventSubscription("signal", signalName); } @Override public ExecutionQuery signalEventSubscriptionName(String signalName) { return eventSubscription("signal", signalName); } @Override public ExecutionQuery messageEventSubscriptionName(String messageName) { return eventSubscription("message", messageName); } public ExecutionQuery eventSubscription(String eventType, String eventName) { if (eventName == null) { throw new ActivitiIllegalArgumentException("event name is null"); } if (eventType == null) { throw new ActivitiIllegalArgumentException("event type is null"); } if (eventSubscriptions == null) { eventSubscriptions = new ArrayList<>(); } eventSubscriptions.add(new EventSubscriptionQueryValue(eventName, eventType)); return this; } @Override public ExecutionQuery processVariableValueEquals(String variableName, Object variableValue) { return variableValueEquals(variableName, variableValue, false); } @Override public ExecutionQuery processVariableValueEquals(Object variableValue) { return variableValueEquals(variableValue, false); } @Override public ExecutionQuery processVariableValueNotEquals(String variableName, Object variableValue) { return variableValueNotEquals(variableName, variableValue, false); } @Override public ExecutionQuery processVariableValueEqualsIgnoreCase(String name, String value) { return variableValueEqualsIgnoreCase(name, value, false); } @Override public ExecutionQuery processVariableValueNotEqualsIgnoreCase(String name, String value) { return variableValueNotEqualsIgnoreCase(name, value, false); } @Override public ExecutionQuery processVariableValueLike(String name, String value) { return variableValueLike(name, value, false); } @Override public ExecutionQuery processVariableValueLikeIgnoreCase(String name, String value) { return variableValueLikeIgnoreCase(name, value, false); } @Override public ExecutionQuery locale(String locale) { this.locale = locale; return this; } @Override public ExecutionQuery withLocalizationFallback() { withLocalizationFallback = true; return this; } // ordering //////////////////////////////////////////////////// @Override public ExecutionQueryImpl orderByProcessInstanceId() { this.orderProperty = ExecutionQueryProperty.PROCESS_INSTANCE_ID; return this; } @Override public ExecutionQueryImpl orderByProcessDefinitionId() { this.orderProperty = ExecutionQueryProperty.PROCESS_DEFINITION_ID; return this; } @Override public ExecutionQueryImpl orderByProcessDefinitionKey() { this.orderProperty = ExecutionQueryProperty.PROCESS_DEFINITION_KEY; return this; } @Override public ExecutionQueryImpl orderByTenantId() { this.orderProperty = ExecutionQueryProperty.TENANT_ID; return this; } // results //////////////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); ensureVariablesInitialized(); return commandContext .getExecutionEntityManager() .findExecutionCountByQueryCriteria(this); } @Override @SuppressWarnings({"unchecked"}) public List<Execution> executeList(CommandContext commandContext, Page page) { checkQueryOk(); ensureVariablesInitialized(); List<?> executions = commandContext.getExecutionEntityManager().findExecutionsByQueryCriteria(this, page); for (ExecutionEntity execution : (List<ExecutionEntity>) executions) { String activityId = null; if (execution.getId().equals(execution.getProcessInstanceId())) { if (execution.getProcessDefinitionId() != null) { ProcessDefinition processDefinition = commandContext.getProcessEngineConfiguration() .getDeploymentManager() .findDeployedProcessDefinitionById(execution.getProcessDefinitionId()); activityId = processDefinition.getKey(); } } else { activityId = execution.getActivityId(); } if (activityId != null) { localize(execution, activityId); } } return (List<Execution>) executions; } protected void localize(Execution execution, String activityId) { ExecutionEntity executionEntity = (ExecutionEntity) execution; executionEntity.setLocalizedName(null); executionEntity.setLocalizedDescription(null); String processDefinitionId = executionEntity.getProcessDefinitionId(); if (locale != null && processDefinitionId != null) { ObjectNode languageNode = Context.getLocalizationElementProperties(locale, activityId, processDefinitionId, withLocalizationFallback); if (languageNode != null) { JsonNode languageNameNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_NAME); if (languageNameNode != null && !languageNameNode.isNull()) { executionEntity.setLocalizedName(languageNameNode.asText()); } JsonNode languageDescriptionNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_DESCRIPTION); if (languageDescriptionNode != null && !languageDescriptionNode.isNull()) { executionEntity.setLocalizedDescription(languageDescriptionNode.asText()); } } } } // getters //////////////////////////////////////////////////// public boolean getOnlyProcessInstances() { return false; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionCategory() { return processDefinitionCategory; } public String getProcessDefinitionName() { return processDefinitionName; } public Integer getProcessDefinitionVersion() { return processDefinitionVersion; } public String getActivityId() { return activityId; } public String getProcessInstanceId() { return processInstanceId; } public String getProcessInstanceIds() { return null; } public String getBusinessKey() { return businessKey; } public String getExecutionId() { return executionId; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public String getSubProcessInstanceId() { return subProcessInstanceId; } public boolean isExcludeSubprocesses() { return excludeSubprocesses; } public SuspensionState getSuspensionState() { return suspensionState; } public void setSuspensionState(SuspensionState suspensionState) { this.suspensionState = suspensionState; } public List<EventSubscriptionQueryValue> getEventSubscriptions() { return eventSubscriptions; } public boolean isIncludeChildExecutionsWithBusinessKeyQuery() { return includeChildExecutionsWithBusinessKeyQuery; } public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) { this.eventSubscriptions = eventSubscriptions; } public boolean isActive() { return isActive; } public String getInvolvedUser() { return involvedUser; } public void setInvolvedUser(String involvedUser) { this.involvedUser = involvedUser; } public Set<String> getProcessDefinitionIds() { return processDefinitionIds; } public Set<String> getProcessDefinitionKeys() { return processDefinitionKeys; } public String getParentId() { return parentId; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getName() { return name; } public String getNameLike() { return nameLike; } public void setName(String name) { this.name = name; } public void setNameLike(String nameLike) { this.nameLike = nameLike; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public void setNameLikeIgnoreCase(String nameLikeIgnoreCase) { this.nameLikeIgnoreCase = nameLikeIgnoreCase; } }
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.engine.target; import java.io.ObjectStreamException; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; import com.opengamma.core.position.Portfolio; import com.opengamma.core.position.PortfolioNode; import com.opengamma.core.position.Position; import com.opengamma.core.position.PositionOrTrade; import com.opengamma.core.position.Trade; import com.opengamma.core.security.Security; import com.opengamma.engine.fudgemsg.ComputationTargetTypeFudgeBuilder; import com.opengamma.engine.target.resolver.CreditCurveIdentifierResolver; import com.opengamma.engine.target.resolver.CurrencyResolver; import com.opengamma.engine.target.resolver.ObjectResolver; import com.opengamma.engine.target.resolver.PrimitiveResolver; import com.opengamma.engine.target.resolver.UnorderedCurrencyPairResolver; import com.opengamma.id.UniqueIdentifiable; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.PublicAPI; import com.opengamma.util.credit.CreditCurveIdentifier; import com.opengamma.util.money.Currency; import com.opengamma.util.money.UnorderedCurrencyPair; /** * The type of the target a computation step will act on or a data sourcing function will provide. */ @PublicAPI public abstract class ComputationTargetType implements Serializable { private static final long serialVersionUID = 1L; /** * Try to keep the instances unique. This reduces the operating memory footprint. */ private static final ConcurrentMap<?, ?> COMPUTATION_TARGET_TYPES = new ConcurrentHashMap<Object, Object>() { private static final long serialVersionUID = 1L; @Override public Object get(final Object type) { Object instance = super.get(type); if (instance != null) { return instance; } instance = super.putIfAbsent(type, type); if (instance != null) { return instance; } return type; } }; /** * A map of classes to the computation target types. This is to optimize the {@link #of(Class)} method for common cases used during target resolution. To * modify the map, use a copy-and-replace approach. */ private static final AtomicReference<Map<Class<?>, ComputationTargetType>> CLASS_TYPES = new AtomicReference<Map<Class<?>, ComputationTargetType>>( new HashMap<Class<?>, ComputationTargetType>()); /** * A full portfolio structure. This will seldom be needed for calculations - the root node is usually more important from an aggregation perspective. */ public static final ObjectComputationTargetType<Portfolio> PORTFOLIO = defaultObject(Portfolio.class, "PORTFOLIO"); /** * An ordered list of positions and other portfolio nodes. */ public static final ObjectComputationTargetType<PortfolioNode> PORTFOLIO_NODE = defaultObject(PortfolioNode.class, "PORTFOLIO_NODE"); /** * A position. */ public static final ObjectComputationTargetType<Position> POSITION = defaultObject(Position.class, "POSITION"); /** * A security. */ public static final ObjectComputationTargetType<Security> SECURITY = defaultObject(Security.class, "SECURITY"); /** * A trade. */ public static final ObjectComputationTargetType<Trade> TRADE = defaultObject(Trade.class, "TRADE"); /** * A simple type, for trivial items for which a unique ID (which can just be an arbitrary string triple if scheme, value and version used) that does not need * resolving is sufficient. */ public static final PrimitiveComputationTargetType<Primitive> PRIMITIVE = defaultPrimitive(Primitive.class, "PRIMITIVE", new PrimitiveResolver()); /** * A currency. */ public static final PrimitiveComputationTargetType<Currency> CURRENCY = defaultPrimitive(Currency.class, "CURRENCY", new CurrencyResolver()); /** * An unordered currency pair. */ public static final PrimitiveComputationTargetType<UnorderedCurrencyPair> UNORDERED_CURRENCY_PAIR = defaultPrimitive(UnorderedCurrencyPair.class, "UNORDERED_CURRENCY_PAIR", new UnorderedCurrencyPairResolver()); /** * A credit curve identifier. */ public static final PrimitiveComputationTargetType<CreditCurveIdentifier> CREDIT_CURVE_IDENTIFIER = defaultPrimitive(CreditCurveIdentifier.class, "CREDIT_CURVE_IDENTIFIER", new CreditCurveIdentifierResolver()); /** * A wildcard type. This may be used when declaring the target type of a function. It should not be used as part of a target reference as the lack of specific * type details will prevent a resolver from producing the concrete target object. */ public static final ObjectComputationTargetType<UniqueIdentifiable> ANYTHING = defaultObject(UniqueIdentifiable.class, "ANYTHING"); /** * A position or a trade object. This is a union type for an object that is either an instance of {@link Position}, {@link Trade}, or both. This may be used * when declaring the target type of a function. It should not normally be used as part of a target reference as the resolver will have to try multiple * resolution strategies to determine the concrete instance. */ public static final ObjectComputationTargetType<PositionOrTrade> POSITION_OR_TRADE = ObjectComputationTargetType.of(POSITION.or(TRADE), PositionOrTrade.class); /** * An explicit null, for the anonymous target. */ public static final ComputationTargetType NULL = new NullComputationTargetType(); /** * An equivalent to the previous use of {@code PRIMITIVE}. It means primitives in their new sense, plus currencies and unordered currency pairs that now have * explicit types. * * @deprecated This is not particularly efficient to use and may not be correct, but is better than using {@link #ANYTHING}. It will be removed at the first * opportunity. */ @Deprecated public static final ComputationTargetType LEGACY_PRIMITIVE = PRIMITIVE.or(CURRENCY).or(UNORDERED_CURRENCY_PAIR); private final int _hashCode; /* package */ ComputationTargetType(final int hashCode) { _hashCode = hashCode; } private static <T extends UniqueIdentifiable> ComputationTargetType defaultType(final Class<T> clazz, final String name) { final ComputationTargetType type = of(clazz, name, true); // This is safe; we only get called like this during class initialization CLASS_TYPES.get().put(clazz, type); return type; } private static <T extends UniqueIdentifiable> ObjectComputationTargetType<T> defaultObject(final Class<T> clazz, final String name) { return ObjectComputationTargetType.of(defaultType(clazz, name), clazz); } private static <T extends UniqueIdentifiable> PrimitiveComputationTargetType<T> defaultPrimitive(final Class<T> clazz, final String name, final ObjectResolver<T> resolver) { return PrimitiveComputationTargetType.of(defaultType(clazz, name), clazz, resolver); } private static ComputationTargetType of(final Class<? extends UniqueIdentifiable> clazz, final String name, final boolean nameWellKnown) { return (ComputationTargetType) COMPUTATION_TARGET_TYPES.get(new ClassComputationTargetType(clazz, name, nameWellKnown)); } public static <T extends UniqueIdentifiable> ComputationTargetType of(final Class<T> clazz) { final Map<Class<?>, ComputationTargetType> cache = CLASS_TYPES.get(); ComputationTargetType type = cache.get(clazz); if (type != null) { return type; } ArgumentChecker.notNull(clazz, "clazz"); type = of(clazz, clazz.getSimpleName(), false); final Map<Class<?>, ComputationTargetType> updatedCache = new HashMap<>(cache); updatedCache.put(clazz, type); CLASS_TYPES.compareAndSet(cache, updatedCache); return type; } public ComputationTargetType containing(final Class<? extends UniqueIdentifiable> clazz) { return containing(of(clazz)); } public ComputationTargetType containing(final ComputationTargetType inner) { ArgumentChecker.notNull(inner, "inner"); return (ComputationTargetType) COMPUTATION_TARGET_TYPES.get(new NestedComputationTargetType(this, inner)); } public ComputationTargetType or(final Class<? extends UniqueIdentifiable> clazz) { return or(of(clazz)); } /** * Creates a composite type that is either this instance or the alternative. * * @param alternative * the alternative type to this one, not null * @return the composite type instance, not null */ public ComputationTargetType or(final ComputationTargetType alternative) { ArgumentChecker.notNull(alternative, "alternative"); return (ComputationTargetType) COMPUTATION_TARGET_TYPES.get(new MultipleComputationTargetType(this, alternative)); } /** * Creates a composite type that is any of the given alternatives. * <p> * {@code multiple(a, b, c)} will give the same result as {@code a.or(b).or(c)} but is more efficient. * * @param alternatives * the alternative types to this one, not null, not containing null, and with at least two different types * @return the composite type instance, not null */ public static ComputationTargetType multiple(final ComputationTargetType... alternatives) { ArgumentChecker.notNull(alternatives, "alternatives"); return (ComputationTargetType) COMPUTATION_TARGET_TYPES.get(new MultipleComputationTargetType(alternatives)); } /** * Tests if the given target object is valid for this type descriptor. * * @param target * the object to test * @return true if the object is compatible, false if the object is not of the descriptor's type */ public abstract boolean isCompatible(UniqueIdentifiable target); /** * Tests if the given type descriptor is compatible with this type descriptor. The target class must be the same class or a subclass at each nesting level. * * @param type * the type to test * @return true if the type is compatible, false otherwise */ public abstract boolean isCompatible(ComputationTargetType type); /** * Tests if the given target class is valid for this type descriptor. * * @param clazz * the object class to test * @return true if the class is compatible, false if it is not of the descriptor's type */ public abstract boolean isCompatible(Class<? extends UniqueIdentifiable> clazz); private static final class Parser { private final String _buffer; private int _index; Parser(final String str) { _buffer = str; } private static boolean isIdentifier(final char c) { return c != '/' && c != '|' && c != '(' && c != ')'; } public ComputationTargetType parse() { ComputationTargetType type = null; do { switch (_buffer.charAt(_index)) { case '/': if (type == null) { throw new IllegalArgumentException("Unexpected / at index " + _index + " of " + _buffer); } _index++; type = new NestedComputationTargetType(type, parse()); break; case '|': if (type == null) { throw new IllegalArgumentException("Unexpected | at index " + _index + " of " + _buffer); } _index++; type = new MultipleComputationTargetType(type, parse()); break; case '(': _index++; if (type == null) { type = parse(); } else { throw new IllegalArgumentException("Unexpected ( at index " + _index + " of " + _buffer); } break; case ')': if (type == null) { throw new IllegalArgumentException("Unexpected ) at index " + _index + " of " + _buffer); } _index++; return type; default: if (type != null) { throw new IllegalArgumentException("Unexpected identifier at index " + _index + " of " + _buffer); } final StringBuilder sb = new StringBuilder(); do { sb.append(_buffer.charAt(_index++)); } while (_index < _buffer.length() && isIdentifier(_buffer.charAt(_index))); type = ComputationTargetTypeFudgeBuilder.fromString(sb.toString()); break; } } while (_index < _buffer.length()); return type; } } /** * Parses a string produced by {@link #toString}. * * @param str * the string to parse, not null * @return the computation target type, not null */ public static ComputationTargetType parse(final String str) { return new Parser(str).parse(); } /** * Apply the visitor operation to this target type. * * @param <T> * the return type of the visitor * @param <D> * the parameter data type of the visitor * @param visitor * the visitor to apply, not null * @param data * the data value to pass to the visitor * @return the result of the visitor operation */ public abstract <D, T> T accept(ComputationTargetTypeVisitor<D, T> visitor, D data); /** * Produces a string representation of the type that includes outer brackets if necessary to maintain the structure of composite types for handling by * {@link #parse}. * * @param sb * the string builder to append the string representation to */ protected abstract void toStringNested(StringBuilder sb); /** * Produces a string representation of the type that can be parsed by {@link #parse} and is vaguely human readable. * * @return the string representation */ @Override public abstract String toString(); /** * Produces a string representation of the type that includes outer brackets if necessary to maintain the structure of composite types for viewing by a user. * * @param sb * the string builder to append the string representation to */ protected abstract void getNameNested(StringBuilder sb); /** * Produces a string representation of the type that can be displayed to the user. * * @return the string representation */ public abstract String getName(); @Override public abstract boolean equals(Object o); @Override public final int hashCode() { return _hashCode; } /** * Tests if the leaf target type(s) matches the given type. {@code x.isTargetType(y) == y.isCompatible(x) } * * @param type * the type to test, not null * @return true if the leaf target type (or one of the types if there are multiple choices) matches the given type, false otherwise */ public abstract boolean isTargetType(ComputationTargetType type); /** * Tests if the leaf target type(s) matches the given type. * * @param type * the type to test, not null * @return true if the leaf target type (or one of the types if there are multiple choices) matches the given type, false otherwise */ public abstract boolean isTargetType(Class<? extends UniqueIdentifiable> type); protected Object readResolve() throws ObjectStreamException { return COMPUTATION_TARGET_TYPES.get(this); } }
package org.peerbox.view.tray; import java.awt.AWTException; import java.awt.Image; import java.awt.PopupMenu; import java.awt.TrayIcon; import java.awt.TrayIcon.MessageType; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import net.engio.mbassy.listener.Handler; import org.peerbox.app.Constants; import org.peerbox.app.config.AppConfig; import org.peerbox.app.manager.file.messages.FileExecutionFailedMessage; import org.peerbox.app.manager.user.IUserMessageListener; import org.peerbox.app.manager.user.LoginMessage; import org.peerbox.app.manager.user.LogoutMessage; import org.peerbox.app.manager.user.RegisterMessage; import org.peerbox.events.IMessageListener; import org.peerbox.notifications.AggregatedFileEventStatus; import org.peerbox.notifications.ITrayNotifications; import org.peerbox.notifications.InformationNotification; import org.peerbox.presenter.tray.TrayActionHandler; import org.peerbox.presenter.tray.TrayException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; public class JSystemTray extends AbstractSystemTray implements ITrayNotifications, IMessageListener, IUserMessageListener { private final static Logger logger = LoggerFactory.getLogger(JSystemTray.class); private String tooltip; private java.awt.TrayIcon trayIcon; private final JTrayIcons iconProvider; private AppConfig appConfig; private boolean hasFailedOperations = false; @Inject public JSystemTray(AppConfig appConfig, TrayActionHandler actionHandler) { super(actionHandler); this.appConfig = appConfig; this.iconProvider = new JTrayIcons(); setTooltip(Constants.APP_NAME); } private TrayIcon create(Image image) throws IOException { TrayIcon trayIcon = new java.awt.TrayIcon(image); trayIcon.setImageAutoSize(true); trayIcon.setToolTip(tooltip); trayIcon.setPopupMenu(createMenu(false)); return trayIcon; } private PopupMenu createMenu(boolean isUserLoggedIn) { JTrayMenu menu = new JTrayMenu(trayActionHandler); PopupMenu root = menu.create(isUserLoggedIn); return root; } @Override public void show() throws TrayException { try { trayIcon = create(iconProvider.getDefaultIcon()); java.awt.SystemTray sysTray = java.awt.SystemTray.getSystemTray(); sysTray.add(trayIcon); } catch (AWTException e) { logger.debug("SysTray AWTException.", e); logger.error("Could not initialize systray (tray may not be supported?)"); throw new TrayException(e); } catch (IOException e) { logger.debug("SysTray.show IOException.", e); logger.error("Could not initialize systray (image not found?)"); throw new TrayException(e); } } @Override public void setTooltip(String tooltip) { this.tooltip = tooltip; if(trayIcon != null) { trayIcon.setToolTip(this.tooltip); } } @Override public void showDefaultIcon() throws TrayException { try { trayIcon.setImage(iconProvider.getDefaultIcon()); } catch (IOException e) { logger.debug("SysTray.show IOException.", e); logger.error("Could not change icon (image not found?)"); throw new TrayException(e); } } @Override public void showSyncingIcon() throws TrayException { try { trayIcon.setImage(iconProvider.getSyncingIcon()); } catch (IOException e) { logger.debug("SysTray.show IOException.", e); logger.error("Could not change icon (image not found?)"); throw new TrayException(e); } } @Override public void showSuccessIcon() throws TrayException { try { if (hasFailedOperations) { trayIcon.setImage(iconProvider.getErrorIcon()); } else { trayIcon.setImage(iconProvider.getSuccessIcon()); } } catch (IOException e) { logger.debug("SysTray.show IOException.", e); logger.error("Could not change icon (image not found?)"); throw new TrayException(e); } } @Override public void showInformationMessage(String title, String message) { setNewMessageActionListener(null); showMessage(title, message, MessageType.INFO); } private void showMessage(String title, String message, MessageType type) { if (!appConfig.isTrayNotificationEnabled()) { return; } if (title == null) { title = ""; } if (message == null) { message = ""; } logger.info("{} Message: \n{}\n{}", type.toString(), title, message); if (trayIcon != null) { trayIcon.displayMessage(title, message, type); } } /** * NOTIFICATIONS - implementation of the ITrayNotifications interface */ @Override @Handler public void showInformation(InformationNotification in) { ActionListener listener = new ShowActivityActionListener(); setNewMessageActionListener(listener); showMessage(in.getTitle(), in.getMessage(), MessageType.INFO); } @Override @Handler public void showFileEvents(AggregatedFileEventStatus event) { String msg = generateAggregatedFileEventStatusMessage(event); ActionListener listener = new ShowSettingsActionListener(); setNewMessageActionListener(listener); showMessage("File Synchronization", msg, MessageType.INFO); } /** * Removes all action listeners from the tray icon and adds the given listener. * * @param listener to add. If null, listeners are only and no listener is added. */ private void setNewMessageActionListener(ActionListener listener) { // remove all and add given action listener if (trayIcon != null) { for (ActionListener l : trayIcon.getActionListeners()) { trayIcon.removeActionListener(l); } if (listener != null) { trayIcon.addActionListener(listener); } } } /** * Action listener that opens the activity window */ private class ShowActivityActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { trayActionHandler.showActivity(); } } /** * Action listener that opens the settings window */ private class ShowSettingsActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { trayActionHandler.showSettings(); } } private String generateAggregatedFileEventStatusMessage(AggregatedFileEventStatus e) { StringBuilder sb = new StringBuilder(); sb.append("Hi there, some of your files changed.\n\n"); if(e.getNumFilesAdded() > 0) { sb.append("new files: ").append(e.getNumFilesAdded()).append("\n"); } if(e.getNumFilesModified() > 0) { sb.append("updated files: ").append(e.getNumFilesModified()).append("\n"); } if(e.getNumFilesDeleted() > 0) { sb.append("deleted files: ").append(e.getNumFilesDeleted()).append("\n"); } if(e.getNumFilesMoved() > 0) { sb.append("moved files: ").append(e.getNumFilesMoved()).append("\n"); } return sb.toString(); } @Handler public void onSynchronizationComplete(SynchronizationCompleteNotification message) throws TrayException { logger.trace("Set success icon."); showSuccessIcon(); } @Handler public void onSynchronizationStart(SynchronizationStartsNotification message) throws TrayException { logger.trace("Set synchronization icon."); showSyncingIcon(); } @Handler public void onSynchronizationFailed(FileExecutionFailedMessage message) throws TrayException { logger.trace("At least one operation failed. If the application is idle, " + "the error icon is shown."); hasFailedOperations = true; } @Handler public void onSynchronizationErrorResolved(SynchronizationErrorsResolvedNotification message) { logger.trace("All failed operations successfully resolved. If the application is idle, " + "the success icon is shown."); hasFailedOperations = false; } /*** * User event handling ***/ @Handler @Override public void onUserRegister(RegisterMessage register) { // nothing to do } @Handler @Override public void onUserLogin(LoginMessage login) { // refresh menu trayIcon.setPopupMenu(null); trayIcon.setPopupMenu(createMenu(true)); } @Handler @Override public void onUserLogout(LogoutMessage logout) { // refresh menu trayIcon.setPopupMenu(null); trayIcon.setPopupMenu(createMenu(false)); } }
package org.qtrp.nadir.Activity; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.github.jjobes.slidedatetimepicker.SlideDateTimeListener; import com.github.jjobes.slidedatetimepicker.SlideDateTimePicker; import org.qtrp.nadir.CustomViews.ContextMenuRecyclerView; import org.qtrp.nadir.CustomViews.PhotoAdapter; import org.qtrp.nadir.Database.FilmRollDbHelper; import org.qtrp.nadir.Database.Photo; import org.qtrp.nadir.Helpers.LocationHelper; import org.qtrp.nadir.R; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.UUID; import java.util.logging.Logger; public class RollActivity extends AppCompatActivity { private static final int LOCATION_PERMISSION_ID = 200; private static final String TAG = "RollActivity"; private Button addPhotoButton, resetLocationButton, resetTimeButton, cancelButton, deletePhotoButton, savePhotoButton; private EditText longituteEt, latitudeEt, descriptionEt; private TextView timeTv; private ContextMenuRecyclerView photoList; private FilmRollDbHelper filmRollDbHelper; private Long roll_id; private PhotoAdapter adapter; LinearLayout dummyFocus; private Date timestamp; private LinearLayout editPhotoButtonsLayout; private LinearLayout newPhotoButtonsLayout; SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm"); private LocationHelper mGPS; private Photo editingPhoto; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_roll); Intent intent = getIntent(); roll_id = intent.getLongExtra("roll_id", -1); Log.i("Roll id: ", roll_id.toString()); mGPS = new LocationHelper(this); loadUtils(); bindWidgets(); setDatasets(); snapMode(); setListeners(); refreshDatasets(); } private void editMode(Photo photo) { adapter.setCanSelect(false); editPhotoButtonsLayout.setVisibility(View.VISIBLE); newPhotoButtonsLayout.setVisibility(View.GONE); descriptionEt.setText(photo.getDescription()); setLocation(photo.getLatitude(), photo.getLongitude()); setTime(new Date(photo.getTimestamp() * 1000)); editingPhoto = photo; } private void snapMode() { adapter.setCanSelect(true); adapter.deselect(); editingPhoto = null; newPhotoButtonsLayout.setVisibility(View.VISIBLE); editPhotoButtonsLayout.setVisibility(View.GONE); latitudeEt.setText(""); longituteEt.setText(""); setLocation(); descriptionEt.setText(""); setTime(getTimeNow()); refreshDatasets(); dummyFocus.requestFocus(); InputMethodManager imm = (InputMethodManager) getSystemService(RollActivity.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(descriptionEt.getWindowToken(), 0); } @Override protected void onStart() { super.onStart(); startLocation(); } @Override protected void onStop() { super.onStop(); stopLocation(); } private void startLocation() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_ID); return; } else { Log.v(TAG,"permissions are fine. starting."); } mGPS.start(); } private void stopLocation() { mGPS.stop(); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case LOCATION_PERMISSION_ID: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.v(TAG, "location permission granted."); } else { Log.v(TAG, "location permission declined"); } startLocation(); } } } private void refreshDatasets() { adapter.clear(); adapter.addAll(filmRollDbHelper.getPhotosByRollId(roll_id)); adapter.notifyDataSetChanged(); reloadAddresses(); } // private void dummyData() { // adapter.addOne(new Photo(null, roll_id, 2.34534, 2.345345, 12324l, "Stuff", getTimestamp(), )); // adapter.addOne(new Photo(null, roll_id, 2.54644, 2.5677847845, 113346l, "Other stuff", getTimestamp())); // adapter.addOne(new Photo(null, roll_id, 2.54644, 2.5677847845, 11314l, "New stuff", getTimestamp())); // adapter.notifyDataSetChanged(); // } private void bindWidgets() { addPhotoButton = (Button) findViewById(R.id.addPhotoButton); resetLocationButton = (Button) findViewById(R.id.resetLocationButton); resetTimeButton = (Button) findViewById(R.id.resetTimeButton); cancelButton = (Button) findViewById(R.id.cancelButton); deletePhotoButton = (Button) findViewById(R.id.deletePhotoButton); savePhotoButton = (Button) findViewById(R.id.savePhotoButton); longituteEt = (EditText) findViewById(R.id.longtitudeEditText); latitudeEt = (EditText) findViewById(R.id.latitudeEditText); descriptionEt = (EditText) findViewById(R.id.addDescriptionEditText); timeTv = (TextView) findViewById(R.id.photoTimeTextView); photoList = (ContextMenuRecyclerView) findViewById(R.id.photoList); dummyFocus = (LinearLayout) findViewById(R.id.dummy_focus); editPhotoButtonsLayout = (LinearLayout) findViewById(R.id.editPhotoButtonsLayout); newPhotoButtonsLayout = (LinearLayout) findViewById(R.id.newPhotoButtonsLayout); } private void loadUtils() { filmRollDbHelper = new FilmRollDbHelper(this); } public void setDatasets(){ photoList.setHasFixedSize(true); List<Photo> listItems = filmRollDbHelper.getPhotosByRollId(roll_id); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); photoList.setLayoutManager(mLayoutManager); photoList.setItemAnimator(new DefaultItemAnimator()); adapter = new PhotoAdapter(listItems); photoList.setAdapter(adapter); setTime(getTimeNow()); } private Photo setFields(Long photo_id, Long roll_id, String uniqueId, Integer isDeleted){ return new Photo( photo_id, roll_id, parseDouble(latitudeEt.getText().toString()), parseDouble(longituteEt.getText().toString()), timestamp.getTime() / 1000, descriptionEt.getText().toString(), System.currentTimeMillis(), uniqueId, isDeleted, 0, filmRollDbHelper ); }; private void setListeners() { mGPS.setOnGotLocationListener(new LocationHelper.OnGotLocationListener() { @Override public void OnGotLocation(Location location) { if (latitudeEt.getText().length() == 0 && longituteEt.getText().length() == 0) { setLocation(); } } }); resetTimeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setTime(getTimeNow()); } }); resetLocationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setLocation(); } }); addPhotoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { filmRollDbHelper.insertPhoto(setFields( null, roll_id, UUID.randomUUID().toString(), 0) ); snapMode(); } }); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { snapMode(); } }); savePhotoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { editingPhoto = setFields(editingPhoto.getPhotoId(), editingPhoto.getRollId(), editingPhoto.getUniqueID(), editingPhoto.getDeleted()); filmRollDbHelper.updatePhoto(editingPhoto); snapMode(); } }); deletePhotoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { filmRollDbHelper.removePhoto(editingPhoto.getPhotoId(), System.currentTimeMillis()); snapMode(); refreshDatasets(); } }); timeTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new SlideDateTimePicker.Builder(getSupportFragmentManager()).setListener(new SlideDateTimeListener() { @Override public void onDateTimeSet(Date date) { setTime(date); } }) .setInitialDate(timestamp) .build().show(); } }); adapter.setOnItemSelectedListener(new PhotoAdapter.OnItemSelectedListener() { @Override public void onItemSelected(int position) { editMode(adapter.getItem(position)); } }); } private Long getTimestamp() { return System.currentTimeMillis() / 1000; } private Date getTimeNow(){ // correct time in the UTC timezone // represented as seconds since January 1, 1970 00:00:00 UTC return new Date(System.currentTimeMillis()); } private void setTime(Date time){ timestamp = time; timeTv.setText(dateFormat.format(timestamp)); } private void setLocation() { if (mGPS.getLongitude() != null && mGPS.getLatitude() != null) { setLocation(mGPS.getLatitude(), mGPS.getLongitude()); } } private void setLocation(Double latitude, Double longitude) { latitudeEt.setText(String.format("%.6f", latitude)); longituteEt.setText(String.format("%.6f", longitude)); } @Override public void onBackPressed() { super.onBackPressed(); finish(); } public void reloadAddresses() { for (int i = 0; i < adapter.getItemCount(); i++) { final Photo photo = adapter.getItem(i); if (!photo.mustUpdateAddress()) { continue; } filmRollDbHelper.setLastAddressUpdateTimestamp(photo.getPhotoId(), System.currentTimeMillis() / 1000); mGPS.getAddress(photo.getLocation(), new LocationHelper.OnGotAddressListener() { @Override public void OnGotAddress(Location location, String address) { if (address == null) { return; } filmRollDbHelper.updateAddress(location, address); refreshDatasets(); }; }); } } private Double parseDouble(String s) { try { return Double.valueOf(s); } catch(NumberFormatException e) { return null; } } }
/* * 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.druid.query.groupby.epinephelinae; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import org.apache.druid.java.util.common.IAE; import org.apache.druid.java.util.common.ISE; import org.apache.druid.java.util.common.logger.Logger; import org.apache.druid.java.util.common.parsers.CloseableIterator; import org.apache.druid.query.QueryContexts; import org.apache.druid.query.QueryTimeoutException; import org.apache.druid.query.aggregation.AggregatorFactory; import org.apache.druid.query.aggregation.BufferAggregator; import org.apache.druid.segment.ColumnSelectorFactory; import java.nio.ByteBuffer; import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; /** * A streaming grouper which can aggregate sorted inputs. This grouper can aggregate while its iterator is being * consumed. The aggregation thread and the iterating thread can be different. * * This grouper is backed by an off-heap circular array. The reading thread is able to read data from an array slot * only when aggregation for the grouping key correspoing to that slot is finished. Since the reading and writing * threads cannot access the same array slot at the same time, they can read/write data without contention. * * This class uses the spinlock for waiting for at least one slot to become available when the array is empty or full. * If the array is empty, the reading thread waits for the aggregation for an array slot is finished. If the array is * full, the writing thread waits for the reading thread to read at least one aggregate from the array. */ public class StreamingMergeSortedGrouper<KeyType> implements Grouper<KeyType> { private static final Logger LOG = new Logger(StreamingMergeSortedGrouper.class); private static final long DEFAULT_TIMEOUT_NS = TimeUnit.SECONDS.toNanos(5); // default timeout for spinlock // Threashold time for spinlocks in increaseWriteIndex() and increaseReadIndex(). The waiting thread calls // Thread.yield() after this threadhold time elapses. private static final long SPIN_FOR_TIMEOUT_THRESHOLD_NS = 1000L; private final Supplier<ByteBuffer> bufferSupplier; private final KeySerde<KeyType> keySerde; private final BufferAggregator[] aggregators; private final int[] aggregatorOffsets; private final int keySize; private final int recordSize; // size of (key + all aggregates) // Timeout for the current query. // The query must fail with a timeout exception if System.nanoTime() >= queryTimeoutAtNs. This is used in the // spinlocks to prevent the writing thread from being blocked if the iterator of this grouper is not consumed due to // some failures which potentially makes the whole system being paused. private final long queryTimeoutAtNs; private final boolean hasQueryTimeout; // Below variables are initialized when init() is called. private ByteBuffer buffer; private int maxNumSlots; private boolean initialized; /** * Indicate that this grouper consumed the last input or not. The writing thread must set this value to true by * calling {@link #finish()} when it's done. This variable is always set by the writing thread and read by the * reading thread. */ private volatile boolean finished; /** * Current write index of the array. This points to the array slot where the aggregation is currently performed. Its * initial value is -1 which means any data are not written yet. Since it's assumed that the input is sorted by the * grouping key, this variable is moved to the next slot whenever a new grouping key is found. Once it reaches the * last slot of the array, it moves to the first slot. * * This is always moved ahead of {@link #nextReadIndex}. If the array is full, this variable * cannot be moved until {@link #nextReadIndex} is moved. See {@link #increaseWriteIndex()} for more details. This * variable is always incremented by the writing thread and read by both the writing and the reading threads. */ private volatile int curWriteIndex; /** * Next read index of the array. This points to the array slot which the reading thread will read next. Its initial * value is -1 which means any data are not read yet. This variable can point an array slot only when the aggregation * for that slot is finished. Once it reaches the last slot of the array, it moves to the first slot. * * This always follows {@link #curWriteIndex}. If the array is empty, this variable cannot be moved until the * aggregation for at least one grouping key is finished which in turn {@link #curWriteIndex} is moved. See * {@link #iterator()} for more details. This variable is always incremented by the reading thread and read by both * the writing and the reading threads. */ private volatile int nextReadIndex; /** * Returns the minimum buffer capacity required for this grouper. This grouper keeps track read/write indexes * and they cannot point the same array slot at the same time. Since the read/write indexes move circularly, one * extra slot is needed in addition to the read/write slots. Finally, the required minimum buffer capacity is * 3 * record size. * * @return required minimum buffer capacity */ public static <KeyType> int requiredBufferCapacity( KeySerde<KeyType> keySerde, AggregatorFactory[] aggregatorFactories ) { int recordSize = keySerde.keySize(); for (AggregatorFactory aggregatorFactory : aggregatorFactories) { recordSize += aggregatorFactory.getMaxIntermediateSizeWithNulls(); } return recordSize * 3; } StreamingMergeSortedGrouper( final Supplier<ByteBuffer> bufferSupplier, final KeySerde<KeyType> keySerde, final ColumnSelectorFactory columnSelectorFactory, final AggregatorFactory[] aggregatorFactories, final long queryTimeoutAtMs ) { this.bufferSupplier = bufferSupplier; this.keySerde = keySerde; this.aggregators = new BufferAggregator[aggregatorFactories.length]; this.aggregatorOffsets = new int[aggregatorFactories.length]; this.keySize = keySerde.keySize(); int offset = keySize; for (int i = 0; i < aggregatorFactories.length; i++) { aggregators[i] = aggregatorFactories[i].factorizeBuffered(columnSelectorFactory); aggregatorOffsets[i] = offset; offset += aggregatorFactories[i].getMaxIntermediateSizeWithNulls(); } this.recordSize = offset; // queryTimeoutAtMs comes from System.currentTimeMillis(), but we should use System.nanoTime() to check timeout in // this class. See increaseWriteIndex() and increaseReadIndex(). this.hasQueryTimeout = queryTimeoutAtMs != QueryContexts.NO_TIMEOUT; final long timeoutNs = hasQueryTimeout ? TimeUnit.MILLISECONDS.toNanos(queryTimeoutAtMs - System.currentTimeMillis()) : QueryContexts.NO_TIMEOUT; this.queryTimeoutAtNs = System.nanoTime() + timeoutNs; } @Override public void init() { if (!initialized) { buffer = bufferSupplier.get(); maxNumSlots = buffer.capacity() / recordSize; Preconditions.checkState( maxNumSlots > 2, "Buffer[%s] should be large enough to store at least three records[%s]", buffer.capacity(), recordSize ); reset(); initialized = true; } } @Override public boolean isInitialized() { return initialized; } @Override public AggregateResult aggregate(KeyType key, int notUsed) { return aggregate(key); } @Override public AggregateResult aggregate(KeyType key) { try { final ByteBuffer keyBuffer = keySerde.toByteBuffer(key); if (keyBuffer.remaining() != keySize) { throw new IAE( "keySerde.toByteBuffer(key).remaining[%s] != keySerde.keySize[%s], buffer was the wrong size?!", keyBuffer.remaining(), keySize ); } final int prevRecordOffset = curWriteIndex * recordSize; if (curWriteIndex == -1 || !keyEquals(keyBuffer, buffer, prevRecordOffset)) { // Initialize a new slot for the new key. This may be potentially blocked if the array is full until at least // one slot becomes available. initNewSlot(keyBuffer); } final int curRecordOffset = curWriteIndex * recordSize; for (int i = 0; i < aggregatorOffsets.length; i++) { aggregators[i].aggregate(buffer, curRecordOffset + aggregatorOffsets[i]); } return AggregateResult.ok(); } catch (RuntimeException e) { finished = true; throw e; } } /** * Checks two keys contained in the given buffers are same. * * @param curKeyBuffer the buffer for the given key from {@link #aggregate(Object)} * @param buffer the whole array buffer * @param bufferOffset the key offset of the buffer * * @return true if the two buffers are same. */ private boolean keyEquals(ByteBuffer curKeyBuffer, ByteBuffer buffer, int bufferOffset) { // Since this method is frequently called per each input row, the compare performance matters. int i = 0; for (; i + Long.BYTES <= keySize; i += Long.BYTES) { if (curKeyBuffer.getLong(i) != buffer.getLong(bufferOffset + i)) { return false; } } if (i + Integer.BYTES <= keySize) { // This can be called at most once because we already compared using getLong() in the above. if (curKeyBuffer.getInt(i) != buffer.getInt(bufferOffset + i)) { return false; } i += Integer.BYTES; } for (; i < keySize; i++) { if (curKeyBuffer.get(i) != buffer.get(bufferOffset + i)) { return false; } } return true; } /** * Initialize a new slot for a new grouping key. This may be potentially blocked if the array is full until at least * one slot becomes available. */ private void initNewSlot(ByteBuffer newKey) { // Wait if the array is full and increase curWriteIndex increaseWriteIndex(); final int recordOffset = recordSize * curWriteIndex; buffer.position(recordOffset); buffer.put(newKey); for (int i = 0; i < aggregators.length; i++) { aggregators[i].init(buffer, recordOffset + aggregatorOffsets[i]); } } /** * Wait for {@link #nextReadIndex} to be moved if necessary and move {@link #curWriteIndex}. */ private void increaseWriteIndex() { final long startAtNs = System.nanoTime(); final long queryTimeoutAtNs = getQueryTimeoutAtNs(startAtNs); final long spinTimeoutAtNs = startAtNs + SPIN_FOR_TIMEOUT_THRESHOLD_NS; long timeoutNs = queryTimeoutAtNs - startAtNs; long spinTimeoutNs = SPIN_FOR_TIMEOUT_THRESHOLD_NS; // In the below, we check that the array is full and wait for at least one slot to become available. // // nextReadIndex is a volatile variable and the changes on it are continuously checked until they are seen in // the while loop. See the following links. // * http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1.4 // * http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5 // * https://stackoverflow.com/questions/11761552/detailed-semantics-of-volatile-regarding-timeliness-of-visibility if (curWriteIndex == maxNumSlots - 1) { // We additionally check that nextReadIndex is -1 here because the writing thread should wait for the reading // thread to start reading only when the writing thread tries to overwrite the first slot for the first time. // The below condition is checked in a while loop instead of using a lock to avoid frequent thread park. while ((nextReadIndex == -1 || nextReadIndex == 0) && !Thread.currentThread().isInterrupted()) { if (timeoutNs <= 0L) { throw new QueryTimeoutException(); } // Thread.yield() should not be called from the very beginning if (spinTimeoutNs <= 0L) { Thread.yield(); } long now = System.nanoTime(); timeoutNs = queryTimeoutAtNs - now; spinTimeoutNs = spinTimeoutAtNs - now; } // Changes on nextReadIndex happens-before changing curWriteIndex. curWriteIndex = 0; } else { final int nextWriteIndex = curWriteIndex + 1; // The below condition is checked in a while loop instead of using a lock to avoid frequent thread park. while ((nextWriteIndex == nextReadIndex) && !Thread.currentThread().isInterrupted()) { if (timeoutNs <= 0L) { throw new QueryTimeoutException(); } // Thread.yield() should not be called from the very beginning if (spinTimeoutNs <= 0L) { Thread.yield(); } long now = System.nanoTime(); timeoutNs = queryTimeoutAtNs - now; spinTimeoutNs = spinTimeoutAtNs - now; } // Changes on nextReadIndex happens-before changing curWriteIndex. curWriteIndex = nextWriteIndex; } } @Override public void reset() { curWriteIndex = -1; nextReadIndex = -1; finished = false; } @Override public void close() { for (BufferAggregator aggregator : aggregators) { try { aggregator.close(); } catch (Exception e) { LOG.warn(e, "Could not close aggregator [%s], skipping.", aggregator); } } } /** * Signal that no more inputs are added. Must be called after {@link #aggregate(Object)} is called for the last input. */ public void finish() { increaseWriteIndex(); // Once finished is set, curWriteIndex must not be changed. This guarantees that the remaining number of items in // the array is always decreased as the reading thread proceeds. See hasNext() and remaining() below. finished = true; } /** * Return a sorted iterator. This method can be called safely while writing, and the iterating thread and the writing * thread can be different. The result iterator always returns sorted results. This method should be called only one * time per grouper. * * @return a sorted iterator */ public CloseableIterator<Entry<KeyType>> iterator() { if (!initialized) { throw new ISE("Grouper should be initialized first"); } return new CloseableIterator<Entry<KeyType>>() { { // Wait for some data to be ready and initialize nextReadIndex. increaseReadIndexTo(0); } @Override public boolean hasNext() { // If setting finished happens-before the below check, curWriteIndex isn't changed anymore and thus remainig() // can be computed safely because nextReadIndex is changed only by the reading thread. // Otherwise, hasNext() always returns true. // // The below line can be executed between increasing curWriteIndex and setting finished in // StreamingMergeSortedGrouper.finish(), but it is also a valid case because there should be at least one slot // which is not read yet before finished is set. return !finished || remaining() > 0; } /** * Calculate the number of remaining items in the array. Must be called only when * {@link StreamingMergeSortedGrouper#finished} is true. * * @return the number of remaining items */ private int remaining() { if (curWriteIndex >= nextReadIndex) { return curWriteIndex - nextReadIndex; } else { return (maxNumSlots - nextReadIndex) + curWriteIndex; } } @Override public Entry<KeyType> next() { if (!hasNext()) { throw new NoSuchElementException(); } // Here, nextReadIndex should be valid which means: // - a valid array index which should be >= 0 and < maxNumSlots // - an index of the array slot where the aggregation for the corresponding grouping key is done // - an index of the array slot which is not read yet final int recordOffset = recordSize * nextReadIndex; final KeyType key = keySerde.fromByteBuffer(buffer, recordOffset); final Object[] values = new Object[aggregators.length]; for (int i = 0; i < aggregators.length; i++) { values[i] = aggregators[i].get(buffer, recordOffset + aggregatorOffsets[i]); } final int targetIndex = nextReadIndex == maxNumSlots - 1 ? 0 : nextReadIndex + 1; // Wait if the array is empty until at least one slot becomes available for read, and then increase // nextReadIndex. increaseReadIndexTo(targetIndex); return new Entry<>(key, values); } /** * Wait for {@link StreamingMergeSortedGrouper#curWriteIndex} to be moved if necessary and move * {@link StreamingMergeSortedGrouper#nextReadIndex}. * * @param target the target index {@link StreamingMergeSortedGrouper#nextReadIndex} will move to */ private void increaseReadIndexTo(int target) { // Check that the array is empty and wait for at least one slot to become available. // // curWriteIndex is a volatile variable and the changes on it are continuously checked until they are seen in // the while loop. See the following links. // * http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1.4 // * http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5 // * https://stackoverflow.com/questions/11761552/detailed-semantics-of-volatile-regarding-timeliness-of-visibility final long startAtNs = System.nanoTime(); final long queryTimeoutAtNs = getQueryTimeoutAtNs(startAtNs); final long spinTimeoutAtNs = startAtNs + SPIN_FOR_TIMEOUT_THRESHOLD_NS; long timeoutNs = queryTimeoutAtNs - startAtNs; long spinTimeoutNs = SPIN_FOR_TIMEOUT_THRESHOLD_NS; // The below condition is checked in a while loop instead of using a lock to avoid frequent thread park. while ((curWriteIndex == -1 || target == curWriteIndex) && !finished && !Thread.currentThread().isInterrupted()) { if (timeoutNs <= 0L) { throw new QueryTimeoutException(); } // Thread.yield() should not be called from the very beginning if (spinTimeoutNs <= 0L) { Thread.yield(); } long now = System.nanoTime(); timeoutNs = queryTimeoutAtNs - now; spinTimeoutNs = spinTimeoutAtNs - now; } // Changes on curWriteIndex happens-before changing nextReadIndex. nextReadIndex = target; } @Override public void close() { // do nothing } }; } private long getQueryTimeoutAtNs(long startAtNs) { return hasQueryTimeout ? queryTimeoutAtNs : startAtNs + DEFAULT_TIMEOUT_NS; } /** * Return a sorted iterator. This method can be called safely while writing and iterating thread and writing thread * can be different. The result iterator always returns sorted results. This method should be called only one time * per grouper. * * @param sorted not used * * @return a sorted iterator */ @Override public CloseableIterator<Entry<KeyType>> iterator(boolean sorted) { return iterator(); } }
/* Derby - Class org.apache.derby.impl.sql.compile.CreateIndexNode 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.derby.impl.sql.compile; import java.util.HashSet; import java.util.List; import java.util.Properties; import org.apache.derby.catalog.UUID; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.reference.Limits; import org.apache.derby.iapi.reference.Property; import org.apache.derby.iapi.reference.SQLState; import org.apache.derby.iapi.services.property.PropertyUtil; import org.apache.derby.iapi.services.sanity.SanityManager; import org.apache.derby.iapi.sql.compile.CompilerContext; import org.apache.derby.iapi.sql.dictionary.ColumnDescriptor; import org.apache.derby.iapi.sql.dictionary.DataDictionary; import org.apache.derby.iapi.sql.dictionary.SchemaDescriptor; import org.apache.derby.iapi.sql.dictionary.TableDescriptor; import org.apache.derby.iapi.sql.execute.ConstantAction; import org.apache.derby.iapi.types.DataTypeDescriptor; /** * A CreateIndexNode is the root of a QueryTree that represents a CREATE INDEX * statement. * */ public class CreateIndexNode extends DDLStatementNode { boolean unique; DataDictionary dd = null; Properties properties; String indexType; TableName indexName; TableName tableName; List columnNameList; String[] columnNames = null; boolean[] isAscending; int[] boundColumnIDs; TableDescriptor td; /** * Initializer for a CreateIndexNode * * @param unique True means it's a unique index * @param indexType The type of index * @param indexName The name of the index * @param tableName The name of the table the index will be on * @param columnNameList A list of column names, in the order they * appear in the index. * @param properties The optional properties list associated with the index. * * @exception StandardException Thrown on error */ public void init( Object unique, Object indexType, Object indexName, Object tableName, Object columnNameList, Object properties) throws StandardException { initAndCheck(indexName); this.unique = ((Boolean) unique).booleanValue(); this.indexType = (String) indexType; this.indexName = (TableName) indexName; this.tableName = (TableName) tableName; this.columnNameList = (List) columnNameList; this.properties = (Properties) properties; } /** * Convert this object to a String. See comments in QueryTreeNode.java * for how this should be done for tree printing. * * @return This object as a String */ public String toString() { if (SanityManager.DEBUG) { return super.toString() + "unique: " + unique + "\n" + "indexType: " + indexType + "\n" + "indexName: " + indexName + "\n" + "tableName: " + tableName + "\n" + "properties: " + properties + "\n"; } else { return ""; } } public String statementToString() { return "CREATE INDEX"; } public boolean getUniqueness() { return unique; } public String getIndexType() { return indexType; } public TableName getIndexName() { return indexName; } public UUID getBoundTableID() { return td.getUUID(); } public Properties getProperties() { return properties; } public TableName getIndexTableName() {return tableName; } public String[] getColumnNames() { return columnNames; } // get 1-based column ids public int[] getKeyColumnIDs() { return boundColumnIDs; } public boolean[] getIsAscending() { return isAscending; } // We inherit the generate() method from DDLStatementNode. /** * Bind this CreateIndexNode. This means doing any static error * checking that can be done before actually creating the table. * For example, verifying that the column name list does not * contain any duplicate column names. * * @exception StandardException Thrown on error */ public void bindStatement() throws StandardException { CompilerContext cc = getCompilerContext(); SchemaDescriptor sd; int columnCount; sd = getSchemaDescriptor(); td = getTableDescriptor(tableName); //throw an exception if user is attempting to create an index on a temporary table if (td.getTableType() == TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE) { throw StandardException.newException(SQLState.LANG_NOT_ALLOWED_FOR_DECLARED_GLOBAL_TEMP_TABLE); } //If total number of indexes on the table so far is more than 32767, then we need to throw an exception if (td.getTotalNumberOfIndexes() > Limits.DB2_MAX_INDEXES_ON_TABLE) { throw StandardException.newException(SQLState.LANG_TOO_MANY_INDEXES_ON_TABLE, String.valueOf(td.getTotalNumberOfIndexes()), tableName, String.valueOf(Limits.DB2_MAX_INDEXES_ON_TABLE)); } /* Validate the column name list */ verifyAndGetUniqueNames(); columnCount = columnNames.length; boundColumnIDs = new int[ columnCount ]; // Verify that the columns exist for (int i = 0; i < columnCount; i++) { ColumnDescriptor columnDescriptor; columnDescriptor = td.getColumnDescriptor(columnNames[i]); if (columnDescriptor == null) { throw StandardException.newException(SQLState.LANG_COLUMN_NOT_FOUND_IN_TABLE, columnNames[i], tableName); } boundColumnIDs[ i ] = columnDescriptor.getPosition(); // Don't allow a column to be created on a non-orderable type if ( ! columnDescriptor.getType().getTypeId(). orderable(getClassFactory())) { throw StandardException.newException(SQLState.LANG_COLUMN_NOT_ORDERABLE_DURING_EXECUTION, columnDescriptor.getType().getTypeId().getSQLTypeName()); } } /* Check for number of key columns to be less than 16 to match DB2 */ if (columnCount > 16) throw StandardException.newException(SQLState.LANG_TOO_MANY_INDEX_KEY_COLS); /* See if the index already exists in this schema. * NOTE: We still need to check at execution time * since the index name is only unique to the schema, * not the table. */ // if (dd.getConglomerateDescriptor(indexName.getTableName(), sd, false) != null) // { // throw StandardException.newException(SQLState.LANG_OBJECT_ALREADY_EXISTS_IN_OBJECT, // "Index", // indexName.getTableName(), // "schema", // sd.getSchemaName()); // } /* Statement is dependent on the TableDescriptor */ getCompilerContext().createDependency(td); } /** * Return true if the node references SESSION schema tables (temporary or permanent) * * @return true if references SESSION schema tables, else false * * @exception StandardException Thrown on error */ public boolean referencesSessionSchema() throws StandardException { //If create index is on a SESSION schema table, then return true. return isSessionSchema(td.getSchemaName()); } /** * Create the Constant information that will drive the guts of Execution. * * @exception StandardException Thrown on failure */ public ConstantAction makeConstantAction() throws StandardException { SchemaDescriptor sd = getSchemaDescriptor(); int columnCount = columnNames.length; int approxLength = 0; boolean index_has_long_column = false; // bump the page size for the index, // if the approximate sizes of the columns in the key are // greater than the bump threshold. // Ideally, we would want to have atleast 2 or 3 keys fit in one page // With fix for beetle 5728, indexes on long types is not allowed // so we do not have to consider key columns of long types for (int i = 0; i < columnCount; i++) { ColumnDescriptor columnDescriptor = td.getColumnDescriptor(columnNames[i]); DataTypeDescriptor dts = columnDescriptor.getType(); approxLength += dts.getTypeId().getApproximateLengthInBytes(dts); } if (approxLength > Property.IDX_PAGE_SIZE_BUMP_THRESHOLD) { if (((properties == null) || (properties.get(Property.PAGE_SIZE_PARAMETER) == null)) && (PropertyUtil.getServiceProperty( getLanguageConnectionContext().getTransactionCompile(), Property.PAGE_SIZE_PARAMETER) == null)) { // do not override the user's choice of page size, whether it // is set for the whole database or just set on this statement. if (properties == null) properties = new Properties(); properties.put( Property.PAGE_SIZE_PARAMETER, Property.PAGE_SIZE_DEFAULT_LONG); } } return getGenericConstantActionFactory().getCreateIndexConstantAction( false, // not for CREATE TABLE unique, false, //its not a UniqueWithDuplicateNulls Index indexType, sd.getSchemaName(), indexName.getTableName(), tableName.getTableName(), td.getUUID(), columnNames, isAscending, false, null, properties); } /** * Check the uniqueness of the column names within the derived column list. * * @exception StandardException Thrown if column list contains a * duplicate name. */ private void verifyAndGetUniqueNames() throws StandardException { int size = columnNameList.size(); HashSet seenNames = new HashSet(size + 2, 0.999f); columnNames = new String[size]; isAscending = new boolean[size]; for (int index = 0; index < size; index++) { /* Verify that this column's name is unique within the list * Having a space at the end meaning descending on the column */ columnNames[index] = (String) columnNameList.get(index); if (columnNames[index].endsWith(" ")) { columnNames[index] = columnNames[index].substring(0, columnNames[index].length() - 1); isAscending[index] = false; } else isAscending[index] = true; boolean alreadySeen = !seenNames.add(columnNames[index]); if (alreadySeen) { throw StandardException.newException(SQLState.LANG_DUPLICATE_COLUMN_NAME_CREATE_INDEX, columnNames[index]); } } } }
package edu.psu.compbio.seqcode.gse.tools.motifs; import edu.psu.compbio.seqcode.gse.datasets.binding.*; import edu.psu.compbio.seqcode.gse.datasets.chipchip.ChipChipBayes; import edu.psu.compbio.seqcode.gse.datasets.chipchip.ChipChipMetadataLoader; import edu.psu.compbio.seqcode.gse.datasets.chipchip.Experiment; import edu.psu.compbio.seqcode.gse.datasets.general.NamedRegion; import edu.psu.compbio.seqcode.gse.datasets.general.Region; import edu.psu.compbio.seqcode.gse.datasets.locators.BayesLocator; import edu.psu.compbio.seqcode.gse.datasets.species.Gene; import edu.psu.compbio.seqcode.gse.datasets.species.Genome; import edu.psu.compbio.seqcode.gse.datasets.species.Organism; import edu.psu.compbio.seqcode.gse.ewok.verbs.BayesBindingGenerator; import edu.psu.compbio.seqcode.gse.ewok.verbs.ChromRegionIterator; import edu.psu.compbio.seqcode.gse.ewok.verbs.FastaWriter; import edu.psu.compbio.seqcode.gse.ewok.verbs.RefGeneGenerator; import edu.psu.compbio.seqcode.gse.ewok.verbs.RegionSorter; import edu.psu.compbio.seqcode.gse.ewok.verbs.binding.BindingExpander; import edu.psu.compbio.seqcode.gse.utils.NotFoundException; import edu.psu.compbio.seqcode.gse.utils.io.DatasetsGeneralIO; import java.util.*; import java.io.*; import java.sql.SQLException; public class MotifFastaWriter { private static final double PROB_THRESHOLD = 0.3; private static final double SIZE_THRESHOLD = 2.0; //should be in range from 2.0 - 20 or 30 private static final int PEAK_OFFSET_THRESHOLD = 200; private static final int PEAK_SEQUENCE_WINDOW_SIZE = 250; private static final String GENE_TABLE = "refGene"; private static final int GENE_WINDOW_SIZE = 30000; private static final String DELIM = ","; /** * * @param organism * @param genome * @param table * @param expt * @param version * @param goodChroms * @param filePrefix * @param outputUnmatchedPeaks * @param outputGenes * @param outputNonGenePeaks * @return */ public static Vector<Region> getDataRegionsFromPeaks(Organism organism, Genome genome, String table, String expt, String version, String type) { Vector<Region> dataRegions = new Vector<Region>(); try { BindingScanLoader bsl = new BindingScanLoader(); String bslVersion = expt + "," + version; Collection<BindingScan> bs = bsl.loadScans(genome, bslVersion, type); BindingExpander be = new BindingExpander(bsl, bs); //Scan through all the chromosomes Iterator<NamedRegion> chroms = new ChromRegionIterator(genome); while (chroms.hasNext()) { NamedRegion currentChrom = chroms.next(); String chromName = currentChrom.getName(); Vector<int[]> peaks = new Vector<int[]>(); System.out.println("\n"); //System.out.println("expt " + expts[i] + ", Chrom " + chromName + ", replicate " + j + ":"); Iterator<BindingEvent> bindingIterator = be.execute(currentChrom); RegionSorter<BindingEvent> rs = new RegionSorter<BindingEvent>(); Iterator<BindingEvent> sortedBindingIterator = rs.execute(bindingIterator); if (!sortedBindingIterator.hasNext()) { System.out.println("expt " + expt + ", Chrom " + chromName + ": No Binding Events"); } while (sortedBindingIterator.hasNext()) { BindingEvent event = sortedBindingIterator.next(); int[] peak = new int[] {event.getStart(), event.getEnd()}; peaks.addElement(peak); } System.out.println("expt " + expt + ", Chrom " + chromName + ": " + peaks.size() + " peaks"); List<NamedRegion> peakRegions = processPeakData(peaks, genome, chromName, currentChrom.getWidth()); dataRegions.addAll(peakRegions); } } catch (SQLException sqlex) { sqlex.printStackTrace(); } return dataRegions; } /** * Combine peaks that are closest to each other and generate regions * @param repPeakInfo * @return */ public static List<NamedRegion> processPeakData(Vector<int[]> peaks, Genome genome, String chromName, int chromLength) { List<NamedRegion> processedPeaks = new Vector<NamedRegion>(); int index = 0; Vector<int[]> peakSequence = findNearbyPeakSequence(peaks, index, PEAK_OFFSET_THRESHOLD); while (peakSequence.size() > 0) { //System.out.println("Sequential peaks: " + peakSequence.size()); int start = (peakSequence.elementAt(0))[0]; int end = (peakSequence.elementAt(peakSequence.size()-1))[1]; String regionName = chromName + ":" + start + "-" + end; int middle = (start + end) / 2; Gene[] closestGenes = findClosestGenes(genome, GENE_TABLE, chromName, middle, GENE_WINDOW_SIZE, GENE_WINDOW_SIZE); if ((closestGenes[0] != null) || (closestGenes[1] != null)) { int upDist = Integer.MAX_VALUE; int downDist = Integer.MAX_VALUE; if (closestGenes[0] != null) { upDist = start - closestGenes[0].getStart(); } if (closestGenes[1] != null) { downDist = closestGenes[1].getStart() - start; } if ( upDist < downDist) { regionName = regionName + ", " + downDist + " bp downstream of " + closestGenes[0].getName(); } else { regionName = regionName + ", " + upDist + " bp upstream of " + closestGenes[1].getName(); } } int sequenceStart = (int)Math.max(start - (PEAK_SEQUENCE_WINDOW_SIZE/2), 0); int sequenceEnd = (int)Math.min(end + (PEAK_SEQUENCE_WINDOW_SIZE/2), chromLength); NamedRegion region = new NamedRegion(genome, chromName, sequenceStart, sequenceEnd, regionName); processedPeaks.add(region); index = index + peakSequence.size(); peakSequence = findNearbyPeakSequence(peaks, index, PEAK_OFFSET_THRESHOLD); } return processedPeaks; } /** * * @param dataRegions * @param outputFilename */ public static void writeDataRegions(Vector<Region> dataRegions, String outputFilename) { FastaWriter writer = null; try { writer = new FastaWriter(outputFilename); writer.consume(dataRegions.iterator()); } catch (FileNotFoundException fnfex) { fnfex.printStackTrace(); } catch (IOException ioex) { ioex.printStackTrace(); } finally { if (writer != null) { writer.close(); } } } /** * * @param dataRegions * @param outputFilename */ public static void writeDataRegions(Vector<Region> dataRegions, String outputFilename, int lineLength) { FastaWriter writer = null; try { writer = new FastaWriter(outputFilename); writer.setLineLength(lineLength); writer.consume(dataRegions.iterator()); } catch (FileNotFoundException fnfex) { fnfex.printStackTrace(); } catch (IOException ioex) { ioex.printStackTrace(); } finally { if (writer != null) { writer.close(); } } } /** * Find a sequence of consecutive nearby peaks * This method should eventually move into another class * * @param repPeakInfo * @param indices * @param maxDistance * @return */ public static Vector<int[]> findNearbyPeakSequence(Vector<int[]> peaks, int index, int maxDistance) { Vector<int[]> peakSequence = new Vector<int[]>(); int prevPeakLocation = -1; //find the first peak from among the replicates if (index < peaks.size()) { prevPeakLocation = (peaks.elementAt(index))[0]; } if (prevPeakLocation == -1) { //no peaks, return an empty sequence return peakSequence; } else { peakSequence.addElement(peaks.elementAt(index)); index++; } /** * continue finding peaks until consecutive peaks are farther apart than * the specified max distance */ boolean done = false; while (!done) { int nextPeakLocation = -1; if (index < peaks.size()) { nextPeakLocation = (peaks.elementAt(index))[0]; } if ((nextPeakLocation == -1) || ((nextPeakLocation - prevPeakLocation) > maxDistance)) { /** * stop if no more peaks could be found, or consecutive peaks * are too far apart */ done = true; } else { //peaks are close together peakSequence.addElement(peaks.elementAt(index)); index++; prevPeakLocation = nextPeakLocation; } } return peakSequence; } /** * Find the genes closest to the specified location * This method should eventually move into another class * @param genome * @param chromName * @param loc * @return */ public static Gene[] findClosestGenes(Genome genome, String table, String chromName, int loc, int upLimit, int downLimit) { RefGeneGenerator rgg = new RefGeneGenerator(genome, table); int regionStart = (int)Math.max(loc - upLimit, 0); int regionEnd = (int)(loc + downLimit); Region region = new Region(genome, chromName, regionStart, regionEnd); Iterator<Gene> geneIter = rgg.execute(region); Gene[] closestGenes = new Gene[2]; Arrays.fill(closestGenes, null); int[] closestDistances = new int[] {Integer.MAX_VALUE, Integer.MAX_VALUE }; while (geneIter.hasNext()) { Gene currentGene = geneIter.next(); int currentStart = currentGene.getStart(); int currentDist = (int)Math.abs(loc - currentStart); if (currentStart < loc) { if (currentDist < closestDistances[0]) { closestGenes[0] = currentGene; closestDistances[0] = currentDist; } } else { if (currentDist < closestDistances[1]) { closestGenes[1] = currentGene; closestDistances[1] = currentDist; } } } return closestGenes; } /** * @param args */ public static void main(String[] args) { /** * write out fasta files for the regions of the genome tiled by the * Hox arrays in the ppg project */ // try { // String filename = "G:\\projects\\ppg\\domains\\well_tiled_regions.txt"; // String outputFilename = ""; // // Organism mouse = Organism.getOrganism("Mus musculus"); // Genome mm8 = mouse.getGenome("mm8"); // Vector<Region> dataRegions = MotifFastaWriter.getDataRegionsFromFile(mm8, filename); // MotifFastaWriter.writeDataRegions(dataRegions, outputFilename); // } // catch (NotFoundException ex) { // // TODO Auto-generated catch block // ex.printStackTrace(); // } /** * write out fasta files for regions where peaks have been called */ try { Organism mouse = Organism.getOrganism("Mus musculus"); Genome mm8 = mouse.getGenome("mm8"); String expt = "Mm Hb9:HBG3:Hb9 Stage vs WCE:HBG3:Hb9 Stage"; String version = "1/25/07, default params"; // String outputFilename = "hb9_peak_sequences.fasta"; String type = "BayesBindingGenerator"; // Vector<Region> dataRegions = MotifFastaWriter.getDataRegionsFromPeaks(mouse, mm8, GENE_TABLE, expt, version, type); String inputFilename = "/Users/rca/matlab scratch/Sing_Smad1_top25_peaks_regions.txt"; String outputFilename = "/Users/rca/matlab scratch/Sing_Smad1_25.fasta"; Vector<Region> dataRegions = DatasetsGeneralIO.readRegionsFromFile(mm8, inputFilename); MotifFastaWriter.writeDataRegions(dataRegions, outputFilename, 102); } catch (IOException ioex) { ioex.printStackTrace(); } catch (NotFoundException ex) { // TODO Auto-generated catch block ex.printStackTrace(); } } }
package com.koch.ambeth.merge.server; import java.util.function.Consumer; import com.koch.ambeth.dot.IDotNode; import com.koch.ambeth.dot.IDotWriter; import com.koch.ambeth.merge.IFimExtension; import com.koch.ambeth.persistence.api.IDatabaseMetaData; import com.koch.ambeth.persistence.api.IDirectedLinkMetaData; import com.koch.ambeth.persistence.api.IFieldMetaData; import com.koch.ambeth.persistence.api.ITableMetaData; import com.koch.ambeth.persistence.database.IDatabaseMappedListener; import com.koch.ambeth.service.merge.model.IEntityMetaData; import com.koch.ambeth.service.metadata.Member; import com.koch.ambeth.util.collections.ArrayList; public class DatabaseFimExtension implements IFimExtension, IDatabaseMappedListener { protected String sqlFieldFillColor = "#d0771eaa"; private final ArrayList<IDatabaseMetaData> databases = new ArrayList<IDatabaseMetaData>(); @Override public void databaseMapped(IDatabaseMetaData database) { synchronized (databases) { databases.add(database); } } @Override public Consumer<IDotWriter> extendEntityMetaDataGraph(final IEntityMetaData metaData) { synchronized (databases) { final ArrayList<ITableMetaData> tables = new ArrayList<>(); for (IDatabaseMetaData database : databases) { final ITableMetaData table = database.getTableByType(metaData.getEntityType(), true); if (table != null) { tables.add(table); continue; } } if (tables.isEmpty()) { return null; } return new Consumer<IDotWriter>() { @Override public void accept(IDotWriter dot) { for (ITableMetaData table : tables) { IDotNode node = dot.openNode(table); node.attribute("label", table.getName().replace('.', '\n')); node.attribute("shape", "cylinder"); node.attribute("style", "filled"); node.attribute("fontcolor", "#ffffffff"); node.attribute("fillcolor", "#d0771eaa"); node.endNode(); IDotNode sequenceNode = dot.openNode((Object) table.getSequenceName()); sequenceNode.attribute("label", table.getSequenceName().replace('.', '\n')); sequenceNode.attribute("shape", "cylinder"); sequenceNode.attribute("style", "filled"); sequenceNode.attribute("fontcolor", "#ffffffff"); sequenceNode.attribute("fillcolor", "#d00000aa"); sequenceNode.endNode(); dot.openEdge(metaData, table).attribute("arrowhead", "none").endEdge(); dot.openEdge(table, table.getSequenceName()).attribute("arrowhead", "none") .endEdge(); } } }; } } @Override public IDotNodeCallback extendEntityMetaDataNode(IEntityMetaData metaData) { return null; } @Override public Consumer<IDotWriter> extendPrimitiveMemberGraph(IEntityMetaData metaData, Member member) { return null; } @Override public IDotNodeCallback extendPrimitiveMemberNode(IEntityMetaData metaData, Member member) { synchronized (databases) { final ArrayList<IFieldMetaData> fields = new ArrayList<>(); for (IDatabaseMetaData database : databases) { final ITableMetaData table = database.getTableByType(metaData.getEntityType(), true); if (table == null) { continue; } IFieldMetaData field = table.getFieldByPropertyName(member.getName()); if (field != null) { fields.add(field); } } if (fields.isEmpty()) { return null; } return new IDotNodeCallback() { @Override public void accept(IDotNode node, StringBuilder sb) { for (IFieldMetaData field : fields) { sb.append('\n'); sb.append(field.getName()).append("::").append(field.getOriginalTypeName()); } } }; } } @Override public Consumer<IDotWriter> extendRelationMemberGraph(IEntityMetaData metaData, final Member member, IEntityMetaData targetMetaData) { // synchronized (databases) { // final ArrayList<IDirectedLinkMetaData> links = new ArrayList<>(); // for (IDatabaseMetaData database : databases) { // final ITableMetaData table = // database.getTableByType(metaData.getEntityType(), true); // if (table == null) { // continue; // } // IDirectedLinkMetaData link = table.getLinkByMemberName(member.getName()); // if (link != null) { // links.add(link); // } // } // if (links.isEmpty()) { // return null; // } // return new Consumer<IDotWriter>() { // @Override // public void accept(IDotWriter dot) { // for (IDirectedLinkMetaData link : links) { // IFieldMetaData fromField = link.getFromField(); // IFieldMetaData toField = link.getToField(); // // { // IDotNode node = dot.openNode(link); // node.attribute("label", "default"); // node.attribute("shape", "rectangle"); // node.attribute("style", "filled"); // node.attribute("fontcolor", "#ffffffff"); // node.attribute("fillcolor", "#77d01eaa"); // node.endNode(); // } // // dot.openEdge(member, link).attribute("arrowhead", "none").endEdge(); // // if (fromField != null && !dot.hasNode(fromField)) { // IDotNode node = dot.openNode(fromField); // node.attribute("label", fromField.getName()); // node.attribute("shape", "rectangle"); // node.attribute("style", "filled"); // node.attribute("fontcolor", "#ffffffff"); // node.attribute("fillcolor", sqlFieldFillColor); // node.endNode(); // // dot.openEdge(fromField, link).attribute("arrowhead", "none").endEdge(); // dot.openEdge(fromField.getTable(), fromField) // .attribute("arrowhead", "none").endEdge(); // } // if (toField != null && !dot.hasNode(toField)) { // IDotNode node = dot.openNode(toField); // node.attribute("label", toField.getName()); // node.attribute("shape", "rectangle"); // node.attribute("style", "filled"); // node.attribute("fontcolor", "#ffffffff"); // node.attribute("fillcolor", sqlFieldFillColor); // node.endNode(); // // dot.openEdge(toField, link).attribute("arrowhead", "none").endEdge(); // dot.openEdge(toField.getTable(), toField).attribute("arrowhead", "none") // .endEdge(); // } // } // } // }; // } return null; } @Override public IDotNodeCallback extendRelationMemberNode(IEntityMetaData metaData, Member member, IEntityMetaData targetMetaData) { synchronized (databases) { final ArrayList<IDirectedLinkMetaData> links = new ArrayList<>(); for (IDatabaseMetaData database : databases) { final ITableMetaData table = database.getTableByType(metaData.getEntityType(), true); if (table == null) { continue; } IDirectedLinkMetaData link = table.getLinkByMemberName(member.getName()); if (link != null) { links.add(link); } } if (links.isEmpty()) { return null; } return new IDotNodeCallback() { @Override public void accept(IDotNode node, StringBuilder sb) { for (IDirectedLinkMetaData link : links) { IFieldMetaData fromField = link.getFromField(); IFieldMetaData toField = link.getToField(); sb.append('\n'); if (fromField != null) { sb.append(fromField.getName()).append("::") .append(fromField.getFieldType().getSimpleName()).append("::") .append(fromField.getOriginalTypeName()); } else { sb.append("n/a"); } sb.append('\n'); if (toField != null) { sb.append(toField.getName()).append("::") .append(toField.getFieldType().getSimpleName()).append("::") .append(toField.getOriginalTypeName()); } else { sb.append("n/a"); } } } }; } } @Override public void newTableMetaData(ITableMetaData newTable) { // intended blank } }
/* Copyright 2015 Samsung Electronics Co., LTD * * 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.gearvrf; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Future; import org.gearvrf.utility.Colors; import org.gearvrf.utility.Threads; import static org.gearvrf.utility.Assert.*; import android.graphics.Color; /** * This is one of the key GVRF classes: it holds shaders with textures. * * You can have invisible {@linkplain GVRSceneObject scene objects:} these have * a location and a set of child objects. This can be useful, to move a set of * scene objects as a unit, preserving their relative geometry. Invisible scene * objects don't need any {@linkplain GVRSceneObject#getRenderData() render * data.} * * <p> * Visible scene objects must have render data * {@linkplain GVRSceneObject#attachRenderData(GVRRenderData) attached.} Each * {@link GVRRenderData} has a {@link GVRMesh GL mesh} that defines its * geometry, and a {@link GVRMaterial} that defines its surface. * * <p> * Each {@link GVRMaterial} contains two main things: * <ul> * <li>The id of a (stock or custom) shader, which is used to draw the mesh. See * {@link GVRShaderType} and {@link GVRContext#getMaterialShaderManager()}. * * <li>Data to pass to the shader. This usually - but not always - means a * {@link GVRTexture} and can include other named values to pass to the shader. * </ul> * * <p> * The simplest way to create a {@link GVRMaterial} is to call the * {@linkplain GVRMaterial#GVRMaterial(GVRContext) constructor that takes only a * GVRContext.} Then you just {@link GVRMaterial#setMainTexture(GVRTexture) * setMainTexture()} and you're ready to draw with the default shader, which is * called 'unlit' because it simply drapes the texture over the mesh, without * any lighting or reflection effects. * * <pre> * // for example * GVRMaterial material = new GVRMaterial(gvrContext); * material.setMainTexture(texture); * </pre> */ public class GVRMaterial extends GVRHybridObject implements GVRShaders<GVRMaterialShaderId> { private int mShaderFeatureSet; private GVRMaterialShaderId shaderId; final private Map<String, GVRTexture> textures = new HashMap<String, GVRTexture>(); /** Pre-built shader ids. */ public abstract static class GVRShaderType { public abstract static class UnlitHorizontalStereo { public static final GVRMaterialShaderId ID = new GVRStockMaterialShaderId( 0); } public abstract static class UnlitVerticalStereo { public static final GVRMaterialShaderId ID = new GVRStockMaterialShaderId( 1); } public abstract static class OES { public static final GVRMaterialShaderId ID = new GVRStockMaterialShaderId( 2); } public abstract static class OESHorizontalStereo { public static final GVRMaterialShaderId ID = new GVRStockMaterialShaderId( 3); } public abstract static class OESVerticalStereo { public static final GVRMaterialShaderId ID = new GVRStockMaterialShaderId( 4); } public abstract static class Cubemap { public static final GVRMaterialShaderId ID = new GVRStockMaterialShaderId( 5); } public abstract static class CubemapReflection { public static final GVRMaterialShaderId ID = new GVRStockMaterialShaderId( 6); } public abstract static class Texture { public static final GVRMaterialShaderId ID = new GVRStockMaterialShaderId( 7); } public abstract static class ExternalRenderer { public static final GVRMaterialShaderId ID = new GVRStockMaterialShaderId( 8); } public abstract static class Assimp { public static final GVRMaterialShaderId ID = new GVRStockMaterialShaderId( 9); /** * Set this feature enum if diffuse texture is present in Assimp * material Diffuse texture maps to main_texture in GearVRf */ public static int AS_DIFFUSE_TEXTURE = 0; /** * Set this feature enum if specular texture is present in Assimp * material */ public static int AS_SPECULAR_TEXTURE = 1; /** * Set this feature enum if skinning info is present in Assimp * material */ public static int AS_SKINNING = 2; public static int setBit(int number, int index) { return (number |= 1 << index); } public static boolean isSet(int number, int index) { return ((number & (1 << index)) != 0); } public static int clearBit(int number, int index) { return (number &= ~(1 << index)); } } public abstract static class UnlitFBO { public static final GVRMaterialShaderId ID = new GVRStockMaterialShaderId( 20); } }; /** * A new holder for a shader's uniforms. * * @param gvrContext * Current {@link GVRContext} * @param shaderId * Id of a {@linkplain GVRShaderType stock} or * {@linkplain GVRMaterialShaderManager custom} shader. */ public GVRMaterial(GVRContext gvrContext, GVRMaterialShaderId shaderId) { super(gvrContext, NativeMaterial.ctor(shaderId.ID)); this.shaderId = shaderId; // if texture shader is used, set lighting coefficients to OpenGL default // values if (shaderId == GVRShaderType.Texture.ID) { setAmbientColor(0.2f, 0.2f, 0.2f, 1.0f); setDiffuseColor(0.8f, 0.8f, 0.8f, 1.0f); setSpecularColor(0.0f, 0.0f, 0.0f, 1.0f); setSpecularExponent(0.0f); } this.mShaderFeatureSet = 0; } /** * A convenience overload: builds a {@link GVRMaterial} that uses the most * common stock shader, the {@linkplain GVRShaderType.Texture 'texture'} shader. * * @param gvrContext * Current {@link GVRContext} */ public GVRMaterial(GVRContext gvrContext) { this(gvrContext, GVRShaderType.Texture.ID); } GVRMaterial(GVRContext gvrContext, long ptr) { super(gvrContext, ptr); } public GVRMaterialShaderId getShaderType() { return shaderId; } /** * Set shader id * * @param shaderId * The new shader id. */ public void setShaderType(GVRMaterialShaderId shaderId) { this.shaderId = shaderId; NativeMaterial.setShaderType(getNative(), shaderId.ID); } public GVRTexture getMainTexture() { return getTexture(MAIN_TEXTURE); } public void setMainTexture(GVRTexture texture) { setTexture(MAIN_TEXTURE, texture); } public void setMainTexture(Future<GVRTexture> texture) { setTexture(MAIN_TEXTURE, texture); } /** * Get the {@code color} uniform. * * By convention, GVRF shaders can use a {@code vec3} uniform named * {@code color}. With the default {@linkplain GVRShaderType.Unlit 'unlit' * shader,} this allows you to add an overlay color on top of the texture. * * @return The current {@code vec3 color} as a three-element array */ public float[] getColor() { return getVec3("color"); } /** * A convenience method that wraps {@link #getColor()} and returns an * Android {@link Color} * * @return An Android {@link Color} */ public int getRgbColor() { return Colors.toColor(getColor()); } /** * Set the {@code color} uniform. * * By convention, GVRF shaders can use a {@code vec3} uniform named * {@code color}. With the default {@linkplain GVRShaderType.Unlit 'unlit' * shader,} this allows you to add an overlay color on top of the texture. * Values are between {@code 0.0f} and {@code 1.0f}, inclusive. * * @param r * Red * @param g * Green * @param b * Blue */ public void setColor(float r, float g, float b) { setVec3("color", r, g, b); } /** * A convenience overload of {@link #setColor(float, float, float)} that * lets you use familiar Android {@link Color} values. * * @param color * Any Android {@link Color}; the alpha byte is ignored. */ public void setColor(int color) { setColor(Colors.byteToGl(Color.red(color)), // Colors.byteToGl(Color.green(color)), // Colors.byteToGl(Color.blue(color))); } /** * Get the {@code materialAmbientColor} uniform. * * By convention, GVRF shaders can use a {@code vec4} uniform named * {@code materialAmbientColor}. With the {@linkplain GVRShaderType.Lit * 'lit' shader,} this allows you to add an overlay color on top of the * texture. * * @return The current {@code vec4 materialAmbientColor} as a four-element * array */ public float[] getAmbientColor() { return getVec4("ambient_color"); } /** * Set the {@code materialAmbientColor} uniform for lighting. * * By convention, GVRF shaders can use a {@code vec4} uniform named * {@code materialAmbientColor}. With the {@linkplain GVRShaderType.Lit * 'lit' shader,} this allows you to add an overlay ambient light color on * top of the texture. Values are between {@code 0.0f} and {@code 1.0f}, * inclusive. * * @param r * Red * @param g * Green * @param b * Blue * @param a * Alpha */ public void setAmbientColor(float r, float g, float b, float a) { setVec4("ambient_color", r, g, b, a); } /** * Get the {@code materialDiffuseColor} uniform. * * By convention, GVRF shaders can use a {@code vec4} uniform named * {@code materialDiffuseColor}. With the {@linkplain GVRShaderType.Lit * 'lit' shader,} this allows you to add an overlay color on top of the * texture. * * @return The current {@code vec4 materialDiffuseColor} as a four-element * array */ public float[] getDiffuseColor() { return getVec4("diffuse_color"); } /** * Set the {@code materialDiffuseColor} uniform for lighting. * * By convention, GVRF shaders can use a {@code vec4} uniform named * {@code materialDiffuseColor}. With the {@linkplain GVRShaderType.Lit * 'lit' shader,} this allows you to add an overlay diffuse light color on * top of the texture. Values are between {@code 0.0f} and {@code 1.0f}, * inclusive. * * @param r * Red * @param g * Green * @param b * Blue * @param a * Alpha */ public void setDiffuseColor(float r, float g, float b, float a) { setVec4("diffuse_color", r, g, b, a); } /** * Get the {@code materialSpecularColor} uniform. * * By convention, GVRF shaders can use a {@code vec4} uniform named * {@code materialSpecularColor}. With the {@linkplain GVRShaderType.Lit * 'lit' shader,} this allows you to add an overlay color on top of the * texture. * * @return The current {@code vec4 materialSpecularColor} as a four-element * array */ public float[] getSpecularColor() { return getVec4("specular_color"); } /** * Set the {@code materialSpecularColor} uniform for lighting. * * By convention, GVRF shaders can use a {@code vec4} uniform named * {@code materialSpecularColor}. With the {@linkplain GVRShaderType.Lit * 'lit' shader,} this allows you to add an overlay specular light color on * top of the texture. Values are between {@code 0.0f} and {@code 1.0f}, * inclusive. * * @param r * Red * @param g * Green * @param b * Blue * @param a * Alpha */ public void setSpecularColor(float r, float g, float b, float a) { setVec4("specular_color", r, g, b, a); } /** * Get the {@code materialSpecularExponent} uniform. * * By convention, GVRF shaders can use a {@code float} uniform named * {@code materialSpecularExponent}. With the {@linkplain GVRShaderType.Lit * 'lit' shader,} this allows you to add an overlay color on top of the * texture. * * @return The current {@code vec4 materialSpecularExponent} as a float * value. */ public float getSpecularExponent() { return getFloat("specular_exponent"); } /** * Set the {@code materialSpecularExponent} uniform for lighting. * * By convention, GVRF shaders can use a {@code float} uniform named * {@code materialSpecularExponent}. With the {@linkplain GVRShaderType.Lit * 'lit' shader,} this allows you to add an overlay specular light color on * top of the texture. Values are between {@code 0.0f} and {@code 128.0f}, * inclusive. * * @param exp * Specular exponent */ public void setSpecularExponent(float exp) { setFloat("specular_exponent", exp); } /** * Get the opacity. * * This method returns the {@code opacity} uniform. * * The {@linkplain #setOpacity(float) setOpacity() documentation} explains * what the {@code opacity} uniform does. * * @return The {@code opacity} uniform used to render this material */ public float getOpacity() { return getFloat("opacity"); } /** * Set the opacity, in a complicated way. * * There are two things you need to know, how opacity is applied, and how * opacity is implemented. * * <p> * First, GVRF does not sort by distance every object it can see, then draw * from back to front. Rather, it sorts every object by * {@linkplain GVRRenderData#getRenderingOrder() render order,} then draws * the {@linkplain GVRScene scene graph} in traversal order. So, if you want * to see a scene object through another scene object, you have to * explicitly {@linkplain GVRRenderData#setRenderingOrder(int) set the * rendering order} so that the translucent object draws after the opaque * object. You can use any integer values you like, but GVRF supplies * {@linkplain GVRRenderData.GVRRenderingOrder four standard values;} the * {@linkplain GVRRenderData#getRenderingOrder() default value} is * {@linkplain GVRRenderData.GVRRenderingOrder#GEOMETRY GEOMETRY.} * * <p> * Second, technically all this method does is set the {@code opacity} * uniform. What this does depends on the actual shader. If you don't * specify a shader (or you specify the * {@linkplain GVRMaterial.GVRShaderType.Unlit#ID unlit} shader) setting * {@code opacity} does exactly what you expect; you only have to worry * about the render order. However, it is totally up to a custom shader * whether or how it will handle opacity. * * @param opacity * Value between {@code 0.0f} and {@code 1.0f}, inclusive. */ public void setOpacity(float opacity) { setFloat("opacity", opacity); } public GVRTexture getTexture(String key) { return textures.get(key); } public void setTexture(String key, GVRTexture texture) { checkStringNotNullOrEmpty("key", key); checkNotNull("texture", texture); textures.put(key, texture); NativeMaterial.setTexture(getNative(), key, texture.getNative()); } public void setTexture(final String key, final Future<GVRTexture> texture) { Threads.spawn(new Runnable() { @Override public void run() { try { setTexture(key, texture.get()); } catch (Exception e) { e.printStackTrace(); } } }); } public float getFloat(String key) { return NativeMaterial.getFloat(getNative(), key); } public void setFloat(String key, float value) { checkStringNotNullOrEmpty("key", key); checkFloatNotNaNOrInfinity("value", value); NativeMaterial.setFloat(getNative(), key, value); } public float[] getVec2(String key) { return NativeMaterial.getVec2(getNative(), key); } public void setVec2(String key, float x, float y) { checkStringNotNullOrEmpty("key", key); NativeMaterial.setVec2(getNative(), key, x, y); } public float[] getVec3(String key) { return NativeMaterial.getVec3(getNative(), key); } public void setVec3(String key, float x, float y, float z) { checkStringNotNullOrEmpty("key", key); NativeMaterial.setVec3(getNative(), key, x, y, z); } public float[] getVec4(String key) { return NativeMaterial.getVec4(getNative(), key); } public void setVec4(String key, float x, float y, float z, float w) { checkStringNotNullOrEmpty("key", key); NativeMaterial.setVec4(getNative(), key, x, y, z, w); } /** * Bind a {@code mat4} to the shader uniform {@code key}. * * @param key * Name of the shader uniform */ public void setMat4(String key, float x1, float y1, float z1, float w1, float x2, float y2, float z2, float w2, float x3, float y3, float z3, float w3, float x4, float y4, float z4, float w4) { checkStringNotNullOrEmpty("key", key); NativeMaterial.setMat4(getNative(), key, x1, y1, z1, w1, x2, y2, z2, w2, x3, y3, z3, w3, x4, y4, z4, w4); } /** * Set the feature set for pre-built shader's. Pre-built shader could be * written to support all the properties of a material system with * preprocessor macro to On/Off features. feature set would determine which * properties are available for current model. Currently only Assimp shader * has support for feature set. * * @param featureSet * Feature set for this material. */ public void setShaderFeatureSet(int featureSet) { this.mShaderFeatureSet = featureSet; NativeMaterial.setShaderFeatureSet(getNative(), featureSet); } /** * Get the feature set associated with this material. * * @return An integer representing the feature set. * */ public int getShaderFeatureSet() { return mShaderFeatureSet; } } class NativeMaterial { static native long ctor(int shaderType); static native void setShaderType(long material, long shaderType); static native void setTexture(long material, String key, long texture); static native float getFloat(long material, String key); static native void setFloat(long material, String key, float value); static native float[] getVec2(long material, String key); static native void setVec2(long material, String key, float x, float y); static native float[] getVec3(long material, String key); static native void setVec3(long material, String key, float x, float y, float z); static native float[] getVec4(long material, String key); static native void setVec4(long material, String key, float x, float y, float z, float w); static native void setMat4(long material, String key, float x1, float y1, float z1, float w1, float x2, float y2, float z2, float w2, float x3, float y3, float z3, float w3, float x4, float y4, float z4, float w4); static native void setShaderFeatureSet(long material, int featureSet); }
/* * 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.hive.ql.security; import static org.apache.hadoop.fs.permission.AclEntryScope.ACCESS; import static org.apache.hadoop.fs.permission.AclEntryType.GROUP; import static org.apache.hadoop.fs.permission.AclEntryType.OTHER; import static org.apache.hadoop.fs.permission.AclEntryType.USER; import java.lang.reflect.Method; import java.net.URI; import java.security.PrivilegedExceptionAction; import java.util.Arrays; import java.util.List; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.AclEntry; import org.apache.hadoop.fs.permission.AclEntryScope; import org.apache.hadoop.fs.permission.AclEntryType; import org.apache.hadoop.fs.permission.FsAction; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.shims.ShimLoader; import org.apache.hadoop.hive.shims.Utils; import org.apache.hadoop.hive.shims.HadoopShims.MiniDFSShim; import org.apache.hadoop.security.UserGroupInformation; import com.google.common.collect.Lists; public class TestStorageBasedMetastoreAuthorizationProviderWithACL extends TestStorageBasedMetastoreAuthorizationProvider { protected static MiniDFSShim dfs = null; protected static Path warehouseDir = null; protected UserGroupInformation userUgi = null; protected String testUserName = "test_user"; @Override protected boolean isTestEnabled() { // This test with HDFS ACLs will only work if FileSystem.access() is available in the // version of hadoop-2 used to build Hive. return doesAccessAPIExist(); } private static boolean doesAccessAPIExist() { boolean foundMethod = false; try { Method method = FileSystem.class.getMethod("access", Path.class, FsAction.class); foundMethod = true; } catch (NoSuchMethodException err) { } return foundMethod; } @Override protected HiveConf createHiveConf() throws Exception { userUgi = UserGroupInformation.createUserForTesting(testUserName, new String[] {}); // Hadoop FS ACLs do not work with LocalFileSystem, so set up MiniDFS. HiveConf conf = super.createHiveConf(); String currentUserName = Utils.getUGI().getShortUserName(); conf.set("dfs.namenode.acls.enabled", "true"); conf.set("hadoop.proxyuser." + currentUserName + ".groups", "*"); conf.set("hadoop.proxyuser." + currentUserName + ".hosts", "*"); dfs = ShimLoader.getHadoopShims().getMiniDfs(conf, 4, true, null); FileSystem fs = dfs.getFileSystem(); warehouseDir = new Path(new Path(fs.getUri()), "/warehouse"); fs.mkdirs(warehouseDir); conf.setVar(HiveConf.ConfVars.METASTOREWAREHOUSE, warehouseDir.toString()); conf.setBoolVar(HiveConf.ConfVars.HIVE_WAREHOUSE_SUBDIR_INHERIT_PERMS, true); // Set up scratch directory Path scratchDir = new Path(new Path(fs.getUri()), "/scratchdir"); conf.setVar(HiveConf.ConfVars.SCRATCHDIR, scratchDir.toString()); return conf; } protected String setupUser() { // Using MiniDFS, the permissions don't work properly because // the current user gets treated as a superuser. // For this test, specify a different (non-super) user. InjectableDummyAuthenticator.injectUserName(userUgi.getShortUserName()); InjectableDummyAuthenticator.injectGroupNames(Arrays.asList(userUgi.getGroupNames())); InjectableDummyAuthenticator.injectMode(true); return userUgi.getShortUserName(); } @Override protected void tearDown() throws Exception { super.tearDown(); if (dfs != null) { dfs.shutdown(); dfs = null; } } protected void allowWriteAccessViaAcl(String userName, String location) throws Exception { // Set the FS perms to read-only access, and create ACL entries allowing write access. List<AclEntry> aclSpec = Lists.newArrayList( aclEntry(ACCESS, USER, FsAction.READ_EXECUTE), aclEntry(ACCESS, GROUP, FsAction.READ_EXECUTE), aclEntry(ACCESS, OTHER, FsAction.READ_EXECUTE), aclEntry(ACCESS, USER, userName, FsAction.ALL) ); FileSystem fs = FileSystem.get(new URI(location), clientHiveConf); fs.setAcl(new Path(location), aclSpec); } protected void disallowWriteAccessViaAcl(String userName, String location) throws Exception { FileSystem fs = FileSystem.get(new URI(location), clientHiveConf); fs.removeAcl(new Path(location)); setPermissions(location,"-r-xr-xr-x"); } /** * Create a new AclEntry with scope, type and permission (no name). * Borrowed from TestExtendedAcls * * @param scope * AclEntryScope scope of the ACL entry * @param type * AclEntryType ACL entry type * @param permission * FsAction set of permissions in the ACL entry * @return AclEntry new AclEntry */ private AclEntry aclEntry(AclEntryScope scope, AclEntryType type, FsAction permission) { return new AclEntry.Builder().setScope(scope).setType(type) .setPermission(permission).build(); } /** * Create a new AclEntry with scope, type, name and permission. * Borrowed from TestExtendedAcls * * @param scope * AclEntryScope scope of the ACL entry * @param type * AclEntryType ACL entry type * @param name * String optional ACL entry name * @param permission * FsAction set of permissions in the ACL entry * @return AclEntry new AclEntry */ private AclEntry aclEntry(AclEntryScope scope, AclEntryType type, String name, FsAction permission) { return new AclEntry.Builder().setScope(scope).setType(type).setName(name) .setPermission(permission).build(); } protected void allowCreateDatabase(String userName) throws Exception { allowWriteAccessViaAcl(userName, warehouseDir.toString()); } @Override protected void allowCreateInDb(String dbName, String userName, String location) throws Exception { allowWriteAccessViaAcl(userName, location); } @Override protected void disallowCreateInDb(String dbName, String userName, String location) throws Exception { disallowWriteAccessViaAcl(userName, location); } @Override protected void allowCreateInTbl(String tableName, String userName, String location) throws Exception{ allowWriteAccessViaAcl(userName, location); } @Override protected void disallowCreateInTbl(String tableName, String userName, String location) throws Exception { disallowWriteAccessViaAcl(userName, location); } @Override protected void allowDropOnTable(String tblName, String userName, String location) throws Exception { allowWriteAccessViaAcl(userName, location); } @Override protected void disallowDropOnTable(String tblName, String userName, String location) throws Exception { disallowWriteAccessViaAcl(userName, location); } @Override protected void allowDropOnDb(String dbName, String userName, String location) throws Exception { allowWriteAccessViaAcl(userName, location); } }
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.wso2.siddhi.extension.eventtable.rdbms; import junit.framework.Assert; import org.apache.log4j.Logger; import org.junit.Test; import org.wso2.siddhi.core.ExecutionPlanRuntime; import org.wso2.siddhi.core.SiddhiManager; import org.wso2.siddhi.core.stream.input.InputHandler; import javax.sql.DataSource; import java.sql.SQLException; public class DeleteFromRDBMSTestCase { private static final Logger log = Logger.getLogger(DeleteFromRDBMSTestCase.class); private DataSource dataSource = new BasicDataSource(); @Test public void deleteFromRDBMSTableTest1() throws InterruptedException { log.info("deleteFromTableTest1"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.getSiddhiContext().addSiddhiDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource); try { if (dataSource.getConnection() != null) { DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource,RDBMSTestConstants.TABLE_NAME); String streams = "" + "define stream StockStream (symbol string, price float, volume long); " + "define stream DeleteStockStream (symbol string, price float, volume long); " + "@from(eventtable = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' , table.name = '" + RDBMSTestConstants.TABLE_NAME + "') " + "define table StockTable (symbol string, price float, volume long); "; String query = "" + "@info(name = 'query1') " + "from StockStream " + "insert into StockTable ;" + "" + "@info(name = 'query2') " + "from DeleteStockStream " + "delete StockTable " + " on StockTable.symbol == symbol ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query); InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream"); InputHandler deleteStockStream = executionPlanRuntime.getInputHandler("DeleteStockStream"); executionPlanRuntime.start(); stockStream.send(new Object[]{"WSO2", 55.6f, 100l}); stockStream.send(new Object[]{"IBM", 75.6f, 100l}); stockStream.send(new Object[]{"WSO2", 57.6f, 100l}); deleteStockStream.send(new Object[]{"IBM", 57.6f, 100l}); Thread.sleep(1000); long totalRowsInTable = DBConnectionHelper.getDBConnectionHelperInstance().getRowsInTable(dataSource); Assert.assertEquals("Deletion failed", 2, totalRowsInTable); executionPlanRuntime.shutdown(); } } catch (SQLException e) { log.info("Test case ignored due to DB connection unavailability"); } } @Test public void deleteFromRDBMSTableTest2() throws InterruptedException { log.info("deleteFromTableTest2"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.getSiddhiContext().addSiddhiDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource); try { if (dataSource.getConnection() != null) { DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource,RDBMSTestConstants.TABLE_NAME); String streams = "" + "define stream StockStream (symbol string, price float, volume long); " + "define stream DeleteStockStream (symbol string, price float, volume long); " + "@from(eventtable = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' , table.name = '" + RDBMSTestConstants.TABLE_NAME + "') " + "define table StockTable (symbol string, price float, volume long); "; String query = "" + "@info(name = 'query1') " + "from StockStream " + "insert into StockTable ;" + "" + "@info(name = 'query2') " + "from DeleteStockStream " + "delete StockTable " + " on symbol == StockTable.symbol ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query); InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream"); InputHandler deleteStockStream = executionPlanRuntime.getInputHandler("DeleteStockStream"); executionPlanRuntime.start(); stockStream.send(new Object[]{"WSO2", 55.6f, 100l}); stockStream.send(new Object[]{"IBM", 75.6f, 100l}); stockStream.send(new Object[]{"WSO2", 57.6f, 100l}); deleteStockStream.send(new Object[]{"IBM", 57.6f, 100l}); Thread.sleep(1000); long totalRowsInTable = DBConnectionHelper.getDBConnectionHelperInstance().getRowsInTable(dataSource); Assert.assertEquals("Deletion failed", 2, totalRowsInTable); executionPlanRuntime.shutdown(); } } catch (SQLException e) { log.info("Test case ignored due to DB connection unavailability"); } } @Test public void deleteFromRDBMSTableTest3() throws InterruptedException { log.info("deleteFromTableTest3"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.getSiddhiContext().addSiddhiDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource); try { if (dataSource.getConnection() != null) { DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource,RDBMSTestConstants.TABLE_NAME); String streams = "" + "define stream StockStream (symbol string, price float, volume long); " + "define stream DeleteStockStream (symbol string, price float, volume long); " + "@from(eventtable = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' , table.name = '" + RDBMSTestConstants.TABLE_NAME + "') " + "define table StockTable (symbol string, price float, volume long); "; String query = "" + "@info(name = 'query1') " + "from StockStream " + "insert into StockTable ;" + "" + "@info(name = 'query2') " + "from DeleteStockStream " + "delete StockTable " + " on StockTable.symbol == 'IBM' ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query); InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream"); InputHandler deleteStockStream = executionPlanRuntime.getInputHandler("DeleteStockStream"); executionPlanRuntime.start(); stockStream.send(new Object[]{"WSO2", 55.6f, 100l}); stockStream.send(new Object[]{"IBM", 75.6f, 100l}); stockStream.send(new Object[]{"WSO2", 57.6f, 100l}); deleteStockStream.send(new Object[]{"IBM", 57.6f, 100l}); Thread.sleep(1000); long totalRowsInTable = DBConnectionHelper.getDBConnectionHelperInstance().getRowsInTable(dataSource); Assert.assertEquals("Deletion failed", 2, totalRowsInTable); executionPlanRuntime.shutdown(); } } catch (SQLException e) { log.info("Test case ignored due to DB connection unavailability"); } } @Test public void deleteFromRDBMSTableTest4() throws InterruptedException { log.info("deleteFromTableTest4"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.getSiddhiContext().addSiddhiDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource); try { if (dataSource.getConnection() != null) { DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource,RDBMSTestConstants.TABLE_NAME); String streams = "" + "define stream StockStream (symbol string, price float, volume long); " + "define stream DeleteStockStream (symbol string, price float, volume long); " + "@from(eventtable = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' , table.name = '" + RDBMSTestConstants.TABLE_NAME + "') " + "define table StockTable (symbol string, price float, volume long); "; String query = "" + "@info(name = 'query1') " + "from StockStream " + "insert into StockTable ;" + "" + "@info(name = 'query2') " + "from DeleteStockStream " + "delete StockTable " + " on 'IBM' == StockTable.symbol ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query); InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream"); InputHandler deleteStockStream = executionPlanRuntime.getInputHandler("DeleteStockStream"); executionPlanRuntime.start(); stockStream.send(new Object[]{"WSO2", 55.6f, 100l}); stockStream.send(new Object[]{"IBM", 75.6f, 100l}); stockStream.send(new Object[]{"WSO2", 57.6f, 100l}); deleteStockStream.send(new Object[]{"IBM", 57.6f, 100l}); Thread.sleep(1000); long totalRowsInTable = DBConnectionHelper.getDBConnectionHelperInstance().getRowsInTable(dataSource); Assert.assertEquals("Deletion failed", 2, totalRowsInTable); executionPlanRuntime.shutdown(); } } catch (SQLException e) { log.info("Test case ignored due to DB connection unavailability"); } } @Test public void deleteFromRDBMSTableTest5() throws InterruptedException { log.info("deleteFromTableTest5"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.getSiddhiContext().addSiddhiDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource); try { if (dataSource.getConnection() != null) { DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource,RDBMSTestConstants.TABLE_NAME); String streams = "" + "define stream StockStream (symbol string, price float, volume long); " + "define stream DeleteStockStream (symbol string, price float, volume long); " + "@from(eventtable = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' , table.name = '" + RDBMSTestConstants.TABLE_NAME + "') " + "define table StockTable (symbol string, price float, volume long); "; String query = "" + "@info(name = 'query1') " + "from StockStream " + "insert into StockTable ;" + "" + "@info(name = 'query2') " + "from DeleteStockStream " + "delete StockTable " + " on 'IBM' == symbol ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query); InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream"); InputHandler deleteStockStream = executionPlanRuntime.getInputHandler("DeleteStockStream"); executionPlanRuntime.start(); stockStream.send(new Object[]{"WSO2", 55.6f, 100l}); stockStream.send(new Object[]{"IBM", 75.6f, 100l}); stockStream.send(new Object[]{"WSO2", 57.6f, 100l}); deleteStockStream.send(new Object[]{"IBM", 57.6f, 100l}); Thread.sleep(1000); long totalRowsInTable = DBConnectionHelper.getDBConnectionHelperInstance().getRowsInTable(dataSource); Assert.assertEquals("Deletion failed", 2, totalRowsInTable); executionPlanRuntime.shutdown(); } } catch (SQLException e) { log.info("Test case ignored due to DB connection unavailability"); } } @Test public void deleteFromRDBMSTableTest6() throws InterruptedException { log.info("deleteFromTableTest6"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.getSiddhiContext().addSiddhiDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource); try { if (dataSource.getConnection() != null) { DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource,RDBMSTestConstants.TABLE_NAME); String streams = "" + "define stream StockStream (symbol string, price float, volume long); " + "define stream DeleteStockStream (symbol string, price float, volume long); " + "@from(eventtable = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' , table.name = '" + RDBMSTestConstants.TABLE_NAME + "') " + "define table StockTable (symbol string, price float, volume long); "; String query = "" + "@info(name = 'query1') " + "from StockStream " + "insert into StockTable ;" + "" + "@info(name = 'query2') " + "from DeleteStockStream " + "delete StockTable " + " on symbol == 'IBM' ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query); InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream"); InputHandler deleteStockStream = executionPlanRuntime.getInputHandler("DeleteStockStream"); executionPlanRuntime.start(); stockStream.send(new Object[]{"WSO2", 55.6f, 100l}); stockStream.send(new Object[]{"IBM", 75.6f, 100l}); stockStream.send(new Object[]{"WSO2", 57.6f, 100l}); deleteStockStream.send(new Object[]{"IBM", 57.6f, 100l}); Thread.sleep(1000); long totalRowsInTable = DBConnectionHelper.getDBConnectionHelperInstance().getRowsInTable(dataSource); Assert.assertEquals("Deletion failed", 2, totalRowsInTable); executionPlanRuntime.shutdown(); } } catch (SQLException e) { log.info("Test case ignored due to DB connection unavailability"); } } @Test public void deleteFromTableTest7() throws InterruptedException { log.info("deleteFromTableTest7"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.getSiddhiContext().addSiddhiDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource); try { if (dataSource.getConnection() != null) { DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource,RDBMSTestConstants.TABLE_NAME); String streams = "" + "define stream StockStream (symbol string, price float, volume long); " + "define stream DeleteStockStream (symbol string, price float, volume long); " + "@from(eventtable = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' , table.name = '" + RDBMSTestConstants.TABLE_NAME + "') " + "define table StockTable (symbol string, price float, volume long); "; String query = "" + "@info(name = 'query1') " + "from StockStream " + "insert into StockTable ;" + "" + "@info(name = 'query2') " + "from DeleteStockStream " + "delete StockTable " + " on StockTable.symbol==symbol and StockTable.price > price and StockTable.volume == volume ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query); InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream"); InputHandler deleteStockStream = executionPlanRuntime.getInputHandler("DeleteStockStream"); executionPlanRuntime.start(); stockStream.send(new Object[]{"WSO2", 55.6f, 100l}); stockStream.send(new Object[]{"IBM", 75.6f, 100l}); stockStream.send(new Object[]{"IBM", 57.6f, 100l}); deleteStockStream.send(new Object[]{"IBM", 57.6f, 100l}); Thread.sleep(1000); long totalRowsInTable = DBConnectionHelper.getDBConnectionHelperInstance().getRowsInTable(dataSource); Assert.assertEquals("Deletion failed", 2, totalRowsInTable); executionPlanRuntime.shutdown(); } } catch (SQLException e) { log.info("Test case ignored due to DB connection unavailability"); } } @Test public void deleteFromTableTest8() throws InterruptedException { log.info("deleteFromTableTest8"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.getSiddhiContext().addSiddhiDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource); try { if (dataSource.getConnection() != null) { DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource,RDBMSTestConstants.TABLE_NAME); String streams = "" + "define stream StockStream (symbol string, price float, volume long); " + "define stream DeleteStockStream (symbol string, price float, volume long); " + "@from(eventtable = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' , table.name = '" + RDBMSTestConstants.TABLE_NAME + "') " + "define table StockTable (symbol string, price float, volume long); "; String query = "" + "@info(name = 'query1') " + "from StockStream " + "insert into StockTable ;" + "" + "@info(name = 'query2') " + "from DeleteStockStream " + "delete StockTable " + " on StockTable.symbol=='IBM' and StockTable.price > 50 and StockTable.volume == volume ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query); InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream"); InputHandler deleteStockStream = executionPlanRuntime.getInputHandler("DeleteStockStream"); executionPlanRuntime.start(); stockStream.send(new Object[]{"WSO2", 55.6f, 100l}); stockStream.send(new Object[]{"IBM", 75.6f, 100l}); stockStream.send(new Object[]{"IBM", 57.6f, 100l}); deleteStockStream.send(new Object[]{"IBM", 57.6f, 100l}); Thread.sleep(1000); long totalRowsInTable = DBConnectionHelper.getDBConnectionHelperInstance().getRowsInTable(dataSource); Assert.assertEquals("Deletion failed", 1, totalRowsInTable); executionPlanRuntime.shutdown(); } } catch (SQLException e) { log.info("Test case ignored due to DB connection unavailability"); } } @Test public void deleteFromRDBMSTableTest9() throws InterruptedException { log.info("deleteFromTableTest9"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.getSiddhiContext().addSiddhiDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource); try { if (dataSource.getConnection() != null) { DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource,RDBMSTestConstants.TABLE_NAME); String streams = "" + "define stream StockStream (symbol string, price float, volume long); " + "define stream DeleteStockStream (symbol string, price float, volume long); " + "@from(eventtable = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' , table.name = '" + RDBMSTestConstants.TABLE_NAME + "', cache='lfu', cache.size='1000') " + "define table StockTable (symbol string, price float, volume long); "; String query = "" + "@info(name = 'query1') " + "from StockStream " + "insert into StockTable ;" + "" + "@info(name = 'query2') " + "from DeleteStockStream " + "delete StockTable " + " on StockTable.symbol == symbol ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query); InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream"); InputHandler deleteStockStream = executionPlanRuntime.getInputHandler("DeleteStockStream"); executionPlanRuntime.start(); stockStream.send(new Object[]{"WSO2", 55.6f, 100l}); stockStream.send(new Object[]{"IBM", 75.6f, 100l}); stockStream.send(new Object[]{"WSO2", 57.6f, 100l}); deleteStockStream.send(new Object[]{"IBM", 57.6f, 100l}); Thread.sleep(1000); long totalRowsInTable = DBConnectionHelper.getDBConnectionHelperInstance().getRowsInTable(dataSource); Assert.assertEquals("Deletion failed", 2, totalRowsInTable); executionPlanRuntime.shutdown(); } } catch (SQLException e) { log.info("Test case ignored due to DB connection unavailability"); } } @Test public void deleteFromRDBMSTableTest10() throws InterruptedException { log.info("deleteFromTableTest10"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.getSiddhiContext().addSiddhiDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource); try { if (dataSource.getConnection() != null) { DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource,RDBMSTestConstants.TABLE_NAME); String streams = "" + "define stream StockStream (symbol string, price float, volume long); " + "define stream DeleteStockStream (symbol string, price float, volume long); " + "@from(eventtable = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' , table.name = '" + RDBMSTestConstants.TABLE_NAME + "', bloom.filters = 'enable') " + "define table StockTable (symbol string, price float, volume long); "; String query = "" + "@info(name = 'query1') " + "from StockStream " + "insert into StockTable ;" + "" + "@info(name = 'query2') " + "from DeleteStockStream " + "delete StockTable " + " on StockTable.symbol == symbol ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query); InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream"); InputHandler deleteStockStream = executionPlanRuntime.getInputHandler("DeleteStockStream"); executionPlanRuntime.start(); stockStream.send(new Object[]{"WSO2", 55.6f, 100l}); stockStream.send(new Object[]{"IBM", 75.6f, 100l}); stockStream.send(new Object[]{"WSO2", 57.6f, 100l}); deleteStockStream.send(new Object[]{"IBM", 57.6f, 100l}); Thread.sleep(1000); long totalRowsInTable = DBConnectionHelper.getDBConnectionHelperInstance().getRowsInTable(dataSource); Assert.assertEquals("Deletion failed", 2, totalRowsInTable); executionPlanRuntime.shutdown(); } } catch (SQLException e) { log.info("Test case ignored due to DB connection unavailability"); } } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.raptor.legacy.systemtables; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import io.airlift.slice.Slice; import io.trino.spi.predicate.Domain; import io.trino.spi.predicate.Range; import io.trino.spi.predicate.TupleDomain; import io.trino.spi.type.Type; import io.trino.spi.type.VarcharType; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.collect.Iterables.getOnlyElement; import static io.trino.plugin.raptor.legacy.util.DatabaseUtil.enableStreamingResults; import static io.trino.plugin.raptor.legacy.util.UuidUtil.uuidToBytes; import static io.trino.spi.type.BigintType.BIGINT; import static io.trino.spi.type.BooleanType.BOOLEAN; import static io.trino.spi.type.DoubleType.DOUBLE; import static io.trino.spi.type.VarbinaryType.VARBINARY; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; import static java.sql.ResultSet.CONCUR_READ_ONLY; import static java.sql.ResultSet.TYPE_FORWARD_ONLY; import static java.util.Collections.nCopies; import static java.util.UUID.fromString; public final class PreparedStatementBuilder { private PreparedStatementBuilder() {} public static PreparedStatement create( Connection connection, String sql, List<String> columnNames, List<Type> types, Set<Integer> uuidColumnIndexes, TupleDomain<Integer> tupleDomain) throws SQLException { checkArgument(!isNullOrEmpty(sql), "sql is null or empty"); List<ValueBuffer> bindValues = new ArrayList<>(256); sql += getWhereClause(tupleDomain, columnNames, types, uuidColumnIndexes, bindValues); PreparedStatement statement = connection.prepareStatement(sql, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY); enableStreamingResults(statement); // bind values to statement int bindIndex = 1; for (ValueBuffer value : bindValues) { bindField(value, statement, bindIndex, uuidColumnIndexes.contains(value.getColumnIndex())); bindIndex++; } return statement; } @SuppressWarnings("OptionalGetWithoutIsPresent") private static String getWhereClause( TupleDomain<Integer> tupleDomain, List<String> columnNames, List<Type> types, Set<Integer> uuidColumnIndexes, List<ValueBuffer> bindValues) { if (tupleDomain.isNone()) { return ""; } ImmutableList.Builder<String> conjunctsBuilder = ImmutableList.builder(); Map<Integer, Domain> domainMap = tupleDomain.getDomains().get(); for (Map.Entry<Integer, Domain> entry : domainMap.entrySet()) { int index = entry.getKey(); String columnName = columnNames.get(index); Type type = types.get(index); conjunctsBuilder.add(toPredicate(index, columnName, type, entry.getValue(), uuidColumnIndexes, bindValues)); } List<String> conjuncts = conjunctsBuilder.build(); if (conjuncts.isEmpty()) { return ""; } StringBuilder where = new StringBuilder("WHERE "); return Joiner.on(" AND\n").appendTo(where, conjuncts).toString(); } private static String toPredicate( int columnIndex, String columnName, Type type, Domain domain, Set<Integer> uuidColumnIndexes, List<ValueBuffer> bindValues) { if (domain.getValues().isAll()) { return domain.isNullAllowed() ? "TRUE" : columnName + " IS NOT NULL"; } if (domain.getValues().isNone()) { return domain.isNullAllowed() ? columnName + " IS NULL" : "FALSE"; } return domain.getValues().getValuesProcessor().transform( ranges -> { // Add disjuncts for ranges List<String> disjuncts = new ArrayList<>(); List<Object> singleValues = new ArrayList<>(); // Add disjuncts for ranges for (Range range : ranges.getOrderedRanges()) { checkState(!range.isAll()); // Already checked if (range.isSingleValue()) { singleValues.add(range.getSingleValue()); } else { List<String> rangeConjuncts = new ArrayList<>(); if (!range.isLowUnbounded()) { Object bindValue = getBindValue(columnIndex, uuidColumnIndexes, range.getLowBoundedValue()); rangeConjuncts.add(toBindPredicate(columnName, range.isLowInclusive() ? ">=" : ">")); bindValues.add(ValueBuffer.create(columnIndex, type, bindValue)); } if (!range.isHighUnbounded()) { Object bindValue = getBindValue(columnIndex, uuidColumnIndexes, range.getHighBoundedValue()); rangeConjuncts.add(toBindPredicate(columnName, range.isHighInclusive() ? "<=" : "<")); bindValues.add(ValueBuffer.create(columnIndex, type, bindValue)); } // If rangeConjuncts is null, then the range was ALL, which should already have been checked for checkState(!rangeConjuncts.isEmpty()); disjuncts.add("(" + Joiner.on(" AND ").join(rangeConjuncts) + ")"); } } // Add back all of the possible single values either as an equality or an IN predicate if (singleValues.size() == 1) { disjuncts.add(toBindPredicate(columnName, "=")); bindValues.add(ValueBuffer.create(columnIndex, type, getBindValue(columnIndex, uuidColumnIndexes, getOnlyElement(singleValues)))); } else if (singleValues.size() > 1) { disjuncts.add(columnName + " IN (" + Joiner.on(",").join(nCopies(singleValues.size(), "?")) + ")"); for (Object singleValue : singleValues) { bindValues.add(ValueBuffer.create(columnIndex, type, getBindValue(columnIndex, uuidColumnIndexes, singleValue))); } } // Add nullability disjuncts checkState(!disjuncts.isEmpty()); if (domain.isNullAllowed()) { disjuncts.add(columnName + " IS NULL"); } return "(" + Joiner.on(" OR ").join(disjuncts) + ")"; }, discreteValues -> { String values = Joiner.on(",").join(nCopies(discreteValues.getValues().size(), "?")); String predicate = columnName + (discreteValues.isInclusive() ? "" : " NOT") + " IN (" + values + ")"; for (Object value : discreteValues.getValues()) { bindValues.add(ValueBuffer.create(columnIndex, type, getBindValue(columnIndex, uuidColumnIndexes, value))); } if (domain.isNullAllowed()) { predicate = "(" + predicate + " OR " + columnName + " IS NULL)"; } return predicate; }, allOrNone -> { throw new IllegalStateException("Case should not be reachable"); }); } private static Object getBindValue(int columnIndex, Set<Integer> uuidColumnIndexes, Object value) { if (uuidColumnIndexes.contains(columnIndex)) { return uuidToBytes(fromString(((Slice) value).toStringUtf8())); } return value; } private static String toBindPredicate(String columnName, String operator) { return format("%s %s ?", columnName, operator); } private static void bindField(ValueBuffer valueBuffer, PreparedStatement preparedStatement, int parameterIndex, boolean isUuid) throws SQLException { Type type = valueBuffer.getType(); if (valueBuffer.isNull()) { preparedStatement.setNull(parameterIndex, typeToSqlType(type)); } else if (type.getJavaType() == long.class) { preparedStatement.setLong(parameterIndex, valueBuffer.getLong()); } else if (type.getJavaType() == double.class) { preparedStatement.setDouble(parameterIndex, valueBuffer.getDouble()); } else if (type.getJavaType() == boolean.class) { preparedStatement.setBoolean(parameterIndex, valueBuffer.getBoolean()); } else if (type.getJavaType() == Slice.class && isUuid) { preparedStatement.setBytes(parameterIndex, valueBuffer.getSlice().getBytes()); } else if (type.getJavaType() == Slice.class) { preparedStatement.setString(parameterIndex, new String(valueBuffer.getSlice().getBytes(), UTF_8)); } else { throw new IllegalArgumentException("Unknown Java type: " + type.getJavaType()); } } private static int typeToSqlType(Type type) { if (type.equals(BIGINT)) { return Types.BIGINT; } if (type.equals(DOUBLE)) { return Types.DOUBLE; } if (type.equals(BOOLEAN)) { return Types.BOOLEAN; } if (type instanceof VarcharType) { return Types.VARCHAR; } if (type.equals(VARBINARY)) { return Types.VARBINARY; } throw new IllegalArgumentException("Unknown type: " + type); } }
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.fileEditor.impl; import com.intellij.AppTopics; import com.intellij.CommonBundle; import com.intellij.codeStyle.CodeStyleFacade; import com.intellij.diff.DiffContentFactory; import com.intellij.diff.DiffManager; import com.intellij.diff.DiffRequestPanel; import com.intellij.diff.contents.DocumentContent; import com.intellij.diff.requests.DiffRequest; import com.intellij.diff.requests.SimpleDiffRequest; import com.intellij.diff.util.DiffUserDataKeys; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.UndoConfirmationPolicy; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.event.DocumentAdapter; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.impl.EditorFactoryImpl; import com.intellij.openapi.editor.impl.TrailingSpacesStripper; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.*; import com.intellij.openapi.fileEditor.impl.text.TextEditorImpl; import com.intellij.openapi.fileTypes.BinaryFileTypeDecompilers; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.UnknownFileType; import com.intellij.openapi.project.*; import com.intellij.openapi.project.ex.ProjectEx; import com.intellij.openapi.ui.DialogBuilder; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.newvfs.NewVirtualFileSystem; import com.intellij.pom.core.impl.PomModelImpl; import com.intellij.psi.ExternalChangeAction; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.SingleRootFileViewProvider; import com.intellij.testFramework.LightVirtualFile; import com.intellij.ui.UIBundle; import com.intellij.ui.components.JBScrollPane; import com.intellij.util.Function; import com.intellij.util.PairProcessor; import com.intellij.util.ThrowableRunnable; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.*; import java.util.List; public class FileDocumentManagerImpl extends FileDocumentManager implements VirtualFileListener, ProjectManagerListener, SafeWriteRequestor { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl"); public static final Key<Document> HARD_REF_TO_DOCUMENT_KEY = Key.create("HARD_REF_TO_DOCUMENT_KEY"); private static final Key<String> LINE_SEPARATOR_KEY = Key.create("LINE_SEPARATOR_KEY"); private static final Key<VirtualFile> FILE_KEY = Key.create("FILE_KEY"); private static final Key<Boolean> MUST_RECOMPUTE_FILE_TYPE = Key.create("Must recompute file type"); private final Set<Document> myUnsavedDocuments = ContainerUtil.newConcurrentSet(); private final DocumentCacheStrategy myDocumentCacheStrategy; private final MessageBus myBus; private static final Object lock = new Object(); private final FileDocumentManagerListener myMultiCaster; private final TrailingSpacesStripper myTrailingSpacesStripper = new TrailingSpacesStripper(); private boolean myOnClose; public FileDocumentManagerImpl(@NotNull VirtualFileManager virtualFileManager, @NotNull ProjectManager projectManager) { myDocumentCacheStrategy = createDocumentCacheStrategy(); virtualFileManager.addVirtualFileListener(this); projectManager.addProjectManagerListener(this); myBus = ApplicationManager.getApplication().getMessageBus(); InvocationHandler handler = new InvocationHandler() { @Nullable @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { multiCast(method, args); return null; } }; final ClassLoader loader = FileDocumentManagerListener.class.getClassLoader(); myMultiCaster = (FileDocumentManagerListener)Proxy.newProxyInstance(loader, new Class[]{FileDocumentManagerListener.class}, handler); } private static void unwrapAndRethrow(Exception e) { Throwable unwrapped = e; if (e instanceof InvocationTargetException) { unwrapped = e.getCause() == null ? e : e.getCause(); } if (unwrapped instanceof Error) throw (Error)unwrapped; if (unwrapped instanceof RuntimeException) throw (RuntimeException)unwrapped; LOG.error(unwrapped); } @SuppressWarnings("OverlyBroadCatchBlock") private void multiCast(@NotNull Method method, Object[] args) { try { method.invoke(myBus.syncPublisher(AppTopics.FILE_DOCUMENT_SYNC), args); } catch (ClassCastException e) { LOG.error("Arguments: "+ Arrays.toString(args), e); } catch (Exception e) { unwrapAndRethrow(e); } // Allows pre-save document modification for (FileDocumentManagerListener listener : getListeners()) { try { method.invoke(listener, args); } catch (Exception e) { unwrapAndRethrow(e); } } // stripping trailing spaces try { method.invoke(myTrailingSpacesStripper, args); } catch (Exception e) { unwrapAndRethrow(e); } } @Override @Nullable public Document getDocument(@NotNull final VirtualFile file) { ApplicationManager.getApplication().assertReadAccessAllowed(); DocumentEx document = (DocumentEx)getCachedDocument(file); if (document == null) { if (!file.isValid() || file.isDirectory() || SingleRootFileViewProvider.isTooLargeForContentLoading(file) || isBinaryWithoutDecompiler(file)) { return null; } final CharSequence text = LoadTextUtil.loadText(file); synchronized (lock) { document = (DocumentEx)getCachedDocument(file); if (document != null) return document; // Double checking document = (DocumentEx)createDocument(text, file); document.setModificationStamp(file.getModificationStamp()); final FileType fileType = file.getFileType(); document.setReadOnly(!file.isWritable() || fileType.isBinary()); if (file instanceof LightVirtualFile) { registerDocument(document, file); } else { myDocumentCacheStrategy.putDocument(file, document); document.putUserData(FILE_KEY, file); } if (!(file instanceof LightVirtualFile || file.getFileSystem() instanceof NonPhysicalFileSystem)) { document.addDocumentListener( new DocumentAdapter() { @Override public void documentChanged(DocumentEvent e) { final Document document = e.getDocument(); myUnsavedDocuments.add(document); final Runnable currentCommand = CommandProcessor.getInstance().getCurrentCommand(); Project project = currentCommand == null ? null : CommandProcessor.getInstance().getCurrentCommandProject(); String lineSeparator = CodeStyleFacade.getInstance(project).getLineSeparator(); document.putUserData(LINE_SEPARATOR_KEY, lineSeparator); // avoid documents piling up during batch processing if (areTooManyDocumentsInTheQueue(myUnsavedDocuments)) { saveAllDocumentsLater(); } } } ); } } myMultiCaster.fileContentLoaded(file, document); } return document; } public static boolean areTooManyDocumentsInTheQueue(Collection<Document> documents) { if (documents.size() > 100) return true; int totalSize = 0; for (Document document : documents) { totalSize += document.getTextLength(); if (totalSize > 10 * FileUtilRt.MEGABYTE) return true; } return false; } private static Document createDocument(final CharSequence text, VirtualFile file) { boolean acceptSlashR = file instanceof LightVirtualFile && StringUtil.indexOf(text, '\r') >= 0; return ((EditorFactoryImpl)EditorFactory.getInstance()).createDocument(text, acceptSlashR, false); } private interface DocumentCacheStrategy { @Nullable Document getDocument (@NotNull VirtualFile file); void putDocument (@NotNull VirtualFile file, @NotNull Document document); void invalidateDocument (@NotNull VirtualFile file); } @NotNull private static DocumentCacheStrategy createDocumentCacheStrategy() { return new DocumentCacheStrategy() { private final Map<VirtualFile, Document> myDocuments = ContainerUtil.createConcurrentWeakValueMap(); @Nullable @Override public Document getDocument(@NotNull VirtualFile file) { return myDocuments.get(file); } @Override public void putDocument(@NotNull VirtualFile file, @NotNull Document document) { myDocuments.put(file, document); } @Override public void invalidateDocument(@NotNull VirtualFile file) { myDocuments.remove(file); } }; } @Override @Nullable public Document getCachedDocument(@NotNull VirtualFile file) { Document hard = file.getUserData(HARD_REF_TO_DOCUMENT_KEY); return hard != null ? hard : myDocumentCacheStrategy.getDocument(file); } public static void registerDocument(@NotNull final Document document, @NotNull VirtualFile virtualFile) { synchronized (lock) { virtualFile.putUserData(HARD_REF_TO_DOCUMENT_KEY, document); document.putUserData(FILE_KEY, virtualFile); } } @Override @Nullable public VirtualFile getFile(@NotNull Document document) { return document.getUserData(FILE_KEY); } @TestOnly public void dropAllUnsavedDocuments() { if (!ApplicationManager.getApplication().isUnitTestMode()) { throw new RuntimeException("This method is only for test mode!"); } ApplicationManager.getApplication().assertWriteAccessAllowed(); if (!myUnsavedDocuments.isEmpty()) { myUnsavedDocuments.clear(); fireUnsavedDocumentsDropped(); } } private void saveAllDocumentsLater() { // later because some document might have been blocked by PSI right now ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { if (ApplicationManager.getApplication().isDisposed()) { return; } final Document[] unsavedDocuments = getUnsavedDocuments(); for (Document document : unsavedDocuments) { VirtualFile file = getFile(document); if (file == null) continue; Project project = ProjectUtil.guessProjectForFile(file); if (project == null) continue; if (PsiDocumentManager.getInstance(project).isDocumentBlockedByPsi(document)) continue; saveDocument(document); } } }); } @Override public void saveAllDocuments() { saveAllDocuments(true); } /** * @param isExplicit caused by user directly (Save action) or indirectly (e.g. Compile) */ public void saveAllDocuments(boolean isExplicit) { ApplicationManager.getApplication().assertIsDispatchThread(); myMultiCaster.beforeAllDocumentsSaving(); if (myUnsavedDocuments.isEmpty()) return; final Map<Document, IOException> failedToSave = new HashMap<Document, IOException>(); final Set<Document> vetoed = new HashSet<Document>(); while (true) { int count = 0; for (Document document : myUnsavedDocuments) { if (failedToSave.containsKey(document)) continue; if (vetoed.contains(document)) continue; try { doSaveDocument(document, isExplicit); } catch (IOException e) { //noinspection ThrowableResultOfMethodCallIgnored failedToSave.put(document, e); } catch (SaveVetoException e) { vetoed.add(document); } count++; } if (count == 0) break; } if (!failedToSave.isEmpty()) { handleErrorsOnSave(failedToSave); } } @Override public void saveDocument(@NotNull final Document document) { saveDocument(document, true); } public void saveDocument(@NotNull final Document document, final boolean explicit) { ApplicationManager.getApplication().assertIsDispatchThread(); if (!myUnsavedDocuments.contains(document)) return; try { doSaveDocument(document, explicit); } catch (IOException e) { handleErrorsOnSave(Collections.singletonMap(document, e)); } catch (SaveVetoException ignored) { } } @Override public void saveDocumentAsIs(@NotNull Document document) { VirtualFile file = getFile(document); boolean spaceStrippingEnabled = true; if (file != null) { spaceStrippingEnabled = TrailingSpacesStripper.isEnabled(file); TrailingSpacesStripper.setEnabled(file, false); } try { saveDocument(document); } finally { if (file != null) { TrailingSpacesStripper.setEnabled(file, spaceStrippingEnabled); } } } private static class SaveVetoException extends Exception {} private void doSaveDocument(@NotNull final Document document, boolean isExplicit) throws IOException, SaveVetoException { VirtualFile file = getFile(document); if (file == null || file instanceof LightVirtualFile || file.isValid() && !isFileModified(file)) { removeFromUnsaved(document); return; } if (file.isValid() && needsRefresh(file)) { file.refresh(false, false); if (!myUnsavedDocuments.contains(document)) return; } for (FileDocumentSynchronizationVetoer vetoer : Extensions.getExtensions(FileDocumentSynchronizationVetoer.EP_NAME)) { if (!vetoer.maySaveDocument(document, isExplicit)) { throw new SaveVetoException(); } } final AccessToken token = ApplicationManager.getApplication().acquireWriteActionLock(getClass()); try { doSaveDocumentInWriteAction(document, file); } finally { token.finish(); } } private void doSaveDocumentInWriteAction(@NotNull final Document document, @NotNull final VirtualFile file) throws IOException { if (!file.isValid()) { removeFromUnsaved(document); return; } if (!file.equals(getFile(document))) { registerDocument(document, file); } if (!isSaveNeeded(document, file)) { if (document instanceof DocumentEx) { ((DocumentEx)document).setModificationStamp(file.getModificationStamp()); } removeFromUnsaved(document); updateModifiedProperty(file); return; } PomModelImpl.guardPsiModificationsIn(new ThrowableRunnable<IOException>() { @Override public void run() throws IOException { myMultiCaster.beforeDocumentSaving(document); LOG.assertTrue(file.isValid()); String text = document.getText(); String lineSeparator = getLineSeparator(document, file); if (!lineSeparator.equals("\n")) { text = StringUtil.convertLineSeparators(text, lineSeparator); } Project project = ProjectLocator.getInstance().guessProjectForFile(file); LoadTextUtil.write(project, file, FileDocumentManagerImpl.this, text, document.getModificationStamp()); myUnsavedDocuments.remove(document); LOG.assertTrue(!myUnsavedDocuments.contains(document)); myTrailingSpacesStripper.clearLineModificationFlags(document); } }); } private static void updateModifiedProperty(@NotNull VirtualFile file) { for (Project project : ProjectManager.getInstance().getOpenProjects()) { FileEditorManager fileEditorManager = FileEditorManager.getInstance(project); for (FileEditor editor : fileEditorManager.getAllEditors(file)) { if (editor instanceof TextEditorImpl) { ((TextEditorImpl)editor).updateModifiedProperty(); } } } } private void removeFromUnsaved(@NotNull Document document) { myUnsavedDocuments.remove(document); fireUnsavedDocumentsDropped(); LOG.assertTrue(!myUnsavedDocuments.contains(document)); } private static boolean isSaveNeeded(@NotNull Document document, @NotNull VirtualFile file) throws IOException { if (file.getFileType().isBinary() || document.getTextLength() > 1000 * 1000) { // don't compare if the file is too big return true; } byte[] bytes = file.contentsToByteArray(); CharSequence loaded = LoadTextUtil.getTextByBinaryPresentation(bytes, file, false, false); return !Comparing.equal(document.getCharsSequence(), loaded); } private static boolean needsRefresh(final VirtualFile file) { final VirtualFileSystem fs = file.getFileSystem(); return fs instanceof NewVirtualFileSystem && file.getTimeStamp() != ((NewVirtualFileSystem)fs).getTimeStamp(file); } @NotNull public static String getLineSeparator(@NotNull Document document, @NotNull VirtualFile file) { String lineSeparator = LoadTextUtil.getDetectedLineSeparator(file); if (lineSeparator == null) { lineSeparator = document.getUserData(LINE_SEPARATOR_KEY); assert lineSeparator != null : document; } return lineSeparator; } @Override @NotNull public String getLineSeparator(@Nullable VirtualFile file, @Nullable Project project) { String lineSeparator = file == null ? null : LoadTextUtil.getDetectedLineSeparator(file); if (lineSeparator == null) { CodeStyleFacade settingsManager = project == null ? CodeStyleFacade.getInstance() : CodeStyleFacade.getInstance(project); lineSeparator = settingsManager.getLineSeparator(); } return lineSeparator; } @Override public boolean requestWriting(@NotNull Document document, Project project) { final VirtualFile file = getInstance().getFile(document); if (project != null && file != null && file.isValid()) { return !file.getFileType().isBinary() && ReadonlyStatusHandler.ensureFilesWritable(project, file); } if (document.isWritable()) { return true; } document.fireReadOnlyModificationAttempt(); return false; } @Override public void reloadFiles(@NotNull final VirtualFile... files) { for (VirtualFile file : files) { if (file.exists()) { final Document doc = getCachedDocument(file); if (doc != null) { reloadFromDisk(doc); } } } } @Override @NotNull public Document[] getUnsavedDocuments() { if (myUnsavedDocuments.isEmpty()) { return Document.EMPTY_ARRAY; } List<Document> list = new ArrayList<Document>(myUnsavedDocuments); return list.toArray(new Document[list.size()]); } @Override public boolean isDocumentUnsaved(@NotNull Document document) { return myUnsavedDocuments.contains(document); } @Override public boolean isFileModified(@NotNull VirtualFile file) { final Document doc = getCachedDocument(file); return doc != null && isDocumentUnsaved(doc) && doc.getModificationStamp() != file.getModificationStamp(); } @Override public void propertyChanged(@NotNull VirtualFilePropertyEvent event) { final VirtualFile file = event.getFile(); if (VirtualFile.PROP_WRITABLE.equals(event.getPropertyName())) { final Document document = getCachedDocument(file); if (document != null) { ApplicationManager.getApplication().runWriteAction(new ExternalChangeAction() { @Override public void run() { document.setReadOnly(!file.isWritable()); } }); } } else if (VirtualFile.PROP_NAME.equals(event.getPropertyName())) { Document document = getCachedDocument(file); if (document != null) { // a file is linked to a document - chances are it is an "unknown text file" now if (isBinaryWithoutDecompiler(file)) { unbindFileFromDocument(file, document); } } } } private void unbindFileFromDocument(@NotNull VirtualFile file, @NotNull Document document) { myDocumentCacheStrategy.invalidateDocument(file); file.putUserData(HARD_REF_TO_DOCUMENT_KEY, null); document.putUserData(FILE_KEY, null); } private static boolean isBinaryWithDecompiler(@NotNull VirtualFile file) { final FileType ft = file.getFileType(); return ft.isBinary() && BinaryFileTypeDecompilers.INSTANCE.forFileType(ft) != null; } private static boolean isBinaryWithoutDecompiler(@NotNull VirtualFile file) { final FileType fileType = file.getFileType(); return fileType.isBinary() && BinaryFileTypeDecompilers.INSTANCE.forFileType(fileType) == null; } @Override public void contentsChanged(@NotNull VirtualFileEvent event) { if (event.isFromSave()) return; final VirtualFile file = event.getFile(); final Document document = getCachedDocument(file); if (document == null) { myMultiCaster.fileWithNoDocumentChanged(file); return; } if (isBinaryWithDecompiler(file)) { myMultiCaster.fileWithNoDocumentChanged(file); // This will generate PSI event at FileManagerImpl } long documentStamp = document.getModificationStamp(); long oldFileStamp = event.getOldModificationStamp(); if (documentStamp != oldFileStamp) { LOG.info("reload " + file.getName() + " from disk?"); LOG.info(" documentStamp:" + documentStamp); LOG.info(" oldFileStamp:" + oldFileStamp); if (file.isValid() && askReloadFromDisk(file, document)) { reloadFromDisk(document); } } else { reloadFromDisk(document); } } @Override public void reloadFromDisk(@NotNull final Document document) { ApplicationManager.getApplication().assertIsDispatchThread(); final VirtualFile file = getFile(document); assert file != null; if (!fireBeforeFileContentReload(file, document)) { return; } if (file.getLength() > FileUtilRt.LARGE_FOR_CONTENT_LOADING) { unbindFileFromDocument(file, document); myUnsavedDocuments.remove(document); myMultiCaster.fileWithNoDocumentChanged(file); return; } final Project project = ProjectLocator.getInstance().guessProjectForFile(file); CommandProcessor.getInstance().executeCommand(project, new Runnable() { @Override public void run() { ApplicationManager.getApplication().runWriteAction( new ExternalChangeAction.ExternalDocumentChange(document, project) { @Override public void run() { boolean wasWritable = document.isWritable(); DocumentEx documentEx = (DocumentEx)document; documentEx.setReadOnly(false); LoadTextUtil.setCharsetWasDetectedFromBytes(file, null); file.setBOM(null); // reset BOM in case we had one and the external change stripped it away if (!isBinaryWithoutDecompiler(file)) { documentEx.replaceText(LoadTextUtil.loadText(file), file.getModificationStamp()); documentEx.setReadOnly(!wasWritable); } } } ); } }, UIBundle.message("file.cache.conflict.action"), null, UndoConfirmationPolicy.REQUEST_CONFIRMATION); myUnsavedDocuments.remove(document); myMultiCaster.fileContentReloaded(file, document); } private volatile PairProcessor<VirtualFile, Document> askReloadFromDisk = new PairProcessor<VirtualFile, Document>() { @Override public boolean process(final VirtualFile file, final Document document) { String message = UIBundle.message("file.cache.conflict.message.text", file.getPresentableUrl()); final DialogBuilder builder = new DialogBuilder(); builder.setCenterPanel(new JLabel(message, Messages.getQuestionIcon(), SwingConstants.CENTER)); builder.addOkAction().setText(UIBundle.message("file.cache.conflict.load.fs.changes.button")); builder.addCancelAction().setText(UIBundle.message("file.cache.conflict.keep.memory.changes.button")); builder.addAction(new AbstractAction(UIBundle.message("file.cache.conflict.show.difference.button")) { @Override public void actionPerformed(ActionEvent e) { final ProjectEx project = (ProjectEx)ProjectLocator.getInstance().guessProjectForFile(file); FileType fileType = file.getFileType(); String fsContent = LoadTextUtil.loadText(file).toString(); DocumentContent content1 = DiffContentFactory.getInstance().create(fsContent, fileType); DocumentContent content2 = DiffContentFactory.getInstance().create(project, document, file); String title = UIBundle.message("file.cache.conflict.for.file.dialog.title", file.getPresentableUrl()); String title1 = UIBundle.message("file.cache.conflict.diff.content.file.system.content"); String title2 = UIBundle.message("file.cache.conflict.diff.content.memory.content"); DiffRequest request = new SimpleDiffRequest(title, content1, content2, title1, title2); request.putUserData(DiffUserDataKeys.GO_TO_SOURCE_DISABLE, true); DialogBuilder diffBuilder = new DialogBuilder(project); DiffRequestPanel diffPanel = DiffManager.getInstance().createRequestPanel(project, diffBuilder, diffBuilder.getWindow()); diffPanel.setRequest(request); diffBuilder.setCenterPanel(diffPanel.getComponent()); diffBuilder.setDimensionServiceKey("FileDocumentManager.FileCacheConflict"); diffBuilder.addOkAction().setText(UIBundle.message("file.cache.conflict.save.changes.button")); diffBuilder.addCancelAction(); diffBuilder.setTitle(title); if (diffBuilder.show() == DialogWrapper.OK_EXIT_CODE) { builder.getDialogWrapper().close(DialogWrapper.CANCEL_EXIT_CODE); } } }); builder.setTitle(UIBundle.message("file.cache.conflict.dialog.title")); builder.setButtonsAlignment(SwingConstants.CENTER); builder.setHelpId("reference.dialogs.fileCacheConflict"); return builder.show() == 0; } }; @TestOnly public void setAskReloadFromDisk(@NotNull Disposable disposable, @NotNull PairProcessor<VirtualFile, Document> newProcessor) { final PairProcessor<VirtualFile, Document> old = askReloadFromDisk; askReloadFromDisk = newProcessor; Disposer.register(disposable, new Disposable() { @Override public void dispose() { askReloadFromDisk = old; } }); } private boolean askReloadFromDisk(final VirtualFile file, final Document document) { ApplicationManager.getApplication().assertIsDispatchThread(); if (!isDocumentUnsaved(document)) return true; return askReloadFromDisk.process(file, document); } @Override public void fileCreated(@NotNull VirtualFileEvent event) { } @Override public void fileDeleted(@NotNull VirtualFileEvent event) { Document doc = getCachedDocument(event.getFile()); if (doc != null) { myTrailingSpacesStripper.documentDeleted(doc); } } @Override public void fileMoved(@NotNull VirtualFileMoveEvent event) { } @Override public void fileCopied(@NotNull VirtualFileCopyEvent event) { fileCreated(event); } @Override public void beforePropertyChange(@NotNull VirtualFilePropertyEvent event) { } @Override public void beforeContentsChange(@NotNull VirtualFileEvent event) { VirtualFile virtualFile = event.getFile(); // check file type in second order to avoid content detection running if (virtualFile.getLength() == 0 && virtualFile.getFileType() == UnknownFileType.INSTANCE) { virtualFile.putUserData(MUST_RECOMPUTE_FILE_TYPE, Boolean.TRUE); } } public static boolean recomputeFileTypeIfNecessary(@NotNull VirtualFile virtualFile) { if (virtualFile.getUserData(MUST_RECOMPUTE_FILE_TYPE) != null) { virtualFile.getFileType(); virtualFile.putUserData(MUST_RECOMPUTE_FILE_TYPE, null); return true; } return false; } @Override public void beforeFileDeletion(@NotNull VirtualFileEvent event) { } @Override public void beforeFileMovement(@NotNull VirtualFileMoveEvent event) { } @Override public void projectOpened(Project project) { } @Override public boolean canCloseProject(Project project) { if (!myUnsavedDocuments.isEmpty()) { myOnClose = true; try { saveAllDocuments(); } finally { myOnClose = false; } } return myUnsavedDocuments.isEmpty(); } @Override public void projectClosed(Project project) { } @Override public void projectClosing(Project project) { } private void fireUnsavedDocumentsDropped() { myMultiCaster.unsavedDocumentsDropped(); } private boolean fireBeforeFileContentReload(final VirtualFile file, @NotNull Document document) { for (FileDocumentSynchronizationVetoer vetoer : Extensions.getExtensions(FileDocumentSynchronizationVetoer.EP_NAME)) { try { if (!vetoer.mayReloadFileContent(file, document)) { return false; } } catch (Exception e) { LOG.error(e); } } myMultiCaster.beforeFileContentReload(file, document); return true; } @NotNull private static FileDocumentManagerListener[] getListeners() { return FileDocumentManagerListener.EP_NAME.getExtensions(); } private void handleErrorsOnSave(@NotNull Map<Document, IOException> failures) { if (ApplicationManager.getApplication().isUnitTestMode()) { IOException ioException = ContainerUtil.getFirstItem(failures.values()); if (ioException != null) { throw new RuntimeException(ioException); } return; } for (IOException exception : failures.values()) { LOG.warn(exception); } final String text = StringUtil.join(failures.values(), new Function<IOException, String>() { @Override public String fun(IOException e) { return e.getMessage(); } }, "\n"); final DialogWrapper dialog = new DialogWrapper(null) { { init(); setTitle(UIBundle.message("cannot.save.files.dialog.title")); } @Override protected void createDefaultActions() { super.createDefaultActions(); myOKAction.putValue(Action.NAME, UIBundle .message(myOnClose ? "cannot.save.files.dialog.ignore.changes" : "cannot.save.files.dialog.revert.changes")); myOKAction.putValue(DEFAULT_ACTION, null); if (!myOnClose) { myCancelAction.putValue(Action.NAME, CommonBundle.getCloseButtonText()); } } @Override protected JComponent createCenterPanel() { final JPanel panel = new JPanel(new BorderLayout(0, 5)); panel.add(new JLabel(UIBundle.message("cannot.save.files.dialog.message")), BorderLayout.NORTH); final JTextPane area = new JTextPane(); area.setText(text); area.setEditable(false); area.setMinimumSize(new Dimension(area.getMinimumSize().width, 50)); panel.add(new JBScrollPane(area, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER), BorderLayout.CENTER); return panel; } }; if (dialog.showAndGet()) { for (Document document : failures.keySet()) { reloadFromDisk(document); } } } }
package org.drools.eclipse.editors.rete; import java.io.ByteArrayInputStream; import java.io.InputStream; import junit.framework.TestCase; import org.drools.eclipse.editors.DRLRuleEditor2; import org.drools.eclipse.editors.ZoomInAction2; import org.drools.eclipse.editors.ZoomOutAction2; import org.eclipse.core.filebuffers.manipulation.ContainerCreator; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.gef.ui.actions.ZoomComboContributionItem; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.ide.IDE; public class ZoomControlTest extends TestCase { private IFile fFile1; private IFile fFile2; private final static IProgressMonitor NULL_MONITOR = new NullProgressMonitor(); private static final String ORIGINAL_CONTENT = "package test\nrule \"a\"\nend\nrule \"b\"\nend"; public ZoomControlTest(String name) { super( name ); } private String getOriginalContent() { return ORIGINAL_CONTENT; } /* * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { IFolder folder = createFolder( "ZoomControlTestProject/multipleEditorTest/" ); fFile1 = createFile( folder, "myfile1.drl", getOriginalContent() ); fFile2 = createFile( folder, "myfile2.drl", getOriginalContent() ); } /* * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { deleteProject( "ZoomControlTestProject" ); fFile1 = null; fFile2 = null; } public void testMultipleEditors() throws PartInitException { IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchPage page = workbench.getActiveWorkbenchWindow().getActivePage(); DRLRuleEditor2 part1 = (DRLRuleEditor2) IDE.openEditor( page, fFile1 ); DRLRuleEditor2 part2 = (DRLRuleEditor2) IDE.openEditor( page, fFile2 ); checkVisibility( part1, part2, false ); // Editor1 active page.activate( part1 ); checkVisibility( part1, part2, false ); // TODO // part1.setActivePage( 1 ); // checkVisibility( part1, // part2, // true ); // // part1.setActivePage( 0 ); // checkVisibility( part1, // part2, // false ); // // part1.setActivePage( 1 ); // checkVisibility( part1, // part2, // true ); // // // Editor2 active // page.activate( part2 ); // part2.setActivePage( 0 ); // checkVisibility( part1, // part2, // false ); // // part2.setActivePage( 1 ); // checkVisibility( part1, // part2, // true ); // // // Editor1 active // page.activate( part1 ); // checkVisibility( part1, // part2, // true ); // // // Editor2 active // page.activate( part2 ); // checkVisibility( part1, // part2, // true ); // // part2.setActivePage( 0 ); // checkVisibility( part1, // part2, // false ); // // // Editor1 active // page.activate( part1 ); // checkVisibility( part1, // part2, // true ); // part2.setActivePage( 0 ); // checkVisibility( part1, // part2, // false ); } public void testSecondEditorAfterFirst() throws PartInitException { IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchPage page = workbench.getActiveWorkbenchWindow().getActivePage(); DRLRuleEditor2 part1 = (DRLRuleEditor2) IDE.openEditor( page, fFile1 ); // TODO // // Editor1 active // page.activate( part1 ); // part1.setActivePage( 1 ); // checkVisibility( part1, // null, // true ); // // DRLRuleEditor2 part2 = (DRLRuleEditor2) IDE.openEditor( page, // fFile2 ); // page.activate( part2 ); // checkVisibility( part1, // part2, // false ); } private void checkVisibility(DRLRuleEditor2 part1, DRLRuleEditor2 part2, boolean enabled) { if ( part1 != null ) { checkVisibility( part1, enabled ); } if ( part2 != null ) { checkVisibility( part2, enabled ); } } private void checkVisibility(DRLRuleEditor2 editor, boolean enabled) { ZoomInAction2 zoomIn = (ZoomInAction2) editor.getAdapter( ZoomInAction2.class ); ZoomOutAction2 zoomOut = (ZoomOutAction2) editor.getAdapter( ZoomOutAction2.class ); ZoomComboContributionItem zitem = (ZoomComboContributionItem) editor.getAdapter( ZoomComboContributionItem.class ); assertEquals( enabled, zoomIn.isEnabled() ); assertEquals( enabled, zoomOut.isEnabled() ); assertEquals( enabled, zitem.getZoomManager() != null ); } private IFile createFile(IFolder folder, String name, String contents) throws CoreException { IFile file = folder.getFile( name ); InputStream inputStream = new ByteArrayInputStream( contents.getBytes() ); file.create( inputStream, true, NULL_MONITOR ); return file; } private IFolder createFolder(String portableFolderPath) throws CoreException { ContainerCreator creator = new ContainerCreator( ResourcesPlugin.getWorkspace(), new Path( portableFolderPath ) ); IContainer container = creator.createContainer( NULL_MONITOR ); return (IFolder) container; } private void deleteProject(String projectName) throws CoreException { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = root.getProject( projectName ); if ( project.exists() ) project.delete( true, true, NULL_MONITOR ); } }
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.models.sessions.infinispan; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.keycloak.models.ClientModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; import org.keycloak.models.sessions.infinispan.entities.AuthenticationSessionEntity; import org.keycloak.sessions.AuthenticationSessionModel; import org.keycloak.sessions.RootAuthenticationSessionModel; /** * NOTE: Calling setter doesn't automatically enlist for update * * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> */ public class AuthenticationSessionAdapter implements AuthenticationSessionModel { private final KeycloakSession session; private final RootAuthenticationSessionAdapter parent; private final String tabId; private AuthenticationSessionEntity entity; public AuthenticationSessionAdapter(KeycloakSession session, RootAuthenticationSessionAdapter parent, String tabId, AuthenticationSessionEntity entity) { this.session = session; this.parent = parent; this.tabId = tabId; this.entity = entity; } private void update() { parent.update(); } @Override public String getTabId() { return tabId; } @Override public RootAuthenticationSessionModel getParentSession() { return parent; } @Override public RealmModel getRealm() { return parent.getRealm(); } @Override public ClientModel getClient() { return getRealm().getClientById(entity.getClientUUID()); } @Override public String getRedirectUri() { return entity.getRedirectUri(); } @Override public void setRedirectUri(String uri) { entity.setRedirectUri(uri); update(); } @Override public String getAction() { return entity.getAction(); } @Override public void setAction(String action) { entity.setAction(action); update(); } @Override public Set<String> getClientScopes() { if (entity.getClientScopes() == null || entity.getClientScopes().isEmpty()) return Collections.emptySet(); return new HashSet<>(entity.getClientScopes()); } @Override public void setClientScopes(Set<String> clientScopes) { entity.setClientScopes(clientScopes); update(); } @Override public String getProtocol() { return entity.getProtocol(); } @Override public void setProtocol(String protocol) { entity.setProtocol(protocol); update(); } @Override public String getClientNote(String name) { return (entity.getClientNotes() != null && name != null) ? entity.getClientNotes().get(name) : null; } @Override public void setClientNote(String name, String value) { if (entity.getClientNotes() == null) { entity.setClientNotes(new ConcurrentHashMap<>()); } if (name != null) { if (value == null) { entity.getClientNotes().remove(name); } else { entity.getClientNotes().put(name, value); } } update(); } @Override public void removeClientNote(String name) { if (entity.getClientNotes() != null && name != null) { entity.getClientNotes().remove(name); } update(); } @Override public Map<String, String> getClientNotes() { if (entity.getClientNotes() == null || entity.getClientNotes().isEmpty()) return Collections.emptyMap(); Map<String, String> copy = new ConcurrentHashMap<>(); copy.putAll(entity.getClientNotes()); return copy; } @Override public void clearClientNotes() { entity.setClientNotes(new ConcurrentHashMap<>()); update(); } @Override public String getAuthNote(String name) { return (entity.getAuthNotes() != null && name != null) ? entity.getAuthNotes().get(name) : null; } @Override public void setAuthNote(String name, String value) { if (entity.getAuthNotes() == null) { entity.setAuthNotes(new ConcurrentHashMap<>()); } if (name != null) { if (value == null) { entity.getAuthNotes().remove(name); } else { entity.getAuthNotes().put(name, value); } } update(); } @Override public void removeAuthNote(String name) { if (entity.getAuthNotes() != null && name != null) { entity.getAuthNotes().remove(name); } update(); } @Override public void clearAuthNotes() { entity.setAuthNotes(new ConcurrentHashMap<>()); update(); } @Override public void setUserSessionNote(String name, String value) { if (entity.getUserSessionNotes() == null) { entity.setUserSessionNotes(new ConcurrentHashMap<>()); } if (name != null) { if (value == null) { entity.getUserSessionNotes().remove(name); } else { entity.getUserSessionNotes().put(name, value); } } update(); } @Override public Map<String, String> getUserSessionNotes() { if (entity.getUserSessionNotes() == null) { return Collections.EMPTY_MAP; } ConcurrentHashMap<String, String> copy = new ConcurrentHashMap<>(); copy.putAll(entity.getUserSessionNotes()); return copy; } @Override public void clearUserSessionNotes() { entity.setUserSessionNotes(new ConcurrentHashMap<>()); update(); } @Override public Set<String> getRequiredActions() { Set<String> copy = new HashSet<>(); copy.addAll(entity.getRequiredActions()); return copy; } @Override public void addRequiredAction(String action) { entity.getRequiredActions().add(action); update(); } @Override public void removeRequiredAction(String action) { entity.getRequiredActions().remove(action); update(); } @Override public void addRequiredAction(UserModel.RequiredAction action) { addRequiredAction(action.name()); } @Override public void removeRequiredAction(UserModel.RequiredAction action) { removeRequiredAction(action.name()); } @Override public Map<String, AuthenticationSessionModel.ExecutionStatus> getExecutionStatus() { return entity.getExecutionStatus(); } @Override public void setExecutionStatus(String authenticator, AuthenticationSessionModel.ExecutionStatus status) { entity.getExecutionStatus().put(authenticator, status); update(); } @Override public void clearExecutionStatus() { entity.getExecutionStatus().clear(); update(); } @Override public UserModel getAuthenticatedUser() { return entity.getAuthUserId() == null ? null : session.users().getUserById(getRealm(), entity.getAuthUserId()); } @Override public void setAuthenticatedUser(UserModel user) { if (user == null) entity.setAuthUserId(null); else entity.setAuthUserId(user.getId()); update(); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.metadata; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import io.airlift.json.JsonCodec; import io.airlift.json.JsonCodecFactory; import io.prestosql.Session; import io.prestosql.SystemSessionProperties; import io.prestosql.connector.CatalogName; import io.prestosql.spi.PrestoException; import io.prestosql.spi.block.BlockBuilder; import io.prestosql.spi.session.PropertyMetadata; import io.prestosql.spi.type.ArrayType; import io.prestosql.spi.type.BigintType; import io.prestosql.spi.type.BooleanType; import io.prestosql.spi.type.DoubleType; import io.prestosql.spi.type.IntegerType; import io.prestosql.spi.type.MapType; import io.prestosql.spi.type.Type; import io.prestosql.spi.type.VarcharType; import io.prestosql.sql.planner.ParameterRewriter; import io.prestosql.sql.tree.Expression; import io.prestosql.sql.tree.ExpressionTreeRewriter; import javax.annotation.Nullable; import javax.inject.Inject; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkState; import static io.prestosql.spi.StandardErrorCode.INVALID_SESSION_PROPERTY; import static io.prestosql.spi.type.TypeUtils.writeNativeValue; import static io.prestosql.sql.planner.ExpressionInterpreter.evaluateConstantExpression; import static java.lang.String.format; import static java.util.Objects.requireNonNull; public final class SessionPropertyManager { private static final JsonCodecFactory JSON_CODEC_FACTORY = new JsonCodecFactory(); private final ConcurrentMap<String, PropertyMetadata<?>> systemSessionProperties = new ConcurrentHashMap<>(); private final ConcurrentMap<CatalogName, Map<String, PropertyMetadata<?>>> connectorSessionProperties = new ConcurrentHashMap<>(); public SessionPropertyManager() { this(new SystemSessionProperties()); } @Inject public SessionPropertyManager(SystemSessionProperties systemSessionProperties) { this(systemSessionProperties.getSessionProperties()); } public SessionPropertyManager(List<PropertyMetadata<?>> systemSessionProperties) { addSystemSessionProperties(systemSessionProperties); } public void addSystemSessionProperties(List<PropertyMetadata<?>> systemSessionProperties) { systemSessionProperties .forEach(this::addSystemSessionProperty); } public void addSystemSessionProperty(PropertyMetadata<?> sessionProperty) { requireNonNull(sessionProperty, "sessionProperty is null"); checkState(systemSessionProperties.put(sessionProperty.getName(), sessionProperty) == null, "System session property '%s' are already registered", sessionProperty.getName()); } public void addConnectorSessionProperties(CatalogName catalogName, List<PropertyMetadata<?>> properties) { requireNonNull(catalogName, "catalogName is null"); requireNonNull(properties, "properties is null"); Map<String, PropertyMetadata<?>> propertiesByName = Maps.uniqueIndex(properties, PropertyMetadata::getName); checkState(connectorSessionProperties.putIfAbsent(catalogName, propertiesByName) == null, "Session properties for catalog '%s' are already registered", catalogName); } public void removeConnectorSessionProperties(CatalogName catalogName) { connectorSessionProperties.remove(catalogName); } public Optional<PropertyMetadata<?>> getSystemSessionPropertyMetadata(String name) { requireNonNull(name, "name is null"); return Optional.ofNullable(systemSessionProperties.get(name)); } public Optional<PropertyMetadata<?>> getConnectorSessionPropertyMetadata(CatalogName catalogName, String propertyName) { requireNonNull(catalogName, "catalogName is null"); requireNonNull(propertyName, "propertyName is null"); Map<String, PropertyMetadata<?>> properties = connectorSessionProperties.get(catalogName); if (properties == null || properties.isEmpty()) { throw new PrestoException(INVALID_SESSION_PROPERTY, "Unknown connector " + catalogName); } return Optional.ofNullable(properties.get(propertyName)); } public List<SessionPropertyValue> getAllSessionProperties(Session session, Map<String, CatalogName> catalogs) { requireNonNull(session, "session is null"); ImmutableList.Builder<SessionPropertyValue> sessionPropertyValues = ImmutableList.builder(); Map<String, String> systemProperties = session.getSystemProperties(); for (PropertyMetadata<?> property : new TreeMap<>(systemSessionProperties).values()) { String defaultValue = firstNonNull(property.getDefaultValue(), "").toString(); String value = systemProperties.getOrDefault(property.getName(), defaultValue); sessionPropertyValues.add(new SessionPropertyValue( value, defaultValue, property.getName(), Optional.empty(), property.getName(), property.getDescription(), property.getSqlType().getDisplayName(), property.isHidden())); } for (Entry<String, CatalogName> entry : new TreeMap<>(catalogs).entrySet()) { String catalog = entry.getKey(); CatalogName catalogName = entry.getValue(); Map<String, String> connectorProperties = session.getConnectorProperties(catalogName); for (PropertyMetadata<?> property : new TreeMap<>(connectorSessionProperties.get(catalogName)).values()) { String defaultValue = firstNonNull(property.getDefaultValue(), "").toString(); String value = connectorProperties.getOrDefault(property.getName(), defaultValue); sessionPropertyValues.add(new SessionPropertyValue( value, defaultValue, catalog + "." + property.getName(), Optional.of(catalog), property.getName(), property.getDescription(), property.getSqlType().getDisplayName(), property.isHidden())); } } return sessionPropertyValues.build(); } public <T> T decodeSystemPropertyValue(String name, @Nullable String value, Class<T> type) { PropertyMetadata<?> property = getSystemSessionPropertyMetadata(name) .orElseThrow(() -> new PrestoException(INVALID_SESSION_PROPERTY, "Unknown session property " + name)); return decodePropertyValue(name, value, type, property); } public <T> T decodeCatalogPropertyValue(CatalogName catalog, String catalogName, String propertyName, @Nullable String propertyValue, Class<T> type) { String fullPropertyName = catalogName + "." + propertyName; PropertyMetadata<?> property = getConnectorSessionPropertyMetadata(catalog, propertyName) .orElseThrow(() -> new PrestoException(INVALID_SESSION_PROPERTY, "Unknown session property " + fullPropertyName)); return decodePropertyValue(fullPropertyName, propertyValue, type, property); } public void validateSystemSessionProperty(String propertyName, String propertyValue) { PropertyMetadata<?> propertyMetadata = getSystemSessionPropertyMetadata(propertyName) .orElseThrow(() -> new PrestoException(INVALID_SESSION_PROPERTY, "Unknown session property " + propertyName)); decodePropertyValue(propertyName, propertyValue, propertyMetadata.getJavaType(), propertyMetadata); } public void validateCatalogSessionProperty(CatalogName catalog, String catalogName, String propertyName, String propertyValue) { String fullPropertyName = catalogName + "." + propertyName; PropertyMetadata<?> propertyMetadata = getConnectorSessionPropertyMetadata(catalog, propertyName) .orElseThrow(() -> new PrestoException(INVALID_SESSION_PROPERTY, "Unknown session property " + fullPropertyName)); decodePropertyValue(fullPropertyName, propertyValue, propertyMetadata.getJavaType(), propertyMetadata); } private static <T> T decodePropertyValue(String fullPropertyName, @Nullable String propertyValue, Class<T> type, PropertyMetadata<?> metadata) { if (metadata.getJavaType() != type) { throw new PrestoException(INVALID_SESSION_PROPERTY, format("Property %s is type %s, but requested type was %s", fullPropertyName, metadata.getJavaType().getName(), type.getName())); } if (propertyValue == null) { return type.cast(metadata.getDefaultValue()); } Object objectValue = deserializeSessionProperty(metadata.getSqlType(), propertyValue); try { return type.cast(metadata.decode(objectValue)); } catch (PrestoException e) { throw e; } catch (Exception e) { // the system property decoder can throw any exception throw new PrestoException(INVALID_SESSION_PROPERTY, format("%s is invalid: %s", fullPropertyName, propertyValue), e); } } public static Object evaluatePropertyValue(Expression expression, Type expectedType, Session session, Metadata metadata, List<Expression> parameters) { Expression rewritten = ExpressionTreeRewriter.rewriteWith(new ParameterRewriter(parameters), expression); Object value = evaluateConstantExpression(rewritten, expectedType, metadata, session, parameters); // convert to object value type of SQL type BlockBuilder blockBuilder = expectedType.createBlockBuilder(null, 1); writeNativeValue(expectedType, blockBuilder, value); Object objectValue = expectedType.getObjectValue(session.toConnectorSession(), blockBuilder, 0); if (objectValue == null) { throw new PrestoException(INVALID_SESSION_PROPERTY, "Session property value must not be null"); } return objectValue; } public static String serializeSessionProperty(Type type, Object value) { if (value == null) { throw new PrestoException(INVALID_SESSION_PROPERTY, "Session property can not be null"); } if (BooleanType.BOOLEAN.equals(type)) { return value.toString(); } if (BigintType.BIGINT.equals(type)) { return value.toString(); } if (IntegerType.INTEGER.equals(type)) { return value.toString(); } if (DoubleType.DOUBLE.equals(type)) { return value.toString(); } if (VarcharType.VARCHAR.equals(type)) { return value.toString(); } if (type instanceof ArrayType || type instanceof MapType) { return getJsonCodecForType(type).toJson(value); } throw new PrestoException(INVALID_SESSION_PROPERTY, format("Session property type %s is not supported", type)); } private static Object deserializeSessionProperty(Type type, String value) { if (value == null) { throw new PrestoException(INVALID_SESSION_PROPERTY, "Session property can not be null"); } if (VarcharType.VARCHAR.equals(type)) { return value; } if (BooleanType.BOOLEAN.equals(type)) { return Boolean.valueOf(value); } if (BigintType.BIGINT.equals(type)) { return Long.valueOf(value); } if (IntegerType.INTEGER.equals(type)) { return Integer.valueOf(value); } if (DoubleType.DOUBLE.equals(type)) { return Double.valueOf(value); } if (type instanceof ArrayType || type instanceof MapType) { return getJsonCodecForType(type).fromJson(value); } throw new PrestoException(INVALID_SESSION_PROPERTY, format("Session property type %s is not supported", type)); } private static <T> JsonCodec<T> getJsonCodecForType(Type type) { if (VarcharType.VARCHAR.equals(type)) { return (JsonCodec<T>) JSON_CODEC_FACTORY.jsonCodec(String.class); } if (BooleanType.BOOLEAN.equals(type)) { return (JsonCodec<T>) JSON_CODEC_FACTORY.jsonCodec(Boolean.class); } if (BigintType.BIGINT.equals(type)) { return (JsonCodec<T>) JSON_CODEC_FACTORY.jsonCodec(Long.class); } if (IntegerType.INTEGER.equals(type)) { return (JsonCodec<T>) JSON_CODEC_FACTORY.jsonCodec(Integer.class); } if (DoubleType.DOUBLE.equals(type)) { return (JsonCodec<T>) JSON_CODEC_FACTORY.jsonCodec(Double.class); } if (type instanceof ArrayType) { Type elementType = ((ArrayType) type).getElementType(); return (JsonCodec<T>) JSON_CODEC_FACTORY.listJsonCodec(getJsonCodecForType(elementType)); } if (type instanceof MapType) { Type keyType = ((MapType) type).getKeyType(); Type valueType = ((MapType) type).getValueType(); return (JsonCodec<T>) JSON_CODEC_FACTORY.mapJsonCodec(getMapKeyType(keyType), getJsonCodecForType(valueType)); } throw new PrestoException(INVALID_SESSION_PROPERTY, format("Session property type %s is not supported", type)); } private static Class<?> getMapKeyType(Type type) { if (VarcharType.VARCHAR.equals(type)) { return String.class; } if (BooleanType.BOOLEAN.equals(type)) { return Boolean.class; } if (BigintType.BIGINT.equals(type)) { return Long.class; } if (IntegerType.INTEGER.equals(type)) { return Integer.class; } if (DoubleType.DOUBLE.equals(type)) { return Double.class; } throw new PrestoException(INVALID_SESSION_PROPERTY, format("Session property map key type %s is not supported", type)); } public static class SessionPropertyValue { private final String fullyQualifiedName; private final Optional<String> catalogName; private final String propertyName; private final String description; private final String type; private final String value; private final String defaultValue; private final boolean hidden; private SessionPropertyValue(String value, String defaultValue, String fullyQualifiedName, Optional<String> catalogName, String propertyName, String description, String type, boolean hidden) { this.fullyQualifiedName = fullyQualifiedName; this.catalogName = catalogName; this.propertyName = propertyName; this.description = description; this.type = type; this.value = value; this.defaultValue = defaultValue; this.hidden = hidden; } public String getFullyQualifiedName() { return fullyQualifiedName; } public Optional<String> getCatalogName() { return catalogName; } public String getPropertyName() { return propertyName; } public String getDescription() { return description; } public String getType() { return type; } public String getValue() { return value; } public String getDefaultValue() { return defaultValue; } public boolean isHidden() { return hidden; } } }
/** *============================================================================ * The Ohio State University Research Foundation, Emory University, * the University of Minnesota Supercomputing Institute * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cagrid-grid-incubation/LICENSE.txt for details. *============================================================================ **/ /** *============================================================================ *============================================================================ **/ package org.cagrid.i2b2.domain; import java.util.ArrayList; import org.apache.commons.collections.CollectionUtils; public class Concept extends I2B2Type { private String conceptPath = null; private String name = null; private Double cdePublicId = null; private String cdeVersion = null; private String projectName = null; private Double projectVersion = null; private String encodingServiceURL = null; private Observation observation = null; private ArrayList<MapData> mapDataCollection = null; public Concept() { super(); } public String getConceptPath() { return conceptPath; } public void setConceptPath(String conceptPath) { this.conceptPath = conceptPath; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getCdePublicId() { return cdePublicId; } public void setCdePublicId(Double cdePublicId) { this.cdePublicId = cdePublicId; } public String getCdeVersion() { return cdeVersion; } public void setCdeVersion(String cdeVersion) { this.cdeVersion = cdeVersion; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public Double getProjectVersion() { return projectVersion; } public void setProjectVersion(Double projectVersion) { this.projectVersion = projectVersion; } public String getEncodingServiceURL() { return encodingServiceURL; } public void setEncodingServiceURL(String encodingServiceURL) { this.encodingServiceURL = encodingServiceURL; } public Observation getObservation() { return this.observation; } public void setObservation(Observation observation) { this.observation = observation; } public ArrayList<MapData> getMapDataCollection() { return mapDataCollection; } public void setMapDataCollection(ArrayList<MapData> mapDataCollection) { this.mapDataCollection = mapDataCollection; } public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((cdePublicId == null) ? 0 : cdePublicId.hashCode()); result = prime * result + ((cdeVersion == null) ? 0 : cdeVersion.hashCode()); result = prime * result + ((conceptPath == null) ? 0 : conceptPath.hashCode()); result = prime * result + ((encodingServiceURL == null) ? 0 : encodingServiceURL.hashCode()); result = prime * result + ((mapDataCollection == null) ? 0 : mapDataCollection.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((observation == null) ? 0 : observation.hashCode()); result = prime * result + ((projectName == null) ? 0 : projectName.hashCode()); result = prime * result + ((projectVersion == null) ? 0 : projectVersion.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } Concept other = (Concept) obj; if (cdePublicId == null) { if (other.cdePublicId != null) { return false; } } else if (!cdePublicId.equals(other.cdePublicId)) { return false; } if (cdeVersion == null) { if (other.cdeVersion != null) { return false; } } else if (!cdeVersion.equals(other.cdeVersion)) { return false; } if (conceptPath == null) { if (other.conceptPath != null) { return false; } } else if (!conceptPath.equals(other.conceptPath)) { return false; } if (encodingServiceURL == null) { if (other.encodingServiceURL != null) { return false; } } else if (!encodingServiceURL.equals(other.encodingServiceURL)) { return false; } if (mapDataCollection == null) { if (other.mapDataCollection != null) { return false; } } else if (!CollectionUtils.isEqualCollection(mapDataCollection, other.mapDataCollection)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (observation == null) { if (other.observation != null) { return false; } } else if (!observation.equals(other.observation)) { return false; } if (projectName == null) { if (other.projectName != null) { return false; } } else if (!projectName.equals(other.projectName)) { return false; } if (projectVersion == null) { if (other.projectVersion != null) { return false; } } else if (!projectVersion.equals(other.projectVersion)) { return false; } return true; } }
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. See License.txt in the project root for license information. */ package com.microsoft.azure.engagement.unity; import android.app.Activity; import android.net.Uri; import android.util.Log; import org.json.JSONObject; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Bundle; import com.microsoft.azure.engagement.shared.EngagementShared; import com.microsoft.azure.engagement.shared.EngagementDelegate; import com.unity3d.player.UnityPlayer; public class EngagementWrapper { private static final String pluginName = "UNITY"; private static final String pluginVersion = "1.2.2"; private static final String nativeVersion = "4.2.3"; // to eventually retrieve from the SDK itself private static final String unityMethod_onDataPushReceived = "onDataPushReceived"; private static final String unityMethod_onHandleUrl = "onHandleURL"; private static final String unityMethod_onStatusReceived= "onStatusReceived"; private static Activity androidActivity ; private static String openURL; private static String unityObjectName = null; // Helper private static void UnitySendMessage(String _method,String _message) { if ( unityObjectName == null) Log.e(EngagementShared.LOG_TAG, "Missing unityObjectMethod"); UnityPlayer.UnitySendMessage(unityObjectName, _method, _message); } private static EngagementDelegate engagementDelegate = new EngagementDelegate() { @Override public void didReceiveDataPush(JSONObject _data) { UnitySendMessage(unityMethod_onDataPushReceived, _data.toString()); } }; public static void handleOpenURL(String _url) { Log.i(EngagementShared.LOG_TAG, "handleOpenURL: " + _url); openURL = _url; } public static void processOpenUrl() { if (openURL == null) return ; Log.i(EngagementShared.LOG_TAG,"onHandleOpenURL: "+openURL); UnitySendMessage(unityMethod_onHandleUrl, openURL); openURL = null; } // Unity Interface public static void setAndroidActivity(Activity _androidActivity) { androidActivity = _androidActivity; Uri data = _androidActivity.getIntent().getData(); if (data != null) { String lastUrl = data.toString(); handleOpenURL(lastUrl); } } public static void registerApp( String _instanceName, String _connectionString, int _locationType, int _locationMode, boolean _enablePluginLog) { unityObjectName = _instanceName; if (androidActivity == null) { Log.e(EngagementShared.LOG_TAG,"missing AndroidActivty (setAndroidActivity() not being called?)"); return ; } if (EngagementShared.instance().alreadyInitialized()) { Log.e(EngagementShared.LOG_TAG,"registerApp() already called"); return ; } try { ApplicationInfo ai = androidActivity.getPackageManager().getApplicationInfo(androidActivity.getPackageName(), PackageManager.GET_META_DATA); Bundle bundle = ai.metaData; String mfPluginVersion = bundle.getString("engagement:unity:version"); if (mfPluginVersion == null) throw new PackageManager.NameNotFoundException(); if (pluginVersion.equals(mfPluginVersion)==false) Log.i(EngagementShared.LOG_TAG, "Unity Plugin Version (" + pluginVersion +") does not match manifest version ("+mfPluginVersion+") : Manifest might need to be regenerated"); } catch ( Exception e) { Log.e(EngagementShared.LOG_TAG, "Cannot find engagement:unity:version in Android Manifest : Manifest file needs to be generated through File/Engagement/Generate Android Manifest"); } EngagementShared.instance().setPluginLog(_enablePluginLog); EngagementShared.instance().initSDK(pluginName, pluginVersion, nativeVersion); EngagementShared.instance().setDelegate(engagementDelegate); EngagementShared.locationReportingType locationReporting = EngagementShared.locationReportingType.fromInteger(_locationType); EngagementShared.backgroundReportingType background = EngagementShared.backgroundReportingType.fromInteger(_locationMode); EngagementShared.instance().initialize(androidActivity, _connectionString, locationReporting, background); // We consider the app to be active on registerApp as onResume() is not being automatically called EngagementShared.instance().onResume(); } public static void initializeReach() { processOpenUrl(); EngagementShared.instance().enableDataPush(); } public static void startActivity(String _activityName, String _extraInfos) { EngagementShared.instance().startActivity(_activityName, _extraInfos); } public static void endActivity() { EngagementShared.instance().endActivity(); } public static void startJob(String _jobName, String _extraInfos) { EngagementShared.instance().startJob(_jobName, _extraInfos); } public static void endJob(String _jobName) { EngagementShared.instance().endJob(_jobName); } public static void sendEvent(String _eventName, String _extraInfos) { EngagementShared.instance().sendEvent(_eventName, _extraInfos); } public static void sendAppInfo(String _extraInfos) { EngagementShared.instance().sendAppInfo(_extraInfos); } public static void sendSessionEvent(String _eventName, String _extraInfos) { EngagementShared.instance().sendSessionEvent(_eventName, _extraInfos); } public static void sendJobEvent(String _eventName, String _jobName,String _extraInfos) { EngagementShared.instance().sendJobEvent(_eventName, _jobName, _extraInfos); } public static void sendError(String _errorName, String _extraInfos) { EngagementShared.instance().sendError(_errorName, _extraInfos); } public static void sendSessionError(String _errorName, String _extraInfos) { EngagementShared.instance().sendSessionError(_errorName, _extraInfos); } public static void sendJobError(String _errorName, String _jobName, String _extraInfos) { EngagementShared.instance().sendJobError(_errorName, _jobName, _extraInfos); } public static void getStatus() { EngagementShared.instance().getStatus(new EngagementDelegate() { @Override public void onGetStatusResult(JSONObject _result) { UnitySendMessage(unityMethod_onStatusReceived, _result.toString()); } }); } public static void setEnabled(boolean _enabled) { EngagementShared.instance().setEnabled(_enabled); } public static void onApplicationPause(boolean _paused) { final boolean paused = _paused; // Check if there's an url to be processed processOpenUrl(); // When clicking on a view, we may be called from another thread UnityPlayer.currentActivity.runOnUiThread(new Runnable() { public void run() { if (paused) { EngagementShared.instance().onPause(); } else { EngagementShared.instance().onResume(); } } }); } }
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.engine.impl.batch.builder; import org.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.authorization.Permission; import org.camunda.bpm.engine.batch.Batch; import org.camunda.bpm.engine.impl.batch.BatchConfiguration; import org.camunda.bpm.engine.impl.batch.BatchEntity; import org.camunda.bpm.engine.impl.batch.BatchJobHandler; import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.camunda.bpm.engine.impl.interceptor.CommandContext; import org.camunda.bpm.engine.impl.jobexecutor.JobHandler; import java.util.List; import java.util.Map; public class BatchBuilder { protected CommandContext commandContext; protected BatchConfiguration config; protected String tenantId; protected String type; protected Integer totalJobsCount; protected Permission permission; protected PermissionHandler permissionHandler; protected OperationLogInstanceCountHandler operationLogInstanceCountHandler; protected OperationLogHandler operationLogHandler; public BatchBuilder(CommandContext commandContext) { this.commandContext = commandContext; } public BatchBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } public BatchBuilder config(BatchConfiguration config) { this.config = config; return this; } public BatchBuilder type(String batchType) { this.type = batchType; return this; } public BatchBuilder totalJobs(int totalJobsCount) { this.totalJobsCount = totalJobsCount; return this; } public BatchBuilder permission(Permission permission) { this.permission = permission; return this; } public BatchBuilder permissionHandler(PermissionHandler permissionCheckHandler) { this.permissionHandler = permissionCheckHandler; return this; } public BatchBuilder operationLogHandler(OperationLogInstanceCountHandler operationLogHandler) { this.operationLogInstanceCountHandler = operationLogHandler; return this; } public BatchBuilder operationLogHandler(OperationLogHandler operationLogHandler) { this.operationLogHandler = operationLogHandler; return this; } public Batch build() { checkPermissions(); BatchEntity batch = new BatchEntity(); configure(batch); save(batch); writeOperationLog(); return batch; } protected void checkPermissions() { if (permission == null && permissionHandler == null) { throw new ProcessEngineException("No permission check performed!"); } if (permission != null) { commandContext.getProcessEngineConfiguration() .getCommandCheckers() .forEach(checker -> checker.checkCreateBatch(permission)); } if (permissionHandler != null) { permissionHandler.check(commandContext); } } @SuppressWarnings(value = "unchecked") protected BatchEntity configure(BatchEntity batch) { ProcessEngineConfigurationImpl engineConfig = commandContext.getProcessEngineConfiguration(); Map<String, JobHandler> jobHandlers = engineConfig.getJobHandlers(); BatchJobHandler jobHandler = (BatchJobHandler) jobHandlers.get(type); String type = jobHandler.getType(); batch.setType(type); int invocationPerBatchJobCount = calculateInvocationsPerBatchJob(type); batch.setInvocationsPerBatchJob(invocationPerBatchJobCount); batch.setTenantId(tenantId); byte[] configAsBytes = jobHandler.writeConfiguration(config); batch.setConfigurationBytes(configAsBytes); setTotalJobs(batch, invocationPerBatchJobCount); int jobCount = engineConfig.getBatchJobsPerSeed(); batch.setBatchJobsPerSeed(jobCount); return batch; } protected void setTotalJobs(BatchEntity batch, int invocationPerBatchJobCount) { if (totalJobsCount != null) { batch.setTotalJobs(totalJobsCount); } else { List<String> instanceIds = config.getIds(); int instanceCount = instanceIds.size(); int totalJobsCount = calculateTotalJobs(instanceCount, invocationPerBatchJobCount); batch.setTotalJobs(totalJobsCount); } } protected void save(BatchEntity batch) { commandContext.getBatchManager().insertBatch(batch); String seedDeploymentId = null; if (config.getIdMappings() != null && !config.getIdMappings().isEmpty()) { seedDeploymentId = config.getIdMappings().get(0).getDeploymentId(); } batch.createSeedJobDefinition(seedDeploymentId); batch.createMonitorJobDefinition(); batch.createBatchJobDefinition(); batch.fireHistoricStartEvent(); batch.createSeedJob(); } protected void writeOperationLog() { if (operationLogInstanceCountHandler == null && operationLogHandler == null) { throw new ProcessEngineException("No operation log handler specified!"); } if (operationLogInstanceCountHandler != null) { List<String> instanceIds = config.getIds(); int instanceCount = instanceIds.size(); operationLogInstanceCountHandler.write(commandContext, instanceCount); } else { operationLogHandler.write(commandContext); } } protected int calculateTotalJobs(int instanceCount, int invocationPerBatchJobCount) { if (instanceCount == 0 || invocationPerBatchJobCount == 0) { return 0; } if (instanceCount % invocationPerBatchJobCount == 0) { return instanceCount / invocationPerBatchJobCount; } return (instanceCount / invocationPerBatchJobCount) + 1; } protected int calculateInvocationsPerBatchJob(String batchType) { ProcessEngineConfigurationImpl engineConfig = commandContext.getProcessEngineConfiguration(); Map<String, Integer> invocationsPerBatchJobByBatchType = engineConfig.getInvocationsPerBatchJobByBatchType(); Integer invocationCount = invocationsPerBatchJobByBatchType.get(batchType); if (invocationCount != null) { return invocationCount; } else { return engineConfig.getInvocationsPerBatchJob(); } } }
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dataplex.v1.model; /** * A job represents an instance of a task. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Dataplex API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudDataplexV1Job extends com.google.api.client.json.GenericJson { /** * Output only. The time when the job ended. * The value may be {@code null}. */ @com.google.api.client.util.Key private String endTime; /** * Output only. Additional information about the current state. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String message; /** * Output only. The relative resource name of the job, of the form: * projects/{project_number}/locations/{location_id}/lakes/{lake_id}/ * tasks/{task_id}/jobs/{job_id}. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * Output only. . The number of times the job has been retried (excluding the initial attempt). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Long retryCount; /** * Output only. The underlying service running a job. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String service; /** * Output only. The full resource name for the job run under a particular service. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String serviceJob; /** * Output only. The time when the job was started. * The value may be {@code null}. */ @com.google.api.client.util.Key private String startTime; /** * Output only. Execution state for the job. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String state; /** * Output only. System generated globally unique ID for the job. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String uid; /** * Output only. The time when the job ended. * @return value or {@code null} for none */ public String getEndTime() { return endTime; } /** * Output only. The time when the job ended. * @param endTime endTime or {@code null} for none */ public GoogleCloudDataplexV1Job setEndTime(String endTime) { this.endTime = endTime; return this; } /** * Output only. Additional information about the current state. * @return value or {@code null} for none */ public java.lang.String getMessage() { return message; } /** * Output only. Additional information about the current state. * @param message message or {@code null} for none */ public GoogleCloudDataplexV1Job setMessage(java.lang.String message) { this.message = message; return this; } /** * Output only. The relative resource name of the job, of the form: * projects/{project_number}/locations/{location_id}/lakes/{lake_id}/ * tasks/{task_id}/jobs/{job_id}. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Output only. The relative resource name of the job, of the form: * projects/{project_number}/locations/{location_id}/lakes/{lake_id}/ * tasks/{task_id}/jobs/{job_id}. * @param name name or {@code null} for none */ public GoogleCloudDataplexV1Job setName(java.lang.String name) { this.name = name; return this; } /** * Output only. . The number of times the job has been retried (excluding the initial attempt). * @return value or {@code null} for none */ public java.lang.Long getRetryCount() { return retryCount; } /** * Output only. . The number of times the job has been retried (excluding the initial attempt). * @param retryCount retryCount or {@code null} for none */ public GoogleCloudDataplexV1Job setRetryCount(java.lang.Long retryCount) { this.retryCount = retryCount; return this; } /** * Output only. The underlying service running a job. * @return value or {@code null} for none */ public java.lang.String getService() { return service; } /** * Output only. The underlying service running a job. * @param service service or {@code null} for none */ public GoogleCloudDataplexV1Job setService(java.lang.String service) { this.service = service; return this; } /** * Output only. The full resource name for the job run under a particular service. * @return value or {@code null} for none */ public java.lang.String getServiceJob() { return serviceJob; } /** * Output only. The full resource name for the job run under a particular service. * @param serviceJob serviceJob or {@code null} for none */ public GoogleCloudDataplexV1Job setServiceJob(java.lang.String serviceJob) { this.serviceJob = serviceJob; return this; } /** * Output only. The time when the job was started. * @return value or {@code null} for none */ public String getStartTime() { return startTime; } /** * Output only. The time when the job was started. * @param startTime startTime or {@code null} for none */ public GoogleCloudDataplexV1Job setStartTime(String startTime) { this.startTime = startTime; return this; } /** * Output only. Execution state for the job. * @return value or {@code null} for none */ public java.lang.String getState() { return state; } /** * Output only. Execution state for the job. * @param state state or {@code null} for none */ public GoogleCloudDataplexV1Job setState(java.lang.String state) { this.state = state; return this; } /** * Output only. System generated globally unique ID for the job. * @return value or {@code null} for none */ public java.lang.String getUid() { return uid; } /** * Output only. System generated globally unique ID for the job. * @param uid uid or {@code null} for none */ public GoogleCloudDataplexV1Job setUid(java.lang.String uid) { this.uid = uid; return this; } @Override public GoogleCloudDataplexV1Job set(String fieldName, Object value) { return (GoogleCloudDataplexV1Job) super.set(fieldName, value); } @Override public GoogleCloudDataplexV1Job clone() { return (GoogleCloudDataplexV1Job) super.clone(); } }
package com.j256.ormlite.table; import com.j256.ormlite.BaseCoreTest; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.db.DatabaseType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.h2.H2DatabaseType; import com.j256.ormlite.jpa.PropertyConfig; import com.j256.ormlite.stmt.StatementBuilder.StatementType; import com.j256.ormlite.support.CompiledStatement; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.support.DatabaseConnection; import com.j256.ormlite.support.DatabaseResults; import org.easymock.EasyMock; import org.easymock.IAnswer; import org.junit.Test; import java.lang.reflect.Constructor; import java.sql.SQLException; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import static org.easymock.EasyMock.anyInt; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.isA; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; public class TableUtilsTest extends BaseCoreTest { @Test public void testConstructor() throws Exception { @SuppressWarnings("rawtypes") Constructor[] constructors = TableUtils.class.getDeclaredConstructors(); assertEquals(1, constructors.length); constructors[0].setAccessible(true); constructors[0].newInstance(); } @Test public void testCreateStatements() throws Exception { List<String> stmts = TableUtils.getCreateTableStatements(connectionSource, LocalFoo.class); assertEquals(1, stmts.size()); assertEquals(expectedCreateStatement(), stmts.get(0)); } @Test public void testCreateStatementsTableConfig() throws Exception { List<String> stmts = TableUtils.getCreateTableStatements(connectionSource, DatabaseTableConfig.fromClass(connectionSource, LocalFoo.class)); assertEquals(1, stmts.size()); assertEquals(expectedCreateStatement(), stmts.get(0)); } @Test public void testCreateTableQueriesAfter() throws Exception { final String queryAfter = "SELECT * from foo"; DatabaseType databaseType = new H2DatabaseType() { @Override public void appendColumnArg(String tableName, StringBuilder sb, PropertyConfig fieldType, List<String> additionalArgs, List<String> statementsBefore, List<String> statementsAfter, List<String> queriesAfter) throws SQLException { super.appendColumnArg(tableName, sb, fieldType, additionalArgs, statementsBefore, statementsAfter, queriesAfter); if (fieldType.getColumnName().equals(LocalFoo.ID_FIELD_NAME)) { queriesAfter.add(queryAfter); } } }; final ConnectionSource connectionSource = createMock(ConnectionSource.class); testCreate(connectionSource, databaseType, 0, false, queryAfter, new Callable<Integer>() { public Integer call() throws Exception { return TableUtils.createTable(connectionSource, LocalFoo.class); } }); } @Test(expected = SQLException.class) public void testCreateTableThrow() throws Exception { final ConnectionSource connectionSource = createMock(ConnectionSource.class); testCreate(connectionSource, databaseType, 1, true, null, new Callable<Integer>() { public Integer call() throws Exception { return TableUtils.createTable(connectionSource, LocalFoo.class); } }); } @Test(expected = SQLException.class) public void testCreateTableAboveZero() throws Exception { final ConnectionSource connectionSource = createMock(ConnectionSource.class); testCreate(connectionSource, databaseType, 1, false, null, new Callable<Integer>() { public Integer call() throws Exception { return TableUtils.createTable(connectionSource, LocalFoo.class); } }); } @Test(expected = SQLException.class) public void testCreateTableBelowZero() throws Exception { final ConnectionSource connectionSource = createMock(ConnectionSource.class); testCreate(connectionSource, databaseType, -1, false, null, new Callable<Integer>() { public Integer call() throws Exception { return TableUtils.createTable(connectionSource, LocalFoo.class); } }); } @Test public void testCreateTableTableConfig() throws Exception { final ConnectionSource connectionSource = createMock(ConnectionSource.class); testCreate(connectionSource, databaseType, 0, false, null, new Callable<Integer>() { public Integer call() throws Exception { return (int) TableUtils.createTable(connectionSource, DatabaseTableConfig.fromClass(connectionSource, LocalFoo.class)); } }); } @Test public void testDropTable() throws Exception { final ConnectionSource connectionSource = createMock(ConnectionSource.class); testDrop(connectionSource, 0, false, new Callable<Integer>() { public Integer call() throws Exception { return (int) TableUtils.dropTable(connectionSource, LocalFoo.class, false); } }); } @Test(expected = SQLException.class) public void testDropTableThrow() throws Exception { final ConnectionSource connectionSource = createMock(ConnectionSource.class); testDrop(connectionSource, 0, true, new Callable<Integer>() { public Integer call() throws Exception { return (int) TableUtils.dropTable(connectionSource, LocalFoo.class, false); } }); } @Test public void testDropTableThrowIgnore() throws Exception { final ConnectionSource connectionSource = createMock(ConnectionSource.class); testDrop(connectionSource, 0, true, new Callable<Integer>() { public Integer call() throws Exception { return (int) TableUtils.dropTable(connectionSource, LocalFoo.class, true); } }); } @Test(expected = SQLException.class) public void testDropTableNegRows() throws Exception { final ConnectionSource connectionSource = createMock(ConnectionSource.class); testDrop(connectionSource, -1, false, new Callable<Integer>() { public Integer call() throws Exception { return (int) TableUtils.dropTable(connectionSource, LocalFoo.class, false); } }); } @Test public void testDropTableTableConfig() throws Exception { final ConnectionSource connectionSource = createMock(ConnectionSource.class); testDrop(connectionSource, 0, false, new Callable<Integer>() { public Integer call() throws Exception { return (int) TableUtils.dropTable(connectionSource, DatabaseTableConfig.fromClass(connectionSource, LocalFoo.class), false); } }); } @Test public void testIndex() throws Exception { final ConnectionSource connectionSource = createMock(ConnectionSource.class); expect(connectionSource.getDatabaseType()).andReturn(databaseType).anyTimes(); DatabaseConnection conn = createMock(DatabaseConnection.class); expect(connectionSource.getReadWriteConnection()).andReturn(conn); final CompiledStatement stmt = createMock(CompiledStatement.class); expect(conn.compileStatement(isA(String.class), isA(StatementType.class), isA(PropertyConfig[].class), anyInt())).andAnswer( new IAnswer<CompiledStatement>() { private int stmtC = 0; public CompiledStatement answer() { Object[] args = EasyMock.getCurrentArguments(); assertNotNull(args); assertEquals(4, args.length); if (stmtC == 0) { assertEquals("CREATE TABLE `index` (`stuff` VARCHAR(255) ) ", args[0]); } else if (stmtC == 1) { assertEquals("CREATE INDEX `index_stuff_idx` ON `index` ( `stuff` )", args[0]); } else if (stmtC == 2) { assertEquals("DROP INDEX `index_stuff_idx`", args[0]); } else if (stmtC == 3) { assertEquals("DROP TABLE `index` ", args[0]); } else { fail("Should only be called 4 times"); } stmtC++; assertEquals(StatementType.EXECUTE, args[1]); assertEquals(0, ((PropertyConfig[]) args[2]).length); return stmt; } }) .anyTimes(); expect(stmt.runExecute()).andReturn(0).anyTimes(); connectionSource.releaseConnection(conn); expect(connectionSource.getReadWriteConnection()).andReturn(conn); connectionSource.releaseConnection(conn); expectLastCall().anyTimes(); stmt.close(); expectLastCall().anyTimes(); replay(connectionSource, conn, stmt); TableUtils.createTable(connectionSource, Index.class); TableUtils.dropTable(connectionSource, Index.class, true); verify(connectionSource, conn, stmt); } @Test public void testComboIndex() throws Exception { final ConnectionSource connectionSource = createMock(ConnectionSource.class); expect(connectionSource.getDatabaseType()).andReturn(databaseType).anyTimes(); DatabaseConnection conn = createMock(DatabaseConnection.class); expect(connectionSource.getReadWriteConnection()).andReturn(conn); final CompiledStatement stmt = createMock(CompiledStatement.class); expect(conn.compileStatement(isA(String.class), isA(StatementType.class), isA(PropertyConfig[].class), anyInt())).andAnswer( new IAnswer<CompiledStatement>() { private int stmtC = 0; public CompiledStatement answer() { Object[] args = EasyMock.getCurrentArguments(); assertNotNull(args); assertEquals(4, args.length); if (stmtC == 0) { assertEquals("CREATE TABLE `comboindex` (`stuff` VARCHAR(255) , `junk` BIGINT ) ", args[0]); } else if (stmtC == 1) { assertEquals("CREATE INDEX `" + ComboIndex.INDEX_NAME + "` ON `comboindex` ( `stuff`, `junk` )", args[0]); } else if (stmtC == 2) { assertEquals("DROP INDEX `" + ComboIndex.INDEX_NAME + "`", args[0]); } else if (stmtC == 3) { assertEquals("DROP TABLE `comboindex` ", args[0]); } else { fail("Should only be called 4 times"); } stmtC++; assertEquals(StatementType.EXECUTE, args[1]); assertEquals(0, ((PropertyConfig[]) args[2]).length); return stmt; } }) .anyTimes(); expect(stmt.runExecute()).andReturn(0).anyTimes(); connectionSource.releaseConnection(conn); expect(connectionSource.getReadWriteConnection()).andReturn(conn); connectionSource.releaseConnection(conn); expectLastCall().anyTimes(); stmt.close(); expectLastCall().anyTimes(); replay(connectionSource, conn, stmt); TableUtils.createTable(connectionSource, ComboIndex.class); TableUtils.dropTable(connectionSource, ComboIndex.class, false); verify(connectionSource, conn, stmt); } @Test public void testUniqueIndex() throws Exception { final ConnectionSource connectionSource = createMock(ConnectionSource.class); expect(connectionSource.getDatabaseType()).andReturn(databaseType).anyTimes(); DatabaseConnection conn = createMock(DatabaseConnection.class); expect(connectionSource.getReadWriteConnection()).andReturn(conn); final CompiledStatement stmt = createMock(CompiledStatement.class); expect(conn.compileStatement(isA(String.class), isA(StatementType.class), isA(PropertyConfig[].class), anyInt())).andAnswer( new IAnswer<CompiledStatement>() { private int stmtC = 0; public CompiledStatement answer() { Object[] args = EasyMock.getCurrentArguments(); assertNotNull(args); assertEquals(4, args.length); if (stmtC == 0) { assertEquals("CREATE TABLE `uniqueindex` (`stuff` VARCHAR(255) ) ", args[0]); } else if (stmtC == 1) { assertEquals("CREATE UNIQUE INDEX `uniqueindex_stuff_idx` ON `uniqueindex` ( `stuff` )", args[0]); } else if (stmtC == 2) { assertEquals("DROP INDEX `uniqueindex_stuff_idx`", args[0]); } else if (stmtC == 3) { assertEquals("DROP TABLE `uniqueindex` ", args[0]); } else { fail("Should only be called 4 times"); } stmtC++; assertEquals(StatementType.EXECUTE, args[1]); assertEquals(0, ((PropertyConfig[]) args[2]).length); return stmt; } }).anyTimes(); expect(stmt.runExecute()).andReturn(0).anyTimes(); connectionSource.releaseConnection(conn); expect(connectionSource.getReadWriteConnection()).andReturn(conn); connectionSource.releaseConnection(conn); expectLastCall().anyTimes(); stmt.close(); expectLastCall().anyTimes(); replay(connectionSource, conn, stmt); TableUtils.createTable(connectionSource, UniqueIndex.class); TableUtils.dropTable(connectionSource, UniqueIndex.class, false); verify(connectionSource, conn, stmt); } @Test public void testMissingCreate() throws Exception { Dao<LocalFoo, Integer> fooDao = createDao(LocalFoo.class, false); try { fooDao.queryForAll(); fail("Should have thrown"); } catch (SQLException e) { // expected } } @Test public void testCreateTable() throws Exception { Dao<LocalFoo, Integer> fooDao = createDao(LocalFoo.class, false); // first we create the table createTable(LocalFoo.class, false); // test it out assertEquals(0, fooDao.queryForAll().size()); // now we drop it dropTable(LocalFoo.class, true); try { fooDao.countOf(); fail("Was expecting a SQL exception"); } catch (Exception expected) { // expected } // now create it again createTable(LocalFoo.class, false); assertEquals(0, fooDao.queryForAll().size()); dropTable(LocalFoo.class, true); } @Test public void testDropThenQuery() throws Exception { Dao<LocalFoo, Integer> fooDao = createDao(LocalFoo.class, true); assertEquals(0, fooDao.queryForAll().size()); dropTable(LocalFoo.class, true); try { fooDao.queryForAll(); fail("Should have thrown"); } catch (SQLException e) { // expected } } @Test public void testRawExecuteDropThenQuery() throws Exception { Dao<LocalFoo, Integer> fooDao = createDao(LocalFoo.class, true); StringBuilder sb = new StringBuilder(); sb.append("DROP TABLE "); if (databaseType.isEntityNamesMustBeUpCase()) { databaseType.appendEscapedEntityName(sb, "LOCALFOO"); } else { databaseType.appendEscapedEntityName(sb, "LocalFoo"); } // can't check the return value because of sql-server fooDao.executeRaw(sb.toString()); try { fooDao.queryForAll(); fail("Should have thrown"); } catch (SQLException e) { // expected } } @Test public void testDoubleDrop() throws Exception { Dao<LocalFoo, Integer> fooDao = createDao(LocalFoo.class, false); // first we create the table createTable(LocalFoo.class, false); // test it out assertEquals(0, fooDao.queryForAll().size()); // now we drop it dropTable(LocalFoo.class, true); try { // this should fail dropTable(LocalFoo.class, false); fail("Should have thrown"); } catch (SQLException e) { // expected } } @Test public void testClearTable() throws Exception { Dao<LocalFoo, Integer> fooDao = createDao(LocalFoo.class, true); assertEquals(0, fooDao.countOf()); LocalFoo foo = new LocalFoo(); assertEquals(1, fooDao.create(foo)); assertEquals(1, fooDao.countOf()); TableUtils.clearTable(connectionSource, LocalFoo.class); assertEquals(0, fooDao.countOf()); } @Test public void testCreateTableIfNotExists() throws Exception { dropTable(LocalFoo.class, true); Dao<LocalFoo, Integer> fooDao = createDao(LocalFoo.class, false); try { fooDao.countOf(); fail("Should have thrown an exception"); } catch (Exception e) { // ignored } TableUtils.createTableIfNotExists(connectionSource, LocalFoo.class); assertEquals(0, fooDao.countOf()); // should not throw TableUtils.createTableIfNotExists(connectionSource, LocalFoo.class); assertEquals(0, fooDao.countOf()); } @Test public void testCreateTableConfigIfNotExists() throws Exception { dropTable(LocalFoo.class, true); Dao<LocalFoo, Integer> fooDao = createDao(LocalFoo.class, false); try { fooDao.countOf(); fail("Should have thrown an exception"); } catch (Exception e) { // ignored } DatabaseTableConfig<LocalFoo> tableConfig = DatabaseTableConfig.fromClass(connectionSource, LocalFoo.class); TableUtils.createTableIfNotExists(connectionSource, tableConfig); assertEquals(0, fooDao.countOf()); // should not throw TableUtils.createTableIfNotExists(connectionSource, tableConfig); assertEquals(0, fooDao.countOf()); } /* ================================================================ */ private void testCreate(ConnectionSource connectionSource, DatabaseType databaseType, int rowN, boolean throwExecute, String queryAfter, Callable<Integer> callable) throws Exception { testStatement(connectionSource, databaseType, expectedCreateStatement(), queryAfter, rowN, throwExecute, callable); } private String expectedCreateStatement() { StringBuilder sb = new StringBuilder(); sb.append("CREATE TABLE "); databaseType.appendEscapedEntityName(sb, "localfoo"); sb.append(" ("); databaseType.appendEscapedEntityName(sb, LocalFoo.ID_FIELD_NAME); sb.append(" INTEGER , "); databaseType.appendEscapedEntityName(sb, LocalFoo.NAME_FIELD_NAME); sb.append(" VARCHAR(255) ) "); return sb.toString(); } private void testDrop(ConnectionSource connectionSource, int rowN, boolean throwExecute, Callable<Integer> callable) throws Exception { StringBuilder sb = new StringBuilder(); sb.append("DROP TABLE "); databaseType.appendEscapedEntityName(sb, "foo"); sb.append(' '); testStatement(connectionSource, databaseType, sb.toString(), null, rowN, throwExecute, callable); } private void testStatement(ConnectionSource connectionSource, DatabaseType databaseType, String statement, String queryAfter, int rowN, boolean throwExecute, Callable<Integer> callable) throws Exception { DatabaseConnection conn = createMock(DatabaseConnection.class); CompiledStatement stmt = createMock(CompiledStatement.class); DatabaseResults results = null; final AtomicInteger rowC = new AtomicInteger(1); if (throwExecute) { expect(conn.compileStatement(isA(String.class), isA(StatementType.class), isA(PropertyConfig[].class), anyInt())).andThrow( new SQLException("you asked us to!!")); } else { expect(conn.compileStatement(isA(String.class), isA(StatementType.class), isA(PropertyConfig[].class), anyInt())).andReturn( stmt); expect(stmt.runExecute()).andReturn(rowN); stmt.close(); if (queryAfter != null) { expect( conn.compileStatement(isA(String.class), isA(StatementType.class), isA(PropertyConfig[].class), anyInt())).andReturn(stmt); results = createMock(DatabaseResults.class); expect(results.first()).andReturn(false); expect(stmt.runQuery(null)).andReturn(results); stmt.close(); replay(results); rowC.incrementAndGet(); } } expect(connectionSource.getDatabaseType()).andReturn(databaseType).anyTimes(); expect(connectionSource.getReadWriteConnection()).andReturn(conn); connectionSource.releaseConnection(conn); replay(connectionSource, conn, stmt); // we have to store the value since we count the number of rows in the rowC while call() is happening assertEquals((Integer) rowC.get(), callable.call()); verify(connectionSource, conn, stmt); if (queryAfter != null) { verify(results); } } protected static class LocalFoo { public static final String ID_FIELD_NAME = "id"; public static final String NAME_FIELD_NAME = "name"; @DatabaseField(columnName = ID_FIELD_NAME) int id; @DatabaseField(columnName = NAME_FIELD_NAME) String name; } protected static class Index { @DatabaseField(index = true) String stuff; public Index() { } } protected static class ComboIndex { @DatabaseField(indexName = INDEX_NAME) String stuff; @DatabaseField(indexName = INDEX_NAME) long junk; public ComboIndex() { } public static final String INDEX_NAME = "stuffjunk"; } protected static class UniqueIndex { @DatabaseField(uniqueIndex = true) String stuff; public UniqueIndex() { } } }
package io.github.cloudiator.rest.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.github.cloudiator.rest.model.Api; import io.github.cloudiator.rest.model.CloudCredential; import io.github.cloudiator.rest.model.NewPlatform; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.*; /** * Representation of a platform used by Cloudiator */ @ApiModel(description = "Representation of a platform used by Cloudiator") @Validated public class Platform { @JsonProperty("name") private String name = null; /** * PaaS stack type */ public enum TypeEnum { HEROKU("HEROKU"), OPENSHIFT("OPENSHIFT"), CLOUDFOUNDRY("CLOUDFOUNDRY"); private String value; TypeEnum(String value) { this.value = value; } @Override @JsonValue public String toString() { return String.valueOf(value); } @JsonCreator public static TypeEnum fromValue(String text) { for (TypeEnum b : TypeEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } } @JsonProperty("type") private TypeEnum type = null; @JsonProperty("api") private Api api = null; @JsonProperty("credential") private CloudCredential credential = null; @JsonProperty("endpoint") private String endpoint = null; @JsonProperty("id") private String id = null; public Platform name(String name) { this.name = name; return this; } /** * Human-readable name * @return name **/ @ApiModelProperty(required = true, value = "Human-readable name") @NotNull public String getName() { return name; } public void setName(String name) { this.name = name; } public Platform type(TypeEnum type) { this.type = type; return this; } /** * PaaS stack type * @return type **/ @ApiModelProperty(value = "PaaS stack type") public TypeEnum getType() { return type; } public void setType(TypeEnum type) { this.type = type; } public Platform api(Api api) { this.api = api; return this; } /** * Get api * @return api **/ @ApiModelProperty(required = true, value = "") @NotNull @Valid public Api getApi() { return api; } public void setApi(Api api) { this.api = api; } public Platform credential(CloudCredential credential) { this.credential = credential; return this; } /** * Get credential * @return credential **/ @ApiModelProperty(required = true, value = "") @NotNull @Valid public CloudCredential getCredential() { return credential; } public void setCredential(CloudCredential credential) { this.credential = credential; } public Platform endpoint(String endpoint) { this.endpoint = endpoint; return this; } /** * URI where the api of this platform provider can be accessed. * @return endpoint **/ @ApiModelProperty(example = "https://endpoint.example.com", value = "URI where the api of this platform provider can be accessed.") public String getEndpoint() { return endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } public Platform id(String id) { this.id = id; return this; } /** * Unique identifier for the platform * @return id **/ @ApiModelProperty(value = "Unique identifier for the platform") public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Platform platform = (Platform) o; return Objects.equals(this.name, platform.name) && Objects.equals(this.type, platform.type) && Objects.equals(this.api, platform.api) && Objects.equals(this.credential, platform.credential) && Objects.equals(this.endpoint, platform.endpoint) && Objects.equals(this.id, platform.id); } @Override public int hashCode() { return Objects.hash(name, type, api, credential, endpoint, id); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Platform {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" api: ").append(toIndentedString(api)).append("\n"); sb.append(" credential: ").append(toIndentedString(credential)).append("\n"); sb.append(" endpoint: ").append(toIndentedString(endpoint)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package com.knetikcloud.api; import com.knetikcloud.client.ApiException; import com.knetikcloud.client.ApiClient; import com.knetikcloud.client.Configuration; import com.knetikcloud.client.Pair; import javax.ws.rs.core.GenericType; import com.knetikcloud.model.PageResourceSavedAddressResource; import com.knetikcloud.model.Result; import com.knetikcloud.model.SavedAddressResource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-03-14T12:03:43.231-04:00") public class UsersAddressesApi { private ApiClient apiClient; public UsersAddressesApi() { this(Configuration.getDefaultApiClient()); } public UsersAddressesApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Create a new address * &lt;b&gt;Permissions Needed:&lt;/b&gt; USERS_ADMIN or owner * @param userId The id of the user (required) * @param savedAddressResource The new address (optional) * @return SavedAddressResource * @throws ApiException if fails to make API call */ public SavedAddressResource createAddress(String userId, SavedAddressResource savedAddressResource) throws ApiException { Object localVarPostBody = savedAddressResource; // verify the required parameter 'userId' is set if (userId == null) { throw new ApiException(400, "Missing the required parameter 'userId' when calling createAddress"); } // create path and map variables String localVarPath = "/users/{user_id}/addresses" .replaceAll("\\{" + "user_id" + "\\}", apiClient.escapeString(userId.toString())); // query params List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[] { "oauth2_client_credentials_grant", "oauth2_password_grant" }; GenericType<SavedAddressResource> localVarReturnType = new GenericType<SavedAddressResource>() {}; return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } /** * Delete an address * &lt;b&gt;Permissions Needed:&lt;/b&gt; USERS_ADMIN or owner * @param userId The id of the user (required) * @param id The id of the address (required) * @throws ApiException if fails to make API call */ public void deleteAddress(String userId, Integer id) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'userId' is set if (userId == null) { throw new ApiException(400, "Missing the required parameter 'userId' when calling deleteAddress"); } // verify the required parameter 'id' is set if (id == null) { throw new ApiException(400, "Missing the required parameter 'id' when calling deleteAddress"); } // create path and map variables String localVarPath = "/users/{user_id}/addresses/{id}" .replaceAll("\\{" + "user_id" + "\\}", apiClient.escapeString(userId.toString())) .replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString())); // query params List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[] { "oauth2_client_credentials_grant", "oauth2_password_grant" }; apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); } /** * Get a single address * &lt;b&gt;Permissions Needed:&lt;/b&gt; USERS_ADMIN or owner * @param userId The id of the user (required) * @param id The id of the address (required) * @return SavedAddressResource * @throws ApiException if fails to make API call */ public SavedAddressResource getAddress(String userId, Integer id) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'userId' is set if (userId == null) { throw new ApiException(400, "Missing the required parameter 'userId' when calling getAddress"); } // verify the required parameter 'id' is set if (id == null) { throw new ApiException(400, "Missing the required parameter 'id' when calling getAddress"); } // create path and map variables String localVarPath = "/users/{user_id}/addresses/{id}" .replaceAll("\\{" + "user_id" + "\\}", apiClient.escapeString(userId.toString())) .replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString())); // query params List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[] { "oauth2_client_credentials_grant", "oauth2_password_grant" }; GenericType<SavedAddressResource> localVarReturnType = new GenericType<SavedAddressResource>() {}; return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } /** * List and search addresses * &lt;b&gt;Permissions Needed:&lt;/b&gt; USERS_ADMIN or owner * @param userId The id of the user (required) * @param size The number of objects returned per page (optional, default to 25) * @param page The number of the page returned, starting with 1 (optional, default to 1) * @param order A comma separated list of sorting requirements in priority order, each entry matching PROPERTY_NAME:[ASC|DESC] (optional, default to id:ASC) * @return PageResourceSavedAddressResource * @throws ApiException if fails to make API call */ public PageResourceSavedAddressResource getAddresses(String userId, Integer size, Integer page, String order) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'userId' is set if (userId == null) { throw new ApiException(400, "Missing the required parameter 'userId' when calling getAddresses"); } // create path and map variables String localVarPath = "/users/{user_id}/addresses" .replaceAll("\\{" + "user_id" + "\\}", apiClient.escapeString(userId.toString())); // query params List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); localVarQueryParams.addAll(apiClient.parameterToPairs("", "size", size)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "page", page)); localVarQueryParams.addAll(apiClient.parameterToPairs("", "order", order)); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[] { "oauth2_client_credentials_grant", "oauth2_password_grant" }; GenericType<PageResourceSavedAddressResource> localVarReturnType = new GenericType<PageResourceSavedAddressResource>() {}; return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } /** * Update an address * &lt;b&gt;Permissions Needed:&lt;/b&gt; USERS_ADMIN or owner * @param userId The id of the user (required) * @param id The id of the address (required) * @param savedAddressResource The saved address resource object (optional) * @return SavedAddressResource * @throws ApiException if fails to make API call */ public SavedAddressResource updateAddress(String userId, Integer id, SavedAddressResource savedAddressResource) throws ApiException { Object localVarPostBody = savedAddressResource; // verify the required parameter 'userId' is set if (userId == null) { throw new ApiException(400, "Missing the required parameter 'userId' when calling updateAddress"); } // verify the required parameter 'id' is set if (id == null) { throw new ApiException(400, "Missing the required parameter 'id' when calling updateAddress"); } // create path and map variables String localVarPath = "/users/{user_id}/addresses/{id}" .replaceAll("\\{" + "user_id" + "\\}", apiClient.escapeString(userId.toString())) .replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString())); // query params List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[] { "oauth2_client_credentials_grant", "oauth2_password_grant" }; GenericType<SavedAddressResource> localVarReturnType = new GenericType<SavedAddressResource>() {}; return apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } }
/* * Copyright 2017 Farbod Salamat-Zadeh * * 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 co.timetableapp.ui.base; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import co.timetableapp.R; import co.timetableapp.ui.agenda.AgendaActivity; import co.timetableapp.ui.classes.ClassesActivity; import co.timetableapp.ui.home.MainActivity; import co.timetableapp.ui.schedule.ScheduleActivity; import co.timetableapp.ui.settings.SettingsActivity; import co.timetableapp.ui.subjects.SubjectsActivity; import co.timetableapp.ui.timetables.TimetablesActivity; /** * An activity used for the navigation drawer implementation. * * This should be implemented by activities which contain a navigation drawer. */ public abstract class NavigationDrawerActivity extends AppCompatActivity { protected static final int NAVDRAWER_ITEM_HOME = R.id.navigation_item_home; protected static final int NAVDRAWER_ITEM_SCHEDULE = R.id.navigation_item_schedule; protected static final int NAVDRAWER_ITEM_AGENDA = R.id.navigation_item_agenda; protected static final int NAVDRAWER_ITEM_CLASSES = R.id.navigation_item_classes; protected static final int NAVDRAWER_ITEM_SUBJECTS = R.id.navigation_item_subjects; protected static final int NAVDRAWER_ITEM_MANAGE_TIMETABLES = R.id.navigation_item_manage_timetables; protected static final int NAVDRAWER_ITEM_SETTINGS = R.id.navigation_item_settings; protected static final int NAVDRAWER_ITEM_INVALID = -1; private static final int NAVDRAWER_LAUNCH_DELAY = 250; private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mDrawerToggle; private NavigationView mNavigationView; @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mDrawerLayout = getSelfDrawerLayout(); if (mDrawerLayout == null) { return; } setupLayout(); } /** * This method should be overridden in subclasses of NavigationDrawerActivity to use the Toolbar * Return null if there is no Toolbar */ protected Toolbar getSelfToolbar() { return null; } /** * This method should be overridden in subclasses of NavigationDrawerActivity to use the DrawerLayout * Return null if there is no DrawerLayout */ protected DrawerLayout getSelfDrawerLayout() { return null; } /** * Returns the navigation drawer item that corresponds to this Activity. Subclasses * of NavigationDrawerActivity override this to indicate what nav drawer item corresponds to them * Return NAVDRAWER_ITEM_INVALID to mean that this Activity should not have a Nav Drawer. */ protected int getSelfNavDrawerItem() { return NAVDRAWER_ITEM_INVALID; } /** * Returns the NavigationView that corresponds to this Activity. Subclasses * of NavigationDrawerActivity override this to indicate what nav drawer item corresponds to them * Return null to mean that this Activity should not have a Nav Drawer. */ protected NavigationView getSelfNavigationView() { return null; } private void setupLayout() { Toolbar toolbar = getSelfToolbar(); if (toolbar != null) { setSupportActionBar(toolbar); } mNavigationView = getSelfNavigationView(); if (mNavigationView == null) { return; } mNavigationView.getMenu().findItem(getSelfNavDrawerItem()).setChecked(true); mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { handleNavigationSelection(menuItem); return true; } }); mDrawerToggle = new ActionBarDrawerToggle( this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close); mDrawerLayout.addDrawerListener(mDrawerToggle); mDrawerToggle.syncState(); } private void handleNavigationSelection(final MenuItem menuItem) { if (menuItem.getItemId() == getSelfNavDrawerItem()) { mDrawerLayout.closeDrawers(); return; } // Launch the target Activity after a short delay, to allow the close animation to play Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { goToNavDrawerItem(menuItem.getItemId()); } }, NAVDRAWER_LAUNCH_DELAY); if (menuItem.isCheckable()) { mNavigationView.getMenu().findItem(getSelfNavDrawerItem()).setChecked(false); menuItem.setChecked(true); } mDrawerLayout.closeDrawers(); } private void goToNavDrawerItem(int menuItem) { Intent intent = null; switch (menuItem) { case NAVDRAWER_ITEM_HOME: intent = new Intent(this, MainActivity.class); break; case NAVDRAWER_ITEM_SCHEDULE: intent = new Intent(this, ScheduleActivity.class); break; case NAVDRAWER_ITEM_AGENDA: intent = new Intent(this, AgendaActivity.class); break; case NAVDRAWER_ITEM_CLASSES: intent = new Intent(this, ClassesActivity.class); break; case NAVDRAWER_ITEM_SUBJECTS: intent = new Intent(this, SubjectsActivity.class); break; case NAVDRAWER_ITEM_MANAGE_TIMETABLES: intent = new Intent(this, TimetablesActivity.class); break; case NAVDRAWER_ITEM_SETTINGS: intent = new Intent(this, SettingsActivity.class); break; } if (intent == null) { return; } startActivity(intent); overridePendingTransition(0, 0); finish(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggle mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) { mDrawerLayout.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } }
/** * * Copyright 2011 (C) Rainer Schneider,Roggenburg <schnurlei@googlemail.com> * * 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 de.jdynameta.dbaccess.jdbc.connection; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringReader; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; import java.util.Date; import de.jdynameta.base.metainfo.primitive.BlobByteArrayHolder; import de.jdynameta.base.metainfo.primitive.BlobType; import de.jdynameta.base.metainfo.primitive.BooleanType; import de.jdynameta.base.metainfo.primitive.CurrencyType; import de.jdynameta.base.metainfo.primitive.FloatType; import de.jdynameta.base.metainfo.primitive.LongType; import de.jdynameta.base.metainfo.primitive.PrimitiveTypeVisitor; import de.jdynameta.base.metainfo.primitive.TextType; import de.jdynameta.base.metainfo.primitive.TimeStampType; import de.jdynameta.base.metainfo.primitive.VarCharType; import de.jdynameta.base.value.JdyPersistentException; /** * @author Rainer * * @version 17.07.2002 */ public class PreparedStatementWriter implements PrimitiveTypeVisitor { private final PreparedStatement preparedStatement; protected int index; /** * Constructor for PreparedStatementWriter. * @param aPreparedStatement * @param aStartIndex */ public PreparedStatementWriter(PreparedStatement aPreparedStatement, int aStartIndex) { super(); this.preparedStatement = aPreparedStatement; this.index = aStartIndex; } @Override public void handleValue(Long aValue, LongType aType) throws JdyPersistentException { try { if (aValue != null) { if (aValue.intValue() < Integer.MAX_VALUE) { preparedStatement.setInt(index, aValue.intValue()); } else { preparedStatement.setLong(index, aValue); } } else { preparedStatement.setNull(index, Types.INTEGER); } index++; } catch (SQLException excp) { throw new JdyPersistentException(excp); } } @Override public void handleValue(BigDecimal aValue, CurrencyType aType) throws JdyPersistentException { try { if (aValue != null) { preparedStatement.setBigDecimal(index, aValue); } else { preparedStatement.setNull(index, Types.NUMERIC); } index++; } catch (SQLException excp) { throw new JdyPersistentException(excp); } } @Override public void handleValue(Boolean aValue, BooleanType aType) throws JdyPersistentException { try { if (aValue != null) { preparedStatement.setBoolean(index, aValue); } else { preparedStatement.setNull(index, Types.BOOLEAN); } index++; } catch (SQLException excp) { throw new JdyPersistentException(excp); } } @Override public void handleValue(Double aValue, FloatType aType) throws JdyPersistentException { try { if (aValue != null) { preparedStatement.setDouble(index, aValue); } else { preparedStatement.setNull(index, Types.DOUBLE); } index++; } catch (SQLException excp) { throw new JdyPersistentException(excp); } } @Override public void handleValue(String aValue, VarCharType aType) throws JdyPersistentException { if (aType.isClob()) { try { if (aValue != null) { byte[] bytesToInsert = aValue.getBytes(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytesToInsert); preparedStatement.setBinaryStream(index, bIn, bytesToInsert.length); } else { preparedStatement.setNull(index, Types.CLOB); } index++; } catch (SQLException excp) { throw new JdyPersistentException(excp); } } else { try { if (aValue != null) { if (aValue.length() > 0) { StringBuilder resultBuffer = new StringBuilder(aValue.length() + aValue.length() / 20); try { // replace \n with \r\n BufferedReader bufReader = new BufferedReader(new StringReader(aValue)); String curLine = bufReader.readLine(); while (curLine != null) { resultBuffer.append(curLine); curLine = bufReader.readLine(); if (curLine != null || aValue.endsWith("\n")) { resultBuffer.append("\r\n"); } } } catch (IOException ioExcp) { ioExcp.printStackTrace(); } aValue = resultBuffer.toString(); preparedStatement.setCharacterStream(index, new StringReader(aValue)); } else // bugfix for Access setAsciiStream don't work with "" { preparedStatement.setString(index, aValue); } } else { preparedStatement.setNull(index, Types.VARCHAR); } index++; } catch (SQLException excp) { throw new JdyPersistentException(excp); } } } @Override public void handleValue(Date aValue, TimeStampType aType) throws JdyPersistentException { try { if (aValue != null) { if (aType.isDatePartUsed() && !aType.isTimePartUsed()) { preparedStatement.setDate(index, new java.sql.Date(aValue.getTime())); } else if (!aType.isDatePartUsed() && aType.isTimePartUsed()) { preparedStatement.setTimestamp(index, new java.sql.Timestamp(aValue.getTime())); } else { preparedStatement.setTimestamp(index, new java.sql.Timestamp(aValue.getTime())); } } else { if (aType.isDatePartUsed() && !aType.isTimePartUsed()) { preparedStatement.setNull(index, Types.DATE); } else if (!aType.isDatePartUsed() && aType.isTimePartUsed()) { preparedStatement.setNull(index, Types.TIME); } else { preparedStatement.setNull(index, Types.TIMESTAMP); } } index++; } catch (SQLException excp) { throw new JdyPersistentException(excp); } } @Override public void handleValue(String aValue, TextType aType) throws JdyPersistentException { try { if (aValue != null) { preparedStatement.setString(index, aValue.trim()); // preparedStatement.setString(index, aOperator.prepareSqlValue(aValue.trim())); } else { preparedStatement.setNull(index, Types.CHAR); } index++; } catch (SQLException excp) { throw new JdyPersistentException(excp); } } @Override public void handleValue(BlobByteArrayHolder aValue, BlobType aType) throws JdyPersistentException { try { if (aValue != null) { byte[] bytesToInsert = aValue.getBytes(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytesToInsert); preparedStatement.setBinaryStream(index, bIn, bytesToInsert.length); } else { preparedStatement.setNull(index, Types.BLOB); } index++; } catch (SQLException excp) { throw new JdyPersistentException(excp); } } /** * Returns the index. * * @return int */ public int getIndex() { return index; } /** * Sets the index. * * @param aIndex */ public void setIndex(int aIndex) { this.index = aIndex; } protected final PreparedStatement getPreparedStatement() { return this.preparedStatement; } }
/* * 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.pig.impl.util; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; import java.util.Properties; import org.apache.hadoop.conf.Configuration; public class UDFContext { private Configuration jconf = null; private HashMap<UDFContextKey, Properties> udfConfs; private Properties clientSysProps; private static final String CLIENT_SYS_PROPS = "pig.client.sys.props"; private static final String UDF_CONTEXT = "pig.udf.context"; private static ThreadLocal<UDFContext> tss = new ThreadLocal<UDFContext>(); private UDFContext() { udfConfs = new HashMap<UDFContextKey, Properties>(); } public static UDFContext getUDFContext() { if (tss.get() == null) { UDFContext ctx = new UDFContext(); tss.set(ctx); } return tss.get(); } // internal pig use only - should NOT be called from user code public void setClientSystemProps() { clientSysProps = System.getProperties(); } /** * Get the System Properties (Read only) as on the client machine from where Pig * was launched. This will include command line properties passed at launch * time * @return client side System Properties including command line properties */ public Properties getClientSystemProps() { return clientSysProps; } /** * Adds the JobConf to this singleton. Will be * called on the backend by the Map and Reduce * functions so that UDFs can obtain the JobConf * on the backend. */ public void addJobConf(Configuration conf) { jconf = conf; } /** * Get the JobConf. This should only be called on * the backend. It will return null on the frontend. * @return JobConf for this job. This is a copy of the * JobConf. Nothing written here will be kept by the system. * getUDFConf should be used for recording UDF specific * information. */ public Configuration getJobConf() { if (jconf != null) return new Configuration(jconf); else return null; } /** * Get a properties object that is specific to this UDF. * Note that if a given UDF is called multiple times in a script, * and each instance passes different arguments, then each will * be provided with different configuration object. * This can be used by loaders to pass their input object path * or URI and separate themselves from other instances of the * same loader. Constructor arguments could also be used, * as they are available on both the front and back end. * * Note that this can only be used to share information * across instantiations of the same function in the front end * and between front end and back end. It cannot be used to * share information between instantiations (that is, between * map and/or reduce instances) on the back end at runtime. * @param c of the UDF obtaining the properties object. * @param args String arguments that make this instance of * the UDF unique. * @return A reference to the properties object specific to * the calling UDF. This is a reference, not a copy. * Any changes to this object will automatically be * propogated to other instances of the UDF calling this * function. */ @SuppressWarnings("rawtypes") public Properties getUDFProperties(Class c, String[] args) { UDFContextKey k = generateKey(c, args); Properties p = udfConfs.get(k); if (p == null) { p = new Properties(); udfConfs.put(k, p); } return p; } /** * Get a properties object that is specific to this UDF. * Note that if a given UDF is called multiple times in a script, * they will all be provided the same configuration object. It * is up to the UDF to make sure the multiple instances do not * stomp on each other. * * It is guaranteed that this properties object will be separate * from that provided to any other UDF. * * Note that this can only be used to share information * across instantiations of the same function in the front end * and between front end and back end. It cannot be used to * share information between instantiations (that is, between * map and/or reduce instances) on the back end at runtime. * @param c of the UDF obtaining the properties object. * @return A reference to the properties object specific to * the calling UDF. This is a reference, not a copy. * Any changes to this object will automatically be * propogated to other instances of the UDF calling this * function. */ @SuppressWarnings("rawtypes") public Properties getUDFProperties(Class c) { UDFContextKey k = generateKey(c, null); Properties p = udfConfs.get(k); if (p == null) { p = new Properties(); udfConfs.put(k, p); } return p; } /** * Serialize the UDF specific information into an instance * of JobConf. This function is intended to be called on * the front end in preparation for sending the data to the * backend. * @param conf JobConf to serialize into * @throws IOException if underlying serialization throws it */ public void serialize(Configuration conf) throws IOException { conf.set(UDF_CONTEXT, ObjectSerializer.serialize(udfConfs)); conf.set(CLIENT_SYS_PROPS, ObjectSerializer.serialize(clientSysProps)); } /** * Populate the udfConfs field. This function is intended to * be called by Map.configure or Reduce.configure on the backend. * It assumes that addJobConf has already been called. * @throws IOException if underlying deseralization throws it */ @SuppressWarnings("unchecked") public void deserialize() throws IOException { udfConfs = (HashMap<UDFContextKey, Properties>)ObjectSerializer.deserialize(jconf.get(UDF_CONTEXT)); clientSysProps = (Properties)ObjectSerializer.deserialize( jconf.get(CLIENT_SYS_PROPS)); } private UDFContextKey generateKey(Class<?> c, String[] args) { return new UDFContextKey(c.getName(), args); } public void reset() { udfConfs.clear(); } public boolean isUDFConfEmpty() { return udfConfs.isEmpty(); } /** * Class that acts as key for hashmap in UDFContext, * it holds the class and args of the udf, and * implements equals() and hashCode() */ private static class UDFContextKey implements Serializable{ private static final long serialVersionUID = 1; private String className; private String[] args; UDFContextKey(){ } UDFContextKey(String className, String [] args){ this.className = className; this.args = args; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(args); result = prime * result + ((className == null) ? 0 : className.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; UDFContextKey other = (UDFContextKey) obj; if (!Arrays.equals(args, other.args)) return false; if (className == null) { if (other.className != null) return false; } else if (!className.equals(other.className)) return false; return true; } } }
/* * Copyright 2006-2021 Prowide * * 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.prowidesoftware.swift.model.field; import com.prowidesoftware.swift.model.Tag; import com.prowidesoftware.Generated; import com.prowidesoftware.deprecation.ProwideDeprecated; import com.prowidesoftware.deprecation.TargetYear; import java.io.Serializable; import java.util.Locale; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import com.prowidesoftware.swift.model.BIC; import com.prowidesoftware.swift.model.field.MultiLineField; import com.prowidesoftware.swift.model.field.BICContainer; import com.prowidesoftware.swift.model.field.BICResolver; import org.apache.commons.lang3.StringUtils; import com.prowidesoftware.swift.model.field.SwiftParseUtils; import com.prowidesoftware.swift.model.field.Field; import com.prowidesoftware.swift.model.*; import com.prowidesoftware.swift.utils.SwiftFormatUtils; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * SWIFT MT Field 87A. * <p> * Model and parser for field 87A of a SWIFT MT message. * * <p>Subfields (components) Data types * <ol> * <li><code>String</code></li> * <li><code>String</code></li> * <li><code>BIC</code></li> * </ol> * * <p>Structure definition * <ul> * <li>validation pattern: <code>[[/&lt;DC&gt;][/34x]$]&lt;BIC&gt;</code></li> * <li>parser pattern: <code>[[/c][/S]$]S</code></li> * <li>components pattern: <code>SSB</code></li> * </ul> * * <p> * This class complies with standard release <strong>SRU2021</strong> */ @SuppressWarnings("unused") @Generated public class Field87A extends OptionAPartyField implements Serializable, BICContainer, MultiLineField { /** * Constant identifying the SRU to which this class belongs to. */ public static final int SRU = 2021; private static final long serialVersionUID = 1L; /** * Constant with the field name 87A. */ public static final String NAME = "87A"; /** * Same as NAME, intended to be clear when using static imports. */ public static final String F_87A = "87A"; /** * Default constructor. Creates a new field setting all components to null. */ public Field87A() { super(); } /** * Creates a new field and initializes its components with content from the parameter value. * @param value complete field value including separators and CRLF */ public Field87A(final String value) { super(value); } /** * Creates a new field and initializes its components with content from the parameter tag. * The value is parsed with {@link #parse(String)} * @throws IllegalArgumentException if the parameter tag is null or its tagname does not match the field name * @since 7.8 */ public Field87A(final Tag tag) { this(); if (tag == null) { throw new IllegalArgumentException("tag cannot be null."); } if (!StringUtils.equals(tag.getName(), "87A")) { throw new IllegalArgumentException("cannot create field 87A from tag "+tag.getName()+", tagname must match the name of the field."); } parse(tag.getValue()); } /** * Copy constructor. * Initializes the components list with a deep copy of the source components list. * @param source a field instance to copy * @since 7.7 */ public static Field87A newInstance(Field87A source) { Field87A cp = new Field87A(); cp.setComponents(new ArrayList<>(source.getComponents())); return cp; } /** * Create a Tag with this field name and the given value. * Shorthand for <code>new Tag(NAME, value)</code> * @see #NAME * @since 7.5 */ public static Tag tag(final String value) { return new Tag(NAME, value); } /** * Create a Tag with this field name and an empty string as value. * Shorthand for <code>new Tag(NAME, "")</code> * @see #NAME * @since 7.5 */ public static Tag emptyTag() { return new Tag(NAME, ""); } /** * Returns the field validator pattern. */ @Override public final String validatorPattern() { return "[[/<DC>][/34x]$]<BIC>"; } /** * Set the component 1 (D/C Mark). * * @param component1 the D/C Mark to set * @return the field object to enable build pattern */ public Field87A setComponent1(String component1) { setComponent(1, component1); return this; } /** * Set the D/C Mark (component 1). * * @param component1 the D/C Mark to set * @return the field object to enable build pattern */ public Field87A setDCMark(String component1) { return setComponent1(component1); } /** * Set the component 2 (Account). * * @param component2 the Account to set * @return the field object to enable build pattern */ public Field87A setComponent2(String component2) { setComponent(2, component2); return this; } /** * Set the Account (component 2). * * @param component2 the Account to set * @return the field object to enable build pattern */ public Field87A setAccount(String component2) { return setComponent2(component2); } /** * Set the component 3 (Identifier Code). * * @param component3 the Identifier Code to set * @return the field object to enable build pattern */ public Field87A setComponent3(String component3) { setComponent(3, component3); return this; } /** * Set the component3 from a BIC object. * * @param component3 the BIC with the Identifier Code content to set * @return the field object to enable build pattern */ public Field87A setComponent3(com.prowidesoftware.swift.model.BIC component3) { setComponent(3, SwiftFormatUtils.getBIC(component3)); return this; } /** * Set the Identifier Code (component 3). * * @param component3 the Identifier Code to set * @return the field object to enable build pattern */ public Field87A setIdentifierCode(String component3) { return setComponent3(component3); } /** * Set the Identifier Code (component 3) from a BIC object. * * @see #setComponent3(com.prowidesoftware.swift.model.BIC) * * @param component3 BIC with the Identifier Code content to set * @return the field object to enable build pattern */ public Field87A setIdentifierCode(com.prowidesoftware.swift.model.BIC component3) { return setComponent3(component3); } /** * Alternative <em>DEPRECATED</em> method setter for field's Identifier Code * * @see #setIdentifierCode(String) * * @param component3 the Identifier Code to set * @return the field object to enable build pattern */ @Deprecated @ProwideDeprecated(phase2 = TargetYear.SRU2022) public Field87A setBIC(String component3) { return setIdentifierCode(component3); } /** * Alternative <em>DEPRECATED</em> method setter for field's Identifier Code from a BIC object. * * @see #setComponent3(com.prowidesoftware.swift.model.BIC) * * @param component3 BIC with the Identifier Code content to set * @return the field object to enable build pattern */ @Deprecated @ProwideDeprecated(phase2 = TargetYear.SRU2022) public Field87A setBIC(com.prowidesoftware.swift.model.BIC component3) { return setIdentifierCode(component3); } public List<BIC> bics() { return BICResolver.bics(this); } public List<String> bicStrings () { return BICResolver.bicStrings(this); } /** * Returns the field's name composed by the field number and the letter option (if any). * @return the static value of Field87A.NAME */ @Override public String getName() { return NAME; } /** * Gets the first occurrence form the tag list or null if not found. * @return null if not found o block is null or empty * @param block may be null or empty */ public static Field87A get(final SwiftTagListBlock block) { if (block == null || block.isEmpty()) { return null; } final Tag t = block.getTagByName(NAME); if (t == null) { return null; } return new Field87A(t); } /** * Gets the first instance of Field87A in the given message. * @param msg may be empty or null * @return null if not found or msg is empty or null * @see #get(SwiftTagListBlock) */ public static Field87A get(final SwiftMessage msg) { if (msg == null || msg.getBlock4() == null || msg.getBlock4().isEmpty()) { return null; } return get(msg.getBlock4()); } /** * Gets a list of all occurrences of the field Field87A in the given message * an empty list is returned if none found. * @param msg may be empty or null in which case an empty list is returned * @see #getAll(SwiftTagListBlock) */ public static List<Field87A> getAll(final SwiftMessage msg) { if (msg == null || msg.getBlock4() == null || msg.getBlock4().isEmpty()) { return java.util.Collections.emptyList(); } return getAll(msg.getBlock4()); } /** * Gets a list of all occurrences of the field Field87A from the given block * an empty list is returned if none found. * * @param block may be empty or null in which case an empty list is returned */ public static List<Field87A> getAll(final SwiftTagListBlock block) { final List<Field87A> result = new ArrayList<>(); if (block == null || block.isEmpty()) { return result; } final Tag[] arr = block.getTagsByName(NAME); if (arr != null && arr.length > 0) { for (final Tag f : arr) { result.add(new Field87A(f)); } } return result; } /** * Returns a specific line from the field's value. * * @see MultiLineField#getLine(int) * @param line a reference to a specific line in the field, first line being 1 * @return line content or null if not present or if line number is above the expected * @since 7.7 */ public String getLine(int line) { return getLine(line, 0); } /** * Returns a specific line from the field's value. * * @see MultiLineField#getLine(int, int) * @param line a reference to a specific line in the field, first line being 1 * @param offset an optional component number used as offset when counting lines * @return line content or null if not present or if line number is above the expected * @since 7.7 */ public String getLine(int line, int offset) { Field87A cp = newInstance(this); return getLine(cp, line, null, offset); } /** * Returns the field value split into lines. * * @see MultiLineField#getLines() * @return lines content or empty list if field's value is empty * @since 7.7 */ public List<String> getLines() { return SwiftParseUtils.getLines(getValue()); } /** * Returns the field value starting at the offset component, split into lines. * * @see MultiLineField#getLines(int) * @param offset an optional component number used as offset when counting lines * @return found lines or empty list if lines are not present or the offset is invalid * @since 7.7 */ public List<String> getLines(int offset) { Field87A cp = newInstance(this); return SwiftParseUtils.getLines(getLine(cp, null, null, offset)); } /** * Returns a specific subset of lines from the field's value, given a range. * * @see MultiLineField#getLinesBetween(int, int ) * @param start a reference to a specific line in the field, first line being 1 * @param end a reference to a specific line in the field, must be greater than start * @return found lines or empty list if value is empty * @since 7.7 */ public List<String> getLinesBetween(int start, int end) { return getLinesBetween(start, end, 0); } /** * Returns a specific subset of lines from the field's value, starting at the offset component. * * @see MultiLineField#getLinesBetween(int start, int end, int offset) * @param start a reference to a specific line in the field, first line being 1 * @param end a reference to a specific line in the field, must be greater than start * @param offset an optional component number used as offset when counting lines * @return found lines or empty list if lines are not present or the offset is invalid * @since 7.7 */ public List<String> getLinesBetween(int start, int end, int offset) { Field87A cp = newInstance(this); return SwiftParseUtils.getLines(getLine(cp, start, end, offset)); } /** * This method deserializes the JSON data into a Field87A object. * @param json JSON structure including tuples with label and value for all field components * @return a new field instance with the JSON data parsed into field components or an empty field id the JSON is invalid * @since 7.10.3 * @see Field#fromJson(String) */ public static Field87A fromJson(final String json) { final Field87A field = new Field87A(); final JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject(); // **** COMPONENT 1 - D/C Mark if (jsonObject.get("dCMark") != null) { field.setComponent1(jsonObject.get("dCMark").getAsString()); } // **** COMPONENT 2 - Account if (jsonObject.get("account") != null) { field.setComponent2(jsonObject.get("account").getAsString()); } // **** COMPONENT 3 - Identifier Code // first try using alias's names (including deprecated ones, if any) if (jsonObject.get("bIC") != null) { field.setComponent3(jsonObject.get("bIC").getAsString()); } // last try using the official component's name (overwrites alternatives and DEPRECATED) if (jsonObject.get("identifierCode") != null) { field.setComponent3(jsonObject.get("identifierCode").getAsString()); } return field; } }
/******************************************************************************* * Any modification, copies of sections of this file must be attached with this * license and shown clearly in the developer's project. The code can be used * as long as you state clearly you do not own it. Any violation might result in * a take-down. * * MIT License * * Copyright (c) 2016, 2017 Anthony Law * * 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 org.ev3dev.hardware.sensors; import org.ev3dev.exception.EV3LibraryException; import org.ev3dev.exception.InvalidModeException; import org.ev3dev.exception.InvalidPortException; import org.ev3dev.exception.InvalidSensorException; import org.ev3dev.hardware.ports.LegoPort; /** * LEGO EV3 color sensor. * @author Anthony * */ public class ColorSensor extends Sensor { /** * Reflected Light Intensity required Sysfs mode */ public static final String SYSFS_REFLECTED_LIGHT_INTENSITY_MODE = "COL-REFLECT"; /** * Reflected Light Intensity Sysfs value index */ public static final int SYSFS_REFLECTED_LIGHT_INTENSITY_VALUE_INDEX = 0; /** * Ambient Light Intensity required Sysfs mode */ public static final String SYSFS_AMBIENT_LIGHT_INTENSITY_MODE = "COL-AMBIENT"; /** * Ambient Light Intensity Sysfs value index */ public static final int SYSFS_AMBIENT_LIGHT_INTENSITY_VALUE_INDEX = 0; /** * Color required Sysfs mode */ public static final String SYSFS_COLOR_MODE = "COL-COLOR"; /** * Color Sysfs value index */ public static final int SYSFS_COLOR_VALUE_INDEX = 0; /** * RGB required Sysfs mode */ public static final String SYSFS_RGB_MODE = "RGB-RAW"; /** * RGB Red Sysfs value index */ public static final int SYSFS_RGB_R_VALUE_INDEX = 0; /** * RGB Green Sysfs value index */ public static final int SYSFS_RGB_G_VALUE_INDEX = 1; /** * RGB Blue Sysfs value index */ public static final int SYSFS_RGB_B_VALUE_INDEX = 2; /** * This device's default driver name */ public static final String DRIVER_NAME = "lego-ev3-color"; private boolean autoSwitchMode = true; /** * Creates a new ColorSensor instance. * @param port LegoPort * @throws InvalidPortException If the specified port wasn't valid * @throws InvalidSensorException If the specified sensor wasn't a ColorSensor * @throws EV3LibraryException If I/O goes wrong */ public ColorSensor(LegoPort port) throws EV3LibraryException { super(port); if (!DRIVER_NAME.equals(this.getDriverName())){ throw new InvalidSensorException("The specified device is not a color sensor."); } port.getAddress(); } /** * Reflected light intensity as a percentage. Light on sensor is red. * @return Reflected Light Intensity in percentage * @throws EV3LibraryException If I/O goes wrong * @throws InvalidModeException The mode selected wasn't valid, or <b>Auto Switch Mode</b> has disabled. */ public int getReflectedLightIntensity() throws EV3LibraryException, InvalidModeException{ if (!this.getMode().equals(SYSFS_REFLECTED_LIGHT_INTENSITY_MODE)){ if (autoSwitchMode){ this.setMode(SYSFS_REFLECTED_LIGHT_INTENSITY_MODE); } else { throw new InvalidModeException("[Auto-switch is off] You are not using a correct mode(" + SYSFS_REFLECTED_LIGHT_INTENSITY_MODE + ")! Yours: " + this.getMode()); } } String str = this.getAttribute("value" + SYSFS_REFLECTED_LIGHT_INTENSITY_VALUE_INDEX); return Integer.parseInt(str); } /** * Ambient light intensity. Light on sensor is dimly lit blue. * @return Ambient light intensity in percentage * @throws EV3LibraryException If I/O goes wrong * @throws InvalidModeException The mode selected wasn't valid, or <b>Auto Switch Mode</b> has disabled. */ public int getAmbientLightIntensity() throws EV3LibraryException, InvalidModeException{ if (!this.getMode().equals(SYSFS_AMBIENT_LIGHT_INTENSITY_MODE)){ if (autoSwitchMode){ this.setMode(SYSFS_AMBIENT_LIGHT_INTENSITY_MODE); } else { throw new InvalidModeException("[Auto-switch is off] You are not using a correct mode(" + SYSFS_AMBIENT_LIGHT_INTENSITY_MODE + ")! Yours: " + this.getMode()); } } String str = this.getAttribute("value" + SYSFS_AMBIENT_LIGHT_INTENSITY_VALUE_INDEX); return Integer.parseInt(str); } /** * Color detected by the sensor, categorized by overall value. <br> * - 0: No color<br> * - 1: Black<br> * - 2: Blue<br> * - 3: Green<br> * - 4: Yellow<br> * - 5: Red<br> * - 6: White<br> * - 7: Brown * @return Color value * @throws EV3LibraryException If I/O goes wrong * @throws InvalidModeException The mode selected wasn't valid, or <b>Auto Switch Mode</b> has disabled. */ public int getColor() throws EV3LibraryException, InvalidModeException{ if (!this.getMode().equals(SYSFS_COLOR_MODE)){ if (autoSwitchMode){ this.setMode(SYSFS_COLOR_MODE); } else { throw new InvalidModeException("[Auto-switch is off] You are not using a correct mode(" + SYSFS_COLOR_MODE + ")! Yours: " + this.getMode()); } } String str = this.getAttribute("value" + SYSFS_COLOR_VALUE_INDEX); return Integer.parseInt(str); } /** * Red component of the detected color, in the range 0-1020 * @return RGB Red component * @throws EV3LibraryException If I/O goes wrong * @throws InvalidModeException The mode selected wasn't valid, or <b>Auto Switch Mode</b> has disabled. */ public int getRGB_Red() throws EV3LibraryException, InvalidModeException{ if (!this.getMode().equals(SYSFS_RGB_MODE)){ if (autoSwitchMode){ this.setMode(SYSFS_RGB_MODE); } else { throw new InvalidModeException("[Auto-switch is off] You are not using a correct mode(" + SYSFS_RGB_MODE + ")! Yours: " + this.getMode()); } } String str = this.getAttribute("value" + SYSFS_RGB_R_VALUE_INDEX); return Integer.parseInt(str); } /** * Green component of the detected color, in the range 0-1020 * @return Green Red component * @throws EV3LibraryException If I/O goes wrong * @throws InvalidModeException The mode selected wasn't valid, or <b>Auto Switch Mode</b> has disabled. */ public int getRGB_Green() throws EV3LibraryException, InvalidModeException{ if (!this.getMode().equals(SYSFS_RGB_MODE)){ if (autoSwitchMode){ this.setMode(SYSFS_RGB_MODE); } else { throw new InvalidModeException("[Auto-switch is off] You are not using a correct mode(" + SYSFS_RGB_MODE + ")! Yours: " + this.getMode()); } } String str = this.getAttribute("value" + SYSFS_RGB_G_VALUE_INDEX); return Integer.parseInt(str); } /** * Blue component of the detected color, in the range 0-1020 * @return Blue Red component * @throws EV3LibraryException If I/O goes wrong * @throws InvalidModeException The mode selected wasn't valid, or <b>Auto Switch Mode</b> has disabled. */ public int getRGB_Blue() throws EV3LibraryException, InvalidModeException{ if (!this.getMode().equals(SYSFS_RGB_MODE)){ if (autoSwitchMode){ this.setMode(SYSFS_RGB_MODE); } else { throw new InvalidModeException("[Auto-switch is off] You are not using a correct mode(" + SYSFS_RGB_MODE + ")! Yours: " + this.getMode()); } } String str = this.getAttribute("value" + SYSFS_RGB_B_VALUE_INDEX); return Integer.parseInt(str); } /** * Set Auto Switch Mode to be enabled or disabled.<br> * (Default: enabled) * @param autoswitch A Boolean */ public void setAutoSwitchMode(boolean autoswitch){ this.autoSwitchMode = autoswitch; } /** * Get whether Auto Switch Mode is enabled or disabled. * @return A Boolean */ public boolean isAutoSwitchMode(){ return autoSwitchMode; } }