Example usage for org.apache.commons.lang3.tuple Pair getKey

List of usage examples for org.apache.commons.lang3.tuple Pair getKey

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Pair getKey.

Prototype

@Override
public final L getKey() 

Source Link

Document

Gets the key from this pair.

This method implements the Map.Entry interface returning the left element as the key.

Usage

From source file:alfio.manager.EventManagerIntegrationTest.java

@Test
public void testDecreaseEventSeatsWithABoundedCategory() {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", 10, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            true, null, null, null, null, null));
    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);//from   w ww  . ja  va2  s .c o m
    Event event = pair.getKey();
    EventModification update = new EventModification(event.getId(), Event.EventType.INTERNAL, null, null, null,
            null, null, null, null, event.getOrganizationId(), null, "0.0", "0.0",
            ZoneId.systemDefault().getId(), null, DateTimeModification.fromZonedDateTime(event.getBegin()),
            DateTimeModification.fromZonedDateTime(event.getEnd()), event.getRegularPrice(),
            event.getCurrency(), 10, event.getVat(), event.isVatIncluded(), event.getAllowedPaymentProxies(),
            null, event.isFreeOfCharge(), null, 7, null, null);
    eventManager.updateEventPrices(event, update, pair.getValue());
    List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
    assertNotNull(tickets);
    assertFalse(tickets.isEmpty());
    assertEquals(10, tickets.size());
    assertTrue(tickets.stream().allMatch(t -> t.getCategoryId() != null));
}

From source file:alfio.manager.EventManagerIntegrationTest.java

@Test
public void testUpdateBoundedCategory() {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", 10, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            false, null, null, null, null, null));
    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);//from  ww  w  .j a v a 2  s .com
    Event event = pair.getKey();
    TicketCategory category = ticketCategoryRepository.findByEventId(event.getId()).get(0);
    TicketCategoryModification tcm = new TicketCategoryModification(category.getId(), "default", 20,
            new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            false, null, null, null, null, null);
    eventManager.updateCategory(category.getId(), event.getId(), tcm, pair.getValue());
    waitingQueueSubscriptionProcessor.distributeAvailableSeats(event);
    List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
    assertNotNull(tickets);
    assertFalse(tickets.isEmpty());
    assertEquals(AVAILABLE_SEATS, tickets.size());
    assertEquals(0, tickets.stream().filter(t -> t.getCategoryId() == null).count());
}

From source file:alfio.manager.EventManagerIntegrationTest.java

@Test
public void testIncreaseEventSeatsWithABoundedCategory() {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", 10, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            true, null, null, null, null, null));
    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);/*from   ww w . ja v  a  2  s .  c  om*/
    Event event = pair.getKey();
    EventModification update = new EventModification(event.getId(), Event.EventType.INTERNAL, null, null, null,
            null, null, null, null, event.getOrganizationId(), null, "0.0", "0.0",
            ZoneId.systemDefault().getId(), null, DateTimeModification.fromZonedDateTime(event.getBegin()),
            DateTimeModification.fromZonedDateTime(event.getEnd()), event.getRegularPrice(),
            event.getCurrency(), 40, event.getVat(), event.isVatIncluded(), event.getAllowedPaymentProxies(),
            null, event.isFreeOfCharge(), null, 7, null, null);
    eventManager.updateEventPrices(event, update, pair.getValue());
    List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
    assertNotNull(tickets);
    assertFalse(tickets.isEmpty());
    assertEquals(20, tickets.size());
    assertEquals(20, ticketRepository.countReleasedUnboundedTickets(event.getId()).intValue());
    assertEquals(10, tickets.stream().filter(t -> t.getCategoryId() != null).count());
}

From source file:alfio.manager.EventManagerIntegrationTest.java

@Test
public void testAddBoundedCategoryToUnboundedEvent() {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", 0, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            false, null, null, null, null, null));
    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);/*from   w  ww. j  a va2s .  c o m*/
    Event event = pair.getKey();
    TicketCategoryModification tcm = new TicketCategoryModification(null, "default", 10,
            new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            true, null, null, null, null, null);
    Result<Integer> result = eventManager.insertCategory(event, tcm, pair.getValue());
    assertTrue(result.isSuccess());
    List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
    assertNotNull(tickets);
    assertFalse(tickets.isEmpty());
    assertEquals(10, tickets.size());
    assertEquals(10, tickets.stream().filter(t -> t.getCategoryId() == null).count());
    assertEquals(10,
            ticketRepository.countReleasedTicketInCategory(event.getId(), result.getData()).intValue());
}

From source file:alfio.manager.EventManagerIntegrationTest.java

@Test
public void testIncreaseEventSeatsWithAnUnboundedCategory() {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", 10, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            false, null, null, null, null, null));
    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);//from   ww w. j  av  a 2  s .  c om
    Event event = pair.getKey();
    EventModification update = new EventModification(event.getId(), Event.EventType.INTERNAL, null, null, null,
            null, null, null, null, event.getOrganizationId(), null, "0.0", "0.0",
            ZoneId.systemDefault().getId(), null, DateTimeModification.fromZonedDateTime(event.getBegin()),
            DateTimeModification.fromZonedDateTime(event.getEnd()), event.getRegularPrice(),
            event.getCurrency(), 40, event.getVat(), event.isVatIncluded(), event.getAllowedPaymentProxies(),
            null, event.isFreeOfCharge(), null, 7, null, null);
    eventManager.updateEventPrices(event, update, pair.getValue());
    List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
    assertNotNull(tickets);
    assertFalse(tickets.isEmpty());
    assertEquals(20, tickets.size());
    assertEquals(20, ticketRepository.countReleasedUnboundedTickets(event.getId()).intValue());
    waitingQueueSubscriptionProcessor.distributeAvailableSeats(event);
    tickets = ticketRepository.findFreeByEventId(event.getId());
    assertEquals(40, tickets.size());
    assertEquals(40, tickets.stream().filter(t -> t.getCategoryId() == null).count());
}

From source file:alfio.manager.EventManagerIntegrationTest.java

private Pair<Event, String> generateAndEditEvent(int newEventSize) {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", 10, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            true, null, null, null, null, null));
    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);//from w  w w .  ja va  2s.  c o  m

    Event event = pair.getKey();
    if (newEventSize != AVAILABLE_SEATS) {
        EventModification update = new EventModification(event.getId(), Event.EventType.INTERNAL, null, null,
                null, null, null, null, null, event.getOrganizationId(), null, null, null,
                event.getZoneId().toString(), Collections.emptyMap(),
                DateTimeModification.fromZonedDateTime(event.getBegin()),
                DateTimeModification.fromZonedDateTime(event.getEnd()), event.getRegularPrice(),
                event.getCurrency(), newEventSize, event.getVat(), event.isVatIncluded(),
                event.getAllowedPaymentProxies(), null, event.isFreeOfCharge(), null, 7, null, null);
        eventManager.updateEventPrices(event, update, pair.getValue());
    }
    List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
    assertNotNull(tickets);
    assertFalse(tickets.isEmpty());
    assertEquals(AVAILABLE_SEATS, tickets.size());
    if (newEventSize > AVAILABLE_SEATS) {
        assertEquals(newEventSize - AVAILABLE_SEATS,
                ticketRepository.countReleasedUnboundedTickets(event.getId()).intValue());
    }
    assertEquals(10, tickets.stream().filter(t -> t.getCategoryId() != null).count());
    return Pair.of(eventRepository.findById(event.getId()), pair.getRight());
}

From source file:alfio.manager.EventManagerIntegrationTest.java

@Test
public void testAddUnboundedCategoryShrinkBoundedCategory() {
    //create the event with a single category which contains all the tickets
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", AVAILABLE_SEATS, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            true, null, null, null, null, null));
    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);/*from w w w .  j  ava 2 s .c  o m*/
    Event event = pair.getKey();
    //shrink the original category to AVAILABLE_SEATS - 2, this would free two seats
    int categoryId = ticketCategoryRepository.findAllTicketCategories(event.getId()).get(0).getId();
    TicketCategoryModification shrink = new TicketCategoryModification(categoryId, "default",
            AVAILABLE_SEATS - 2, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            true, null, null, null, null, null);
    eventManager.updateCategory(categoryId, event.getId(), shrink, pair.getRight());

    //now insert an unbounded ticket category
    TicketCategoryModification tcm = new TicketCategoryModification(null, "default", 10,
            new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            false, null, null, null, null, null);
    eventManager.insertCategory(event.getId(), tcm, pair.getValue());

    waitingQueueSubscriptionProcessor.distributeAvailableSeats(event);
    List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
    assertNotNull(tickets);
    assertFalse(tickets.isEmpty());
    assertEquals(AVAILABLE_SEATS, tickets.size());
    assertEquals(18,
            tickets.stream().filter(t -> t.getCategoryId() != null && t.getCategoryId() == categoryId).count());
    assertEquals(2, tickets.stream().filter(t -> t.getCategoryId() == null).count());
}

From source file:com.nextdoor.bender.operation.substitution.regex.RegexSubstitution.java

@Override
protected void doSubstitution(InternalEvent ievent, DeserializedEvent devent) {
    Pair<String, Map<String, Object>> kv;
    try {/*from   ww  w .  ja va 2 s.  co m*/
        kv = getRegexMatches(devent);
    } catch (FieldNotFoundException e) {
        if (this.failSrcNotFound) {
            throw new OperationException(e);
        }
        return;
    }

    ((Map<String, Object>) kv.getValue()).forEach((k, v) -> {
        try {
            devent.setField(k, v);
        } catch (FieldNotFoundException e) {
            if (this.failDstNotFound) {
                throw new OperationException(e);
            }
        }
    });

    /*
     * Do not remove source field if it has been replaced by a regex group.
     */
    if (this.removeSrcField && !kv.getValue().containsKey(kv.getKey())) {
        try {
            devent.removeField(kv.getKey());
        } catch (FieldNotFoundException e) {
            if (this.failSrcNotFound) {
                throw new OperationException(e);
            }
        }
    }
}

From source file:io.swagger.api.impl.ToolsApiServiceImpl.java

/**
 * @param registryId   registry id/*from w w w  . j a va  2 s. c om*/
 * @param versionId    git reference
 * @param type         type of file
 * @param relativePath if null, return the primary descriptor, if not null, return a specific file
 * @param unwrap       unwrap the file and present the descriptor sans wrapper model
 * @return a specific file wrapped in a response
 */
private Response getFileByToolVersionID(String registryId, String versionId, SourceFile.FileType type,
        String relativePath, boolean unwrap) {
    // if a version is provided, get that version, otherwise return the newest
    ParsedRegistryID parsedID = new ParsedRegistryID(registryId);
    try {
        versionId = URLDecoder.decode(versionId, StandardCharsets.UTF_8.displayName());
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    Entry entry = getEntry(parsedID);

    // check whether this is registered
    if (!entry.getIsPublished()) {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }

    final Pair<io.swagger.model.Tool, Table<String, SourceFile.FileType, Object>> toolTablePair = convertContainer2Tool(
            entry);
    String finalVersionId = versionId;
    if (toolTablePair == null || toolTablePair.getKey().getVersions() == null) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
    io.swagger.model.Tool convertedTool = toolTablePair.getKey();
    final Optional<ToolVersion> first = convertedTool.getVersions().stream()
            .filter(toolVersion -> toolVersion.getName().equalsIgnoreCase(finalVersionId)).findFirst();

    Optional<? extends Version> oldFirst;
    if (entry instanceof Tool) {
        Tool toolEntry = (Tool) entry;
        oldFirst = toolEntry.getVersions().stream()
                .filter(toolVersion -> toolVersion.getName().equalsIgnoreCase(finalVersionId)).findFirst();
    } else {
        Workflow workflowEntry = (Workflow) entry;
        oldFirst = workflowEntry.getVersions().stream()
                .filter(toolVersion -> toolVersion.getName().equalsIgnoreCase(finalVersionId)).findFirst();
    }

    final Table<String, SourceFile.FileType, Object> table = toolTablePair.getValue();
    if (first.isPresent() && oldFirst.isPresent()) {
        final ToolVersion toolVersion = first.get();
        final String toolVersionName = toolVersion.getName();
        if (type == DOCKERFILE) {
            final ToolDockerfile dockerfile = (ToolDockerfile) table.get(toolVersionName,
                    SourceFile.FileType.DOCKERFILE);
            return Response.status(Response.Status.OK)
                    .type(unwrap ? MediaType.TEXT_PLAIN : MediaType.APPLICATION_JSON)
                    .entity(unwrap ? dockerfile.getDockerfile() : dockerfile).build();
        } else {
            if (relativePath == null) {
                if ((type == DOCKSTORE_WDL)
                        && (((ToolDescriptor) table.get(toolVersionName, SourceFile.FileType.DOCKSTORE_WDL))
                                .getType() == ToolDescriptor.TypeEnum.WDL)) {
                    final ToolDescriptor descriptor = (ToolDescriptor) table.get(toolVersionName,
                            SourceFile.FileType.DOCKSTORE_WDL);
                    return Response.status(Response.Status.OK)
                            .entity(unwrap ? descriptor.getDescriptor() : descriptor).build();
                } else if (type == DOCKSTORE_CWL
                        && (((ToolDescriptor) table.get(toolVersionName, SourceFile.FileType.DOCKSTORE_CWL))
                                .getType() == ToolDescriptor.TypeEnum.CWL)) {
                    final ToolDescriptor descriptor = (ToolDescriptor) table.get(toolVersionName,
                            SourceFile.FileType.DOCKSTORE_CWL);
                    return Response.status(Response.Status.OK)
                            .type(unwrap ? MediaType.TEXT_PLAIN : MediaType.APPLICATION_JSON)
                            .entity(unwrap ? descriptor.getDescriptor() : descriptor).build();
                }
                return Response.status(Response.Status.NOT_FOUND).build();
            } else {
                final Set<SourceFile> sourceFiles = oldFirst.get().getSourceFiles();
                final Optional<SourceFile> first1 = sourceFiles.stream()
                        .filter(file -> file.getPath().equalsIgnoreCase(relativePath)).findFirst();
                if (first1.isPresent()) {
                    final SourceFile entity = first1.get();
                    return Response.status(Response.Status.OK)
                            .type(unwrap ? MediaType.TEXT_PLAIN : MediaType.APPLICATION_JSON)
                            .entity(unwrap ? entity.getContent() : entity).build();
                }
            }
        }
    }

    return Response.status(Response.Status.NOT_FOUND).build();
}

From source file:net.mindengine.galen.specs.reader.SpecReader.java

private void initSpecs() {

    putSpec("absent", new SimpleSpecProcessor(new SpecInit() {
        public Spec init() {
            return new SpecAbsent();
        }//from  w w w  .  j a v  a2  s .c o  m
    }));

    putSpec("visible", new SimpleSpecProcessor(new SpecInit() {
        public Spec init() {
            return new SpecVisible();
        }
    }));

    putSpec("contains(\\s+partly)?", new SpecListProccessor(new SpecListInit() {
        public Spec init(String specName, List<String> list) {
            String arguments = specName.substring("contains".length()).trim();

            boolean isPartly = (!arguments.isEmpty() && arguments.equals("partly"));
            return new SpecContains(list, isPartly);
        }
    }));

    putSpec("width", new SpecComplexProcessor(expectThese(range()), new SpecComplexInit() {
        public Spec init(String specName, String paramsText, String contextPath, Object[] args) {
            return new SpecWidth((Range) args[0]);
        }
    }));

    putSpec("height", new SpecComplexProcessor(expectThese(range()), new SpecComplexInit() {
        public Spec init(String specName, String paramsText, String contextPath, Object[] args) {
            return new SpecHeight((Range) args[0]);
        }
    }));

    putSpec("text\\s+.*", new SpecProcessor() {
        @Override
        public Spec processSpec(String specName, String paramsText, String contextPath) {
            String arguments = specName.substring("text".length()).trim();

            List<String> allWords = Expectations.readAllWords(arguments);

            if (allWords.size() > 0) {
                String type = allWords.get(allWords.size() - 1);

                allWords.remove(allWords.size() - 1);
                return new SpecText(SpecText.Type.fromString(type), paramsText.trim()).withOperations(allWords);
            } else
                throw new SyntaxException("Missing validation type (is, starts, ends, contains, matches)");
        }
    });

    putSpec("css.*", new SpecProcessor() {
        @Override
        public Spec processSpec(String specName, String paramsText, String contextPath) {
            String arguments = specName.substring("css".length()).trim();

            StringCharReader reader = new StringCharReader(arguments);

            String cssPropertyName = Expectations.word().read(reader);
            String typeString = Expectations.word().read(reader);

            if (cssPropertyName.isEmpty()) {
                throw new SyntaxException("Missing css property name");
            }
            if (typeString.isEmpty()) {
                throw new SyntaxException("Missing validation type (is, contains, starts, ends, matches)");
            }
            return new SpecCss(cssPropertyName, SpecText.Type.fromString(typeString), paramsText.trim());
        }
    });

    putSpec("inside.*", new SpecComplexProcessor(expectThese(objectName(), locations()), new SpecComplexInit() {
        @SuppressWarnings("unchecked")
        @Override
        public Spec init(String specName, String paramsText, String contextPath, Object[] args) {
            String leftoverName = specName.substring(6).trim();

            String objectName = (String) args[0];
            List<Location> locations = (List<Location>) args[1];

            SpecInside spec = new SpecInside(objectName, locations);

            if (leftoverName.equals("partly")) {
                spec.setPartly(true);
            }
            return spec;
        }
    }));

    putSpec("near", new SpecComplexProcessor(expectThese(objectName(), locations()), new SpecComplexInit() {
        @SuppressWarnings("unchecked")
        @Override
        public Spec init(String specName, String paramsText, String contextPath, Object[] args) {
            String objectName = (String) args[0];
            List<Location> locations = (List<Location>) args[1];

            if (locations == null || locations.size() == 0) {
                throw new SyntaxException(UNKNOWN_LINE, "There is no location defined");
            }
            return new SpecNear(objectName, locations);
        }
    }));

    putSpec("(above|below)", new SpecProcessor() {
        @Override
        public Spec processSpec(String specName, String paramsText, String contextPath) throws IOException {

            StringCharReader reader = new StringCharReader(paramsText.trim());
            String objectName = new ExpectWord().read(reader);

            Range range;
            if (reader.hasMore()) {
                range = Expectations.range().read(reader);
            } else {
                range = Range.greaterThan(-1.0);
            }

            if (specName.equals("above")) {
                return new SpecAbove(objectName, range);
            } else
                return new SpecBelow(objectName, range);
        }
    });

    putSpec("(left\\s+of|right\\s+of)", new SpecProcessor() {
        @Override
        public Spec processSpec(String specName, String paramsText, String contextPath) throws IOException {

            String direction = Expectations.word().read(new StringCharReader(specName));

            StringCharReader reader = new StringCharReader(paramsText.trim());
            String objectName = new ExpectWord().read(reader);

            Range range;
            if (reader.hasMore()) {
                range = Expectations.range().read(reader);
            } else {
                range = Range.greaterThan(-1.0);
            }

            if (direction.equals("left")) {
                return new SpecLeftOf(objectName, range);
            } else {
                return new SpecRightOf(objectName, range);
            }

        }
    });

    putSpec("aligned\\s+.*", new SpecObjectAndErrorRateProcessor(new SpecObjectAndErrorRateInit() {

        @Override
        public Spec init(String specName, String objectName, Integer errorRate) {
            String arguments = specName.substring("aligned".length()).trim();

            StringCharReader reader = new StringCharReader(arguments);

            String[] words = ExpectWord.readAllWords(reader);

            if (words.length == 0) {
                throw new SyntaxException(
                        "Alignment is not defined. Should be either 'vertically' either 'horizonally'");
            }
            String type = words[0];

            Alignment alignment = Alignment.ALL;
            if (words.length > 1) {
                alignment = Alignment.parse(words[1]);
            }

            if (errorRate == null) {
                errorRate = 0;
            }

            if (type.equals("horizontally")) {
                if (alignment.isOneOf(CENTERED, TOP, BOTTOM, ALL)) {
                    return new SpecHorizontally(alignment, objectName).withErrorRate(errorRate);
                } else {
                    throw new SyntaxException(UNKNOWN_LINE,
                            "Horizontal alignment doesn't allow this side: " + alignment.toString());
                }
            } else if (type.equals("vertically")) {
                if (alignment.isOneOf(CENTERED, LEFT, RIGHT, ALL)) {
                    return new SpecVertically(alignment, objectName).withErrorRate(errorRate);
                } else {
                    throw new SyntaxException(UNKNOWN_LINE,
                            "Verticall alignment doesn't allow this side: " + alignment.toString());
                }
            } else {
                throw new SyntaxException("Unknown alignment: " + type);
            }
        }
    }));

    putSpec("centered\\s.*", new SpecObjectAndErrorRateProcessor(new SpecObjectAndErrorRateInit() {

        @Override
        public Spec init(String specName, String objectName, Integer errorRate) {
            specName = specName.replace("centered", "").trim();
            String args[] = specName.split(" ");

            SpecCentered.Alignment alignment = SpecCentered.Alignment.ALL;
            SpecCentered.Location location = null;
            if (args.length == 1) {
                location = SpecCentered.Location.fromString(args[0]);
            } else {
                alignment = SpecCentered.Alignment.fromString(args[0]);
                location = SpecCentered.Location.fromString(args[1]);
            }

            // Setting default 2 px error rate in case it was not provided in page spec
            if (errorRate == null) {
                errorRate = 2;
            }

            return new SpecCentered(objectName, alignment, location).withErrorRate(errorRate);
        }
    }));

    putSpec("(on\\s.*|on)",
            new SpecComplexProcessor(expectThese(objectName(), locations()), new SpecComplexInit() {
                @SuppressWarnings("unchecked")
                @Override
                public Spec init(String specName, String paramsText, String contextPath, Object[] args) {
                    String objectName = (String) args[0];

                    String[] words = ExpectWord.readAllWords(new StringCharReader(specName));

                    if (words.length > 3) {
                        throw new SyntaxException("Too many sides. Should use only 2");
                    }

                    Side sideHorizontal = Side.TOP;
                    Side sideVertical = Side.LEFT;

                    boolean isFirstHorizontal = false;
                    if (words.length > 1) {
                        Side side = Side.fromString(words[1]);
                        if (side == Side.TOP || side == Side.BOTTOM) {
                            isFirstHorizontal = true;
                            sideHorizontal = side;
                        } else
                            sideVertical = side;
                    }

                    if (words.length > 2) {
                        Side side = Side.fromString(words[2]);
                        if (side == Side.TOP || side == Side.BOTTOM) {
                            if (isFirstHorizontal) {
                                throw new SyntaxException(
                                        "Cannot use theses sides: " + words[1] + " " + words[2]);
                            }
                            sideHorizontal = side;
                        } else {
                            if (!isFirstHorizontal) {
                                throw new SyntaxException(
                                        "Cannot use theses sides: " + words[1] + " " + words[2]);
                            }
                            sideVertical = side;
                        }
                    }

                    List<Location> locations = (List<Location>) args[1];
                    if (locations == null || locations.size() == 0) {
                        throw new SyntaxException(UNKNOWN_LINE, "There is no location defined");
                    }

                    return new SpecOn(objectName, sideHorizontal, sideVertical, locations);
                }
            }));

    putSpec("component.*", new SpecProcessor() {

        @Override
        public Spec processSpec(String specName, String paramsText, String contextPath) throws IOException {

            String childFilePath = paramsText.trim();
            if (childFilePath.isEmpty()) {
                throw new SyntaxException("File path to component spec is not specified");
            }

            String fullFilePath = childFilePath;
            if (contextPath != null) {
                fullFilePath = contextPath + File.separator + childFilePath;
            }

            SpecComponent spec = new SpecComponent();
            spec.setSpecPath(fullFilePath);

            if (getSecondWord(specName).equals("frame")) {
                spec.setFrame(true);
            }

            return spec;
        }
    });

    putSpec("color\\s+scheme", new SpecComplexProcessor(expectThese(colorRanges()), new SpecComplexInit() {
        @SuppressWarnings("unchecked")
        @Override
        public Spec init(String specName, String paramsText, String contextPath, Object[] args) {

            List<ColorRange> colorRanges = (List<ColorRange>) args[0];
            if (colorRanges == null || colorRanges.size() == 0) {
                throw new SyntaxException("There are no colors defined");
            }

            SpecColorScheme spec = new SpecColorScheme();
            spec.setColorRanges(colorRanges);
            return spec;
        }
    }));

    putSpec("image",
            new SpecComplexProcessor(expectThese(commaSeparatedRepeatedKeyValues()), new SpecComplexInit() {
                @Override
                public Spec init(String specName, String paramsText, String contextPath, Object[] args) {
                    List<Pair<String, String>> parameters = (List<Pair<String, String>>) args[0];

                    SpecImage spec = new SpecImage();
                    spec.setImagePaths(new LinkedList<String>());
                    spec.setStretch(false);
                    spec.setErrorRate(GalenConfig.getConfig().getImageSpecDefaultErrorRate());
                    spec.setTolerance(GalenConfig.getConfig().getImageSpecDefaultTolerance());

                    for (Pair<String, String> parameter : parameters) {
                        if ("file".equals(parameter.getKey())) {
                            if (contextPath != null) {
                                spec.getImagePaths().add(contextPath + File.separator + parameter.getValue());
                            } else {
                                spec.getImagePaths().add(parameter.getValue());
                            }
                        } else if ("error".equals(parameter.getKey())) {
                            spec.setErrorRate(SpecImage.ErrorRate.fromString(parameter.getValue()));
                        } else if ("tolerance".equals(parameter.getKey())) {
                            spec.setTolerance(parseIntegerParameter("tolerance", parameter.getValue()));
                        } else if ("stretch".equals(parameter.getKey())) {
                            spec.setStretch(true);
                        } else if ("area".equals(parameter.getKey())) {
                            spec.setSelectedArea(parseRect(parameter.getValue()));
                        } else if ("filter".equals(parameter.getKey())) {
                            ImageFilter filter = parseImageFilter(parameter.getValue());
                            spec.getOriginalFilters().add(filter);
                            spec.getSampleFilters().add(filter);
                        } else if ("filter-a".equals(parameter.getKey())) {
                            ImageFilter filter = parseImageFilter(parameter.getValue());
                            spec.getOriginalFilters().add(filter);
                        } else if ("filter-b".equals(parameter.getKey())) {
                            ImageFilter filter = parseImageFilter(parameter.getValue());
                            spec.getSampleFilters().add(filter);
                        } else if ("map-filter".equals(parameter.getKey())) {
                            ImageFilter filter = parseImageFilter(parameter.getValue());
                            spec.getMapFilters().add(filter);
                        } else if ("crop-if-outside".equals(parameter.getKey())) {
                            spec.setCropIfOutside(true);
                        } else {
                            throw new SyntaxException("Unknown parameter: " + parameter.getKey());
                        }
                    }

                    if (spec.getImagePaths() == null || spec.getImagePaths().size() == 0) {
                        throw new SyntaxException("There are no images defined");
                    }
                    return spec;
                }
            }));

}