repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
fuinorg/ddd-4-java
src/test/java/org/fuin/ddd4j/test/PersonId.java
// Path: src/main/java/org/fuin/ddd4j/ddd/EntityId.java // public interface EntityId extends TechnicalId { // // /** // * Returns the type represented by this identifier. // * // * @return Type of entity. // */ // public EntityType getType(); // // /** // * Returns the entity identifier as string. // * // * @return Entity identifier. // */ // public String asString(); // // /** // * Returns the entity identifier as string with type and identifier. // * // * @return Type and identifier. // */ // public String asTypedString(); // // } // // Path: src/main/java/org/fuin/ddd4j/ddd/EntityType.java // public interface EntityType extends Serializable { // // /** // * Returns the entity type name as string. // * // * @return Unique entity type name. // */ // public String asString(); // // } // // Path: src/main/java/org/fuin/ddd4j/ddd/StringBasedEntityType.java // @Immutable // public final class StringBasedEntityType extends AbstractStringValueObject implements EntityType { // // private static final long serialVersionUID = 1000L; // // @NotEmpty // @Size(max = 255) // private final String str; // // /** // * Constructor with unique name to use. // * // * @param str // * Type name of an aggregate that is unique within all types of the context // */ // public StringBasedEntityType(@NotEmpty @Size(max = 255) final String str) { // Contract.requireArgNotEmpty("str", str); // Contract.requireArgMaxLength("str", str, 255); // this.str = str; // } // // @Override // public final String asBaseType() { // return str; // } // // @Override // public final String toString() { // return str; // } // // }
import org.fuin.objects4j.common.Immutable; import jakarta.validation.constraints.NotNull; import org.fuin.ddd4j.ddd.EntityId; import org.fuin.ddd4j.ddd.EntityType; import org.fuin.ddd4j.ddd.StringBasedEntityType; import org.fuin.objects4j.common.Contract; import org.fuin.objects4j.vo.AbstractIntegerValueObject;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.ddd4j.test; /** * Unique identifier of a person. */ @Immutable public final class PersonId extends AbstractIntegerValueObject implements EntityId { private static final long serialVersionUID = 1000L; /** Type of entity this identifier represents. */
// Path: src/main/java/org/fuin/ddd4j/ddd/EntityId.java // public interface EntityId extends TechnicalId { // // /** // * Returns the type represented by this identifier. // * // * @return Type of entity. // */ // public EntityType getType(); // // /** // * Returns the entity identifier as string. // * // * @return Entity identifier. // */ // public String asString(); // // /** // * Returns the entity identifier as string with type and identifier. // * // * @return Type and identifier. // */ // public String asTypedString(); // // } // // Path: src/main/java/org/fuin/ddd4j/ddd/EntityType.java // public interface EntityType extends Serializable { // // /** // * Returns the entity type name as string. // * // * @return Unique entity type name. // */ // public String asString(); // // } // // Path: src/main/java/org/fuin/ddd4j/ddd/StringBasedEntityType.java // @Immutable // public final class StringBasedEntityType extends AbstractStringValueObject implements EntityType { // // private static final long serialVersionUID = 1000L; // // @NotEmpty // @Size(max = 255) // private final String str; // // /** // * Constructor with unique name to use. // * // * @param str // * Type name of an aggregate that is unique within all types of the context // */ // public StringBasedEntityType(@NotEmpty @Size(max = 255) final String str) { // Contract.requireArgNotEmpty("str", str); // Contract.requireArgMaxLength("str", str, 255); // this.str = str; // } // // @Override // public final String asBaseType() { // return str; // } // // @Override // public final String toString() { // return str; // } // // } // Path: src/test/java/org/fuin/ddd4j/test/PersonId.java import org.fuin.objects4j.common.Immutable; import jakarta.validation.constraints.NotNull; import org.fuin.ddd4j.ddd.EntityId; import org.fuin.ddd4j.ddd.EntityType; import org.fuin.ddd4j.ddd.StringBasedEntityType; import org.fuin.objects4j.common.Contract; import org.fuin.objects4j.vo.AbstractIntegerValueObject; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.ddd4j.test; /** * Unique identifier of a person. */ @Immutable public final class PersonId extends AbstractIntegerValueObject implements EntityId { private static final long serialVersionUID = 1000L; /** Type of entity this identifier represents. */
public static final EntityType ENTITY_TYPE = new StringBasedEntityType("Person");
fuinorg/ddd-4-java
src/test/java/org/fuin/ddd4j/test/PersonId.java
// Path: src/main/java/org/fuin/ddd4j/ddd/EntityId.java // public interface EntityId extends TechnicalId { // // /** // * Returns the type represented by this identifier. // * // * @return Type of entity. // */ // public EntityType getType(); // // /** // * Returns the entity identifier as string. // * // * @return Entity identifier. // */ // public String asString(); // // /** // * Returns the entity identifier as string with type and identifier. // * // * @return Type and identifier. // */ // public String asTypedString(); // // } // // Path: src/main/java/org/fuin/ddd4j/ddd/EntityType.java // public interface EntityType extends Serializable { // // /** // * Returns the entity type name as string. // * // * @return Unique entity type name. // */ // public String asString(); // // } // // Path: src/main/java/org/fuin/ddd4j/ddd/StringBasedEntityType.java // @Immutable // public final class StringBasedEntityType extends AbstractStringValueObject implements EntityType { // // private static final long serialVersionUID = 1000L; // // @NotEmpty // @Size(max = 255) // private final String str; // // /** // * Constructor with unique name to use. // * // * @param str // * Type name of an aggregate that is unique within all types of the context // */ // public StringBasedEntityType(@NotEmpty @Size(max = 255) final String str) { // Contract.requireArgNotEmpty("str", str); // Contract.requireArgMaxLength("str", str, 255); // this.str = str; // } // // @Override // public final String asBaseType() { // return str; // } // // @Override // public final String toString() { // return str; // } // // }
import org.fuin.objects4j.common.Immutable; import jakarta.validation.constraints.NotNull; import org.fuin.ddd4j.ddd.EntityId; import org.fuin.ddd4j.ddd.EntityType; import org.fuin.ddd4j.ddd.StringBasedEntityType; import org.fuin.objects4j.common.Contract; import org.fuin.objects4j.vo.AbstractIntegerValueObject;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.ddd4j.test; /** * Unique identifier of a person. */ @Immutable public final class PersonId extends AbstractIntegerValueObject implements EntityId { private static final long serialVersionUID = 1000L; /** Type of entity this identifier represents. */
// Path: src/main/java/org/fuin/ddd4j/ddd/EntityId.java // public interface EntityId extends TechnicalId { // // /** // * Returns the type represented by this identifier. // * // * @return Type of entity. // */ // public EntityType getType(); // // /** // * Returns the entity identifier as string. // * // * @return Entity identifier. // */ // public String asString(); // // /** // * Returns the entity identifier as string with type and identifier. // * // * @return Type and identifier. // */ // public String asTypedString(); // // } // // Path: src/main/java/org/fuin/ddd4j/ddd/EntityType.java // public interface EntityType extends Serializable { // // /** // * Returns the entity type name as string. // * // * @return Unique entity type name. // */ // public String asString(); // // } // // Path: src/main/java/org/fuin/ddd4j/ddd/StringBasedEntityType.java // @Immutable // public final class StringBasedEntityType extends AbstractStringValueObject implements EntityType { // // private static final long serialVersionUID = 1000L; // // @NotEmpty // @Size(max = 255) // private final String str; // // /** // * Constructor with unique name to use. // * // * @param str // * Type name of an aggregate that is unique within all types of the context // */ // public StringBasedEntityType(@NotEmpty @Size(max = 255) final String str) { // Contract.requireArgNotEmpty("str", str); // Contract.requireArgMaxLength("str", str, 255); // this.str = str; // } // // @Override // public final String asBaseType() { // return str; // } // // @Override // public final String toString() { // return str; // } // // } // Path: src/test/java/org/fuin/ddd4j/test/PersonId.java import org.fuin.objects4j.common.Immutable; import jakarta.validation.constraints.NotNull; import org.fuin.ddd4j.ddd.EntityId; import org.fuin.ddd4j.ddd.EntityType; import org.fuin.ddd4j.ddd.StringBasedEntityType; import org.fuin.objects4j.common.Contract; import org.fuin.objects4j.vo.AbstractIntegerValueObject; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.ddd4j.test; /** * Unique identifier of a person. */ @Immutable public final class PersonId extends AbstractIntegerValueObject implements EntityId { private static final long serialVersionUID = 1000L; /** Type of entity this identifier represents. */
public static final EntityType ENTITY_TYPE = new StringBasedEntityType("Person");
fuinorg/ddd-4-java
src/main/java/org/fuin/ddd4j/ddd/AggregateNotFoundException.java
// Path: src/main/java/org/fuin/ddd4j/ddd/Ddd4JUtils.java // public static final String SHORT_ID_PREFIX = "DDD4J";
import org.fuin.objects4j.common.MarshalInformation; import org.fuin.objects4j.common.ToExceptionCapable; import org.fuin.objects4j.vo.ValueObject; import static org.fuin.ddd4j.ddd.Ddd4JUtils.SHORT_ID_PREFIX; import java.io.Serializable; import jakarta.json.bind.annotation.JsonbProperty; import jakarta.validation.constraints.NotNull; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import org.fuin.objects4j.common.Contract; import org.fuin.objects4j.common.ExceptionShortIdentifable;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.ddd4j.ddd; /** * Signals that an aggregate of a given type and identifier was not found in the repository. */ public final class AggregateNotFoundException extends Exception implements ExceptionShortIdentifable, MarshalInformation<AggregateNotFoundException.Data> { private static final long serialVersionUID = 1L; /** Unique short identifier of this exception. */
// Path: src/main/java/org/fuin/ddd4j/ddd/Ddd4JUtils.java // public static final String SHORT_ID_PREFIX = "DDD4J"; // Path: src/main/java/org/fuin/ddd4j/ddd/AggregateNotFoundException.java import org.fuin.objects4j.common.MarshalInformation; import org.fuin.objects4j.common.ToExceptionCapable; import org.fuin.objects4j.vo.ValueObject; import static org.fuin.ddd4j.ddd.Ddd4JUtils.SHORT_ID_PREFIX; import java.io.Serializable; import jakarta.json.bind.annotation.JsonbProperty; import jakarta.validation.constraints.NotNull; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import org.fuin.objects4j.common.Contract; import org.fuin.objects4j.common.ExceptionShortIdentifable; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.ddd4j.ddd; /** * Signals that an aggregate of a given type and identifier was not found in the repository. */ public final class AggregateNotFoundException extends Exception implements ExceptionShortIdentifable, MarshalInformation<AggregateNotFoundException.Data> { private static final long serialVersionUID = 1L; /** Unique short identifier of this exception. */
public static final String SHORT_ID = SHORT_ID_PREFIX + "-AGGREGATE_NOT_FOUND";
fuinorg/ddd-4-java
src/test/java/org/fuin/ddd4j/ddd/EntityIdPathTest.java
// Path: src/test/java/org/fuin/ddd4j/test/AId.java // public class AId implements ImplRootId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("A"); // // private final long id; // // public AId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "AId [id=" + id + "]"; // } // // } // // Path: src/test/java/org/fuin/ddd4j/test/BId.java // public class BId implements EntityId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("B"); // // private final long id; // // public BId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "BId [id=" + id + "]"; // } // // } // // Path: src/test/java/org/fuin/ddd4j/test/CId.java // public class CId implements EntityId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("C"); // // private final long id; // // public CId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "CId [id=" + id + "]"; // } // // }
import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.fuin.ddd4j.test.AId; import org.fuin.ddd4j.test.BId; import org.fuin.ddd4j.test.CId; import org.fuin.objects4j.common.ConstraintViolationException; import org.junit.Test;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.ddd4j.ddd; //CHECKSTYLE:OFF Test code public class EntityIdPathTest { @Test public void testConstructorArray() { // PREPARE
// Path: src/test/java/org/fuin/ddd4j/test/AId.java // public class AId implements ImplRootId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("A"); // // private final long id; // // public AId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "AId [id=" + id + "]"; // } // // } // // Path: src/test/java/org/fuin/ddd4j/test/BId.java // public class BId implements EntityId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("B"); // // private final long id; // // public BId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "BId [id=" + id + "]"; // } // // } // // Path: src/test/java/org/fuin/ddd4j/test/CId.java // public class CId implements EntityId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("C"); // // private final long id; // // public CId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "CId [id=" + id + "]"; // } // // } // Path: src/test/java/org/fuin/ddd4j/ddd/EntityIdPathTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.fuin.ddd4j.test.AId; import org.fuin.ddd4j.test.BId; import org.fuin.ddd4j.test.CId; import org.fuin.objects4j.common.ConstraintViolationException; import org.junit.Test; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.ddd4j.ddd; //CHECKSTYLE:OFF Test code public class EntityIdPathTest { @Test public void testConstructorArray() { // PREPARE
final AId aid = new AId(1L);
fuinorg/ddd-4-java
src/test/java/org/fuin/ddd4j/ddd/EntityIdPathTest.java
// Path: src/test/java/org/fuin/ddd4j/test/AId.java // public class AId implements ImplRootId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("A"); // // private final long id; // // public AId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "AId [id=" + id + "]"; // } // // } // // Path: src/test/java/org/fuin/ddd4j/test/BId.java // public class BId implements EntityId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("B"); // // private final long id; // // public BId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "BId [id=" + id + "]"; // } // // } // // Path: src/test/java/org/fuin/ddd4j/test/CId.java // public class CId implements EntityId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("C"); // // private final long id; // // public CId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "CId [id=" + id + "]"; // } // // }
import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.fuin.ddd4j.test.AId; import org.fuin.ddd4j.test.BId; import org.fuin.ddd4j.test.CId; import org.fuin.objects4j.common.ConstraintViolationException; import org.junit.Test;
public void testConstructorListEmpty() { try { new EntityIdPath(new ArrayList<EntityId>()); fail(); } catch (ConstraintViolationException ex) { assertThat(ex.getMessage()).isEqualTo("Identifier list cannot be empty"); } } @Test public void testConstructorListNullValues() { try { final List<EntityId> list = new ArrayList<>(); list.add(null); new EntityIdPath(list); fail(); } catch (ConstraintViolationException ex) { assertThat(ex.getMessage()).isEqualTo("Identifiers in the list cannot be null"); } } @Test public void testIterator() { // PREPARE final AId aid = new AId(1L);
// Path: src/test/java/org/fuin/ddd4j/test/AId.java // public class AId implements ImplRootId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("A"); // // private final long id; // // public AId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "AId [id=" + id + "]"; // } // // } // // Path: src/test/java/org/fuin/ddd4j/test/BId.java // public class BId implements EntityId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("B"); // // private final long id; // // public BId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "BId [id=" + id + "]"; // } // // } // // Path: src/test/java/org/fuin/ddd4j/test/CId.java // public class CId implements EntityId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("C"); // // private final long id; // // public CId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "CId [id=" + id + "]"; // } // // } // Path: src/test/java/org/fuin/ddd4j/ddd/EntityIdPathTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.fuin.ddd4j.test.AId; import org.fuin.ddd4j.test.BId; import org.fuin.ddd4j.test.CId; import org.fuin.objects4j.common.ConstraintViolationException; import org.junit.Test; public void testConstructorListEmpty() { try { new EntityIdPath(new ArrayList<EntityId>()); fail(); } catch (ConstraintViolationException ex) { assertThat(ex.getMessage()).isEqualTo("Identifier list cannot be empty"); } } @Test public void testConstructorListNullValues() { try { final List<EntityId> list = new ArrayList<>(); list.add(null); new EntityIdPath(list); fail(); } catch (ConstraintViolationException ex) { assertThat(ex.getMessage()).isEqualTo("Identifiers in the list cannot be null"); } } @Test public void testIterator() { // PREPARE final AId aid = new AId(1L);
final BId bid = new BId(2L);
fuinorg/ddd-4-java
src/test/java/org/fuin/ddd4j/ddd/EntityIdPathTest.java
// Path: src/test/java/org/fuin/ddd4j/test/AId.java // public class AId implements ImplRootId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("A"); // // private final long id; // // public AId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "AId [id=" + id + "]"; // } // // } // // Path: src/test/java/org/fuin/ddd4j/test/BId.java // public class BId implements EntityId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("B"); // // private final long id; // // public BId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "BId [id=" + id + "]"; // } // // } // // Path: src/test/java/org/fuin/ddd4j/test/CId.java // public class CId implements EntityId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("C"); // // private final long id; // // public CId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "CId [id=" + id + "]"; // } // // }
import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.fuin.ddd4j.test.AId; import org.fuin.ddd4j.test.BId; import org.fuin.ddd4j.test.CId; import org.fuin.objects4j.common.ConstraintViolationException; import org.junit.Test;
try { new EntityIdPath(new ArrayList<EntityId>()); fail(); } catch (ConstraintViolationException ex) { assertThat(ex.getMessage()).isEqualTo("Identifier list cannot be empty"); } } @Test public void testConstructorListNullValues() { try { final List<EntityId> list = new ArrayList<>(); list.add(null); new EntityIdPath(list); fail(); } catch (ConstraintViolationException ex) { assertThat(ex.getMessage()).isEqualTo("Identifiers in the list cannot be null"); } } @Test public void testIterator() { // PREPARE final AId aid = new AId(1L); final BId bid = new BId(2L);
// Path: src/test/java/org/fuin/ddd4j/test/AId.java // public class AId implements ImplRootId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("A"); // // private final long id; // // public AId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "AId [id=" + id + "]"; // } // // } // // Path: src/test/java/org/fuin/ddd4j/test/BId.java // public class BId implements EntityId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("B"); // // private final long id; // // public BId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "BId [id=" + id + "]"; // } // // } // // Path: src/test/java/org/fuin/ddd4j/test/CId.java // public class CId implements EntityId { // // private static final long serialVersionUID = 1L; // // public static final EntityType TYPE = new StringBasedEntityType("C"); // // private final long id; // // public CId(final long id) { // this.id = id; // } // // @Override // public EntityType getType() { // return TYPE; // } // // @Override // public String asString() { // return "" + id; // } // // @Override // public String asTypedString() { // return getType() + " " + asString(); // } // // @Override // public String toString() { // return "CId [id=" + id + "]"; // } // // } // Path: src/test/java/org/fuin/ddd4j/ddd/EntityIdPathTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.fuin.ddd4j.test.AId; import org.fuin.ddd4j.test.BId; import org.fuin.ddd4j.test.CId; import org.fuin.objects4j.common.ConstraintViolationException; import org.junit.Test; try { new EntityIdPath(new ArrayList<EntityId>()); fail(); } catch (ConstraintViolationException ex) { assertThat(ex.getMessage()).isEqualTo("Identifier list cannot be empty"); } } @Test public void testConstructorListNullValues() { try { final List<EntityId> list = new ArrayList<>(); list.add(null); new EntityIdPath(list); fail(); } catch (ConstraintViolationException ex) { assertThat(ex.getMessage()).isEqualTo("Identifiers in the list cannot be null"); } } @Test public void testIterator() { // PREPARE final AId aid = new AId(1L); final BId bid = new BId(2L);
final CId cid = new CId(3L);
flaxsearch/harahachibu
harahachibu/src/test/java/uk/co/flax/harahachibu/servlets/DiskSpaceFilterTest.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceChecker.java // public interface DiskSpaceChecker { // // /** // * Check whether space is available on the disk or cluster of // * disks. // * @return {@code true} if space is available, {@code false} if not // * (including if server calls fail). // * @throws DiskSpaceCheckerException if problems occur checking the // * disks. // */ // boolean isSpaceAvailable() throws DiskSpaceCheckerException; // // /** // * Pass configuration properties into the checker instance, for custom // * checkers. // * @param configuration a {@link Map} of configuration details. // * @throws DiskSpaceCheckerException if the configuration cannot be read. // */ // void configure(Map<String, Object> configuration) throws DiskSpaceCheckerException; // // /** // * Does the implementation require an HTTP client for remote access? // * @return {@code true} if the checker requires HTTP access. // */ // boolean requiresHttpClient(); // // /** // * Set the HTTP client to use for remote access. This will be supplied and managed // * by DropWizard, avoiding the requirement to implement your own. // * @param httpClient the client to use. // */ // void setHttpClient(Client httpClient); // // /** // * Set the disk space threshold to use to check for available space. // * @param threshold the threshold. // */ // void setThreshold(DiskSpaceThreshold threshold); // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // }
import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.config.ProxyConfiguration; import uk.co.flax.harahachibu.services.DiskSpaceChecker; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import javax.servlet.FilterChain; import javax.servlet.RequestDispatcher; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Arrays; import java.util.List; import static org.mockito.Mockito.*;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.servlets; /** * Unit tests for the DiskSpaceFilter implementation. * * Created by mlp on 13/04/16. */ public class DiskSpaceFilterTest { private final DiskSpaceChecker checker = mock(DiskSpaceChecker.class);
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceChecker.java // public interface DiskSpaceChecker { // // /** // * Check whether space is available on the disk or cluster of // * disks. // * @return {@code true} if space is available, {@code false} if not // * (including if server calls fail). // * @throws DiskSpaceCheckerException if problems occur checking the // * disks. // */ // boolean isSpaceAvailable() throws DiskSpaceCheckerException; // // /** // * Pass configuration properties into the checker instance, for custom // * checkers. // * @param configuration a {@link Map} of configuration details. // * @throws DiskSpaceCheckerException if the configuration cannot be read. // */ // void configure(Map<String, Object> configuration) throws DiskSpaceCheckerException; // // /** // * Does the implementation require an HTTP client for remote access? // * @return {@code true} if the checker requires HTTP access. // */ // boolean requiresHttpClient(); // // /** // * Set the HTTP client to use for remote access. This will be supplied and managed // * by DropWizard, avoiding the requirement to implement your own. // * @param httpClient the client to use. // */ // void setHttpClient(Client httpClient); // // /** // * Set the disk space threshold to use to check for available space. // * @param threshold the threshold. // */ // void setThreshold(DiskSpaceThreshold threshold); // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // Path: harahachibu/src/test/java/uk/co/flax/harahachibu/servlets/DiskSpaceFilterTest.java import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.config.ProxyConfiguration; import uk.co.flax.harahachibu.services.DiskSpaceChecker; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import javax.servlet.FilterChain; import javax.servlet.RequestDispatcher; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Arrays; import java.util.List; import static org.mockito.Mockito.*; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.servlets; /** * Unit tests for the DiskSpaceFilter implementation. * * Created by mlp on 13/04/16. */ public class DiskSpaceFilterTest { private final DiskSpaceChecker checker = mock(DiskSpaceChecker.class);
private final ProxyConfiguration proxyConfig = mock(ProxyConfiguration.class);
flaxsearch/harahachibu
harahachibu/src/test/java/uk/co/flax/harahachibu/servlets/DiskSpaceFilterTest.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceChecker.java // public interface DiskSpaceChecker { // // /** // * Check whether space is available on the disk or cluster of // * disks. // * @return {@code true} if space is available, {@code false} if not // * (including if server calls fail). // * @throws DiskSpaceCheckerException if problems occur checking the // * disks. // */ // boolean isSpaceAvailable() throws DiskSpaceCheckerException; // // /** // * Pass configuration properties into the checker instance, for custom // * checkers. // * @param configuration a {@link Map} of configuration details. // * @throws DiskSpaceCheckerException if the configuration cannot be read. // */ // void configure(Map<String, Object> configuration) throws DiskSpaceCheckerException; // // /** // * Does the implementation require an HTTP client for remote access? // * @return {@code true} if the checker requires HTTP access. // */ // boolean requiresHttpClient(); // // /** // * Set the HTTP client to use for remote access. This will be supplied and managed // * by DropWizard, avoiding the requirement to implement your own. // * @param httpClient the client to use. // */ // void setHttpClient(Client httpClient); // // /** // * Set the disk space threshold to use to check for available space. // * @param threshold the threshold. // */ // void setThreshold(DiskSpaceThreshold threshold); // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // }
import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.config.ProxyConfiguration; import uk.co.flax.harahachibu.services.DiskSpaceChecker; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import javax.servlet.FilterChain; import javax.servlet.RequestDispatcher; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Arrays; import java.util.List; import static org.mockito.Mockito.*;
verify(req, atLeastOnce()).getRequestURI(); verify(chain).doFilter(req, response); } @Test public void proxyWithoutCheckingState() throws Exception { final String requestUri = "/solr/select"; final String requestQuery = "q=test"; final String proxiedUri = DiskSpaceProxyServlet.PROXY_PATH_PREFIX + "/solr/select?" + requestQuery; final RequestDispatcher dispatcher = mock(RequestDispatcher.class); final HttpServletRequest req = mock(HttpServletRequest.class); when(req.getRequestURI()).thenReturn(requestUri); when(req.getContextPath()).thenReturn(""); when(req.getQueryString()).thenReturn(requestQuery); when(req.getRequestDispatcher(proxiedUri)).thenReturn(dispatcher); final ServletResponse response = mock(ServletResponse.class); final FilterChain chain = mock(FilterChain.class); filter.doFilter(req, response, chain); verify(req, atLeastOnce()).getRequestURI(); verify(req, atLeastOnce()).getQueryString(); verify(req).getRequestDispatcher(proxiedUri); verify(dispatcher).forward(req, response); } @Test public void returnErrorWhenDiskCheckFails() throws Exception {
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceChecker.java // public interface DiskSpaceChecker { // // /** // * Check whether space is available on the disk or cluster of // * disks. // * @return {@code true} if space is available, {@code false} if not // * (including if server calls fail). // * @throws DiskSpaceCheckerException if problems occur checking the // * disks. // */ // boolean isSpaceAvailable() throws DiskSpaceCheckerException; // // /** // * Pass configuration properties into the checker instance, for custom // * checkers. // * @param configuration a {@link Map} of configuration details. // * @throws DiskSpaceCheckerException if the configuration cannot be read. // */ // void configure(Map<String, Object> configuration) throws DiskSpaceCheckerException; // // /** // * Does the implementation require an HTTP client for remote access? // * @return {@code true} if the checker requires HTTP access. // */ // boolean requiresHttpClient(); // // /** // * Set the HTTP client to use for remote access. This will be supplied and managed // * by DropWizard, avoiding the requirement to implement your own. // * @param httpClient the client to use. // */ // void setHttpClient(Client httpClient); // // /** // * Set the disk space threshold to use to check for available space. // * @param threshold the threshold. // */ // void setThreshold(DiskSpaceThreshold threshold); // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // Path: harahachibu/src/test/java/uk/co/flax/harahachibu/servlets/DiskSpaceFilterTest.java import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.config.ProxyConfiguration; import uk.co.flax.harahachibu.services.DiskSpaceChecker; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import javax.servlet.FilterChain; import javax.servlet.RequestDispatcher; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Arrays; import java.util.List; import static org.mockito.Mockito.*; verify(req, atLeastOnce()).getRequestURI(); verify(chain).doFilter(req, response); } @Test public void proxyWithoutCheckingState() throws Exception { final String requestUri = "/solr/select"; final String requestQuery = "q=test"; final String proxiedUri = DiskSpaceProxyServlet.PROXY_PATH_PREFIX + "/solr/select?" + requestQuery; final RequestDispatcher dispatcher = mock(RequestDispatcher.class); final HttpServletRequest req = mock(HttpServletRequest.class); when(req.getRequestURI()).thenReturn(requestUri); when(req.getContextPath()).thenReturn(""); when(req.getQueryString()).thenReturn(requestQuery); when(req.getRequestDispatcher(proxiedUri)).thenReturn(dispatcher); final ServletResponse response = mock(ServletResponse.class); final FilterChain chain = mock(FilterChain.class); filter.doFilter(req, response, chain); verify(req, atLeastOnce()).getRequestURI(); verify(req, atLeastOnce()).getQueryString(); verify(req).getRequestDispatcher(proxiedUri); verify(dispatcher).forward(req, response); } @Test public void returnErrorWhenDiskCheckFails() throws Exception {
when(checker.isSpaceAvailable()).thenThrow(new DiskSpaceCheckerException("Error"));
flaxsearch/harahachibu
harahachibu/src/test/java/uk/co/flax/harahachibu/health/ClusterDiskSpaceManagerHealthCheckTest.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // }
import com.codahale.metrics.health.HealthCheck; import org.junit.After; import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.data.DiskSpace; import java.util.*; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.health; /** * Unit tests for the ClusterDiskSpaceManagerHealthCheck. * <p> * Created by mlp on 19/04/16. */ public class ClusterDiskSpaceManagerHealthCheckTest { private final ClusterDiskSpaceManager manager = mock(ClusterDiskSpaceManager.class); private final String[] serverNames = new String[]{"server1", "server2"}; private final Set<String> servers = new LinkedHashSet<>(Arrays.asList(serverNames));
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // } // Path: harahachibu/src/test/java/uk/co/flax/harahachibu/health/ClusterDiskSpaceManagerHealthCheckTest.java import com.codahale.metrics.health.HealthCheck; import org.junit.After; import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.data.DiskSpace; import java.util.*; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.health; /** * Unit tests for the ClusterDiskSpaceManagerHealthCheck. * <p> * Created by mlp on 19/04/16. */ public class ClusterDiskSpaceManagerHealthCheckTest { private final ClusterDiskSpaceManager manager = mock(ClusterDiskSpaceManager.class); private final String[] serverNames = new String[]{"server1", "server2"}; private final Set<String> servers = new LinkedHashSet<>(Arrays.asList(serverNames));
private final Map<String, DiskSpace> diskSpaceMap = new HashMap<>();
flaxsearch/harahachibu
harahachibu/src/test/java/uk/co/flax/harahachibu/resources/SetSpaceResourceTest.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/api/SetSpaceResponse.java // public class SetSpaceResponse { // // public enum ResponseCode { // OK, ERROR // }; // // @JsonProperty("status") // private final ResponseCode responseCode; // @JsonProperty("message") // private final String message; // // public SetSpaceResponse(ResponseCode code, String message) { // this.responseCode = code; // this.message = message; // } // // public static SetSpaceResponse okResponse() { // return new SetSpaceResponse(ResponseCode.OK, null); // } // // public ResponseCode getResponseCode() { // return responseCode; // } // // public String getMessage() { // return message; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // }
import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.api.SetSpaceResponse; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.DiskSpace; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.resources; /** * Unit tests for the set space resource. * * Created by mlp on 18/04/16. */ public class SetSpaceResourceTest { private final ClusterDiskSpaceManager manager = mock(ClusterDiskSpaceManager.class); private SetSpaceResource resource; @Before public void setup() { resource = new SetSpaceResource(manager); } @Test public void returnsErrorOnException() throws Exception { final String server = "dummy";
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/api/SetSpaceResponse.java // public class SetSpaceResponse { // // public enum ResponseCode { // OK, ERROR // }; // // @JsonProperty("status") // private final ResponseCode responseCode; // @JsonProperty("message") // private final String message; // // public SetSpaceResponse(ResponseCode code, String message) { // this.responseCode = code; // this.message = message; // } // // public static SetSpaceResponse okResponse() { // return new SetSpaceResponse(ResponseCode.OK, null); // } // // public ResponseCode getResponseCode() { // return responseCode; // } // // public String getMessage() { // return message; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // } // Path: harahachibu/src/test/java/uk/co/flax/harahachibu/resources/SetSpaceResourceTest.java import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.api.SetSpaceResponse; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.DiskSpace; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.resources; /** * Unit tests for the set space resource. * * Created by mlp on 18/04/16. */ public class SetSpaceResourceTest { private final ClusterDiskSpaceManager manager = mock(ClusterDiskSpaceManager.class); private SetSpaceResource resource; @Before public void setup() { resource = new SetSpaceResource(manager); } @Test public void returnsErrorOnException() throws Exception { final String server = "dummy";
doThrow(new DiskSpaceCheckerException("Error")).when(manager).setDiskSpace(eq(server), isA(DiskSpace.class));
flaxsearch/harahachibu
harahachibu/src/test/java/uk/co/flax/harahachibu/resources/SetSpaceResourceTest.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/api/SetSpaceResponse.java // public class SetSpaceResponse { // // public enum ResponseCode { // OK, ERROR // }; // // @JsonProperty("status") // private final ResponseCode responseCode; // @JsonProperty("message") // private final String message; // // public SetSpaceResponse(ResponseCode code, String message) { // this.responseCode = code; // this.message = message; // } // // public static SetSpaceResponse okResponse() { // return new SetSpaceResponse(ResponseCode.OK, null); // } // // public ResponseCode getResponseCode() { // return responseCode; // } // // public String getMessage() { // return message; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // }
import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.api.SetSpaceResponse; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.DiskSpace; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.resources; /** * Unit tests for the set space resource. * * Created by mlp on 18/04/16. */ public class SetSpaceResourceTest { private final ClusterDiskSpaceManager manager = mock(ClusterDiskSpaceManager.class); private SetSpaceResource resource; @Before public void setup() { resource = new SetSpaceResource(manager); } @Test public void returnsErrorOnException() throws Exception { final String server = "dummy";
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/api/SetSpaceResponse.java // public class SetSpaceResponse { // // public enum ResponseCode { // OK, ERROR // }; // // @JsonProperty("status") // private final ResponseCode responseCode; // @JsonProperty("message") // private final String message; // // public SetSpaceResponse(ResponseCode code, String message) { // this.responseCode = code; // this.message = message; // } // // public static SetSpaceResponse okResponse() { // return new SetSpaceResponse(ResponseCode.OK, null); // } // // public ResponseCode getResponseCode() { // return responseCode; // } // // public String getMessage() { // return message; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // } // Path: harahachibu/src/test/java/uk/co/flax/harahachibu/resources/SetSpaceResourceTest.java import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.api.SetSpaceResponse; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.DiskSpace; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.resources; /** * Unit tests for the set space resource. * * Created by mlp on 18/04/16. */ public class SetSpaceResourceTest { private final ClusterDiskSpaceManager manager = mock(ClusterDiskSpaceManager.class); private SetSpaceResource resource; @Before public void setup() { resource = new SetSpaceResource(manager); } @Test public void returnsErrorOnException() throws Exception { final String server = "dummy";
doThrow(new DiskSpaceCheckerException("Error")).when(manager).setDiskSpace(eq(server), isA(DiskSpace.class));
flaxsearch/harahachibu
harahachibu/src/test/java/uk/co/flax/harahachibu/resources/SetSpaceResourceTest.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/api/SetSpaceResponse.java // public class SetSpaceResponse { // // public enum ResponseCode { // OK, ERROR // }; // // @JsonProperty("status") // private final ResponseCode responseCode; // @JsonProperty("message") // private final String message; // // public SetSpaceResponse(ResponseCode code, String message) { // this.responseCode = code; // this.message = message; // } // // public static SetSpaceResponse okResponse() { // return new SetSpaceResponse(ResponseCode.OK, null); // } // // public ResponseCode getResponseCode() { // return responseCode; // } // // public String getMessage() { // return message; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // }
import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.api.SetSpaceResponse; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.DiskSpace; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.resources; /** * Unit tests for the set space resource. * * Created by mlp on 18/04/16. */ public class SetSpaceResourceTest { private final ClusterDiskSpaceManager manager = mock(ClusterDiskSpaceManager.class); private SetSpaceResource resource; @Before public void setup() { resource = new SetSpaceResource(manager); } @Test public void returnsErrorOnException() throws Exception { final String server = "dummy"; doThrow(new DiskSpaceCheckerException("Error")).when(manager).setDiskSpace(eq(server), isA(DiskSpace.class));
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/api/SetSpaceResponse.java // public class SetSpaceResponse { // // public enum ResponseCode { // OK, ERROR // }; // // @JsonProperty("status") // private final ResponseCode responseCode; // @JsonProperty("message") // private final String message; // // public SetSpaceResponse(ResponseCode code, String message) { // this.responseCode = code; // this.message = message; // } // // public static SetSpaceResponse okResponse() { // return new SetSpaceResponse(ResponseCode.OK, null); // } // // public ResponseCode getResponseCode() { // return responseCode; // } // // public String getMessage() { // return message; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // } // Path: harahachibu/src/test/java/uk/co/flax/harahachibu/resources/SetSpaceResourceTest.java import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.api.SetSpaceResponse; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.DiskSpace; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.resources; /** * Unit tests for the set space resource. * * Created by mlp on 18/04/16. */ public class SetSpaceResourceTest { private final ClusterDiskSpaceManager manager = mock(ClusterDiskSpaceManager.class); private SetSpaceResource resource; @Before public void setup() { resource = new SetSpaceResource(manager); } @Test public void returnsErrorOnException() throws Exception { final String server = "dummy"; doThrow(new DiskSpaceCheckerException("Error")).when(manager).setDiskSpace(eq(server), isA(DiskSpace.class));
SetSpaceResponse response = resource.handlePost(server, 128L, 1024L);
flaxsearch/harahachibu
harahachibu/src/test/java/uk/co/flax/harahachibu/health/DiskSpaceCheckerHealthCheckTest.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceChecker.java // public interface DiskSpaceChecker { // // /** // * Check whether space is available on the disk or cluster of // * disks. // * @return {@code true} if space is available, {@code false} if not // * (including if server calls fail). // * @throws DiskSpaceCheckerException if problems occur checking the // * disks. // */ // boolean isSpaceAvailable() throws DiskSpaceCheckerException; // // /** // * Pass configuration properties into the checker instance, for custom // * checkers. // * @param configuration a {@link Map} of configuration details. // * @throws DiskSpaceCheckerException if the configuration cannot be read. // */ // void configure(Map<String, Object> configuration) throws DiskSpaceCheckerException; // // /** // * Does the implementation require an HTTP client for remote access? // * @return {@code true} if the checker requires HTTP access. // */ // boolean requiresHttpClient(); // // /** // * Set the HTTP client to use for remote access. This will be supplied and managed // * by DropWizard, avoiding the requirement to implement your own. // * @param httpClient the client to use. // */ // void setHttpClient(Client httpClient); // // /** // * Set the disk space threshold to use to check for available space. // * @param threshold the threshold. // */ // void setThreshold(DiskSpaceThreshold threshold); // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // }
import com.codahale.metrics.health.HealthCheck; import com.codahale.metrics.health.HealthCheck.Result; import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.services.DiskSpaceChecker; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.health; /** * Unit tests for the generic disk space checker healthcheck. * * Created by mlp on 19/04/16. */ public class DiskSpaceCheckerHealthCheckTest { private final DiskSpaceChecker checker = mock(DiskSpaceChecker.class); private DiskSpaceCheckerHealthCheck healthCheck; @Before public void setup() { healthCheck = new DiskSpaceCheckerHealthCheck(checker); } @Test public void returnsUnhealthyWhenCheckerThrowsException() throws Exception {
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceChecker.java // public interface DiskSpaceChecker { // // /** // * Check whether space is available on the disk or cluster of // * disks. // * @return {@code true} if space is available, {@code false} if not // * (including if server calls fail). // * @throws DiskSpaceCheckerException if problems occur checking the // * disks. // */ // boolean isSpaceAvailable() throws DiskSpaceCheckerException; // // /** // * Pass configuration properties into the checker instance, for custom // * checkers. // * @param configuration a {@link Map} of configuration details. // * @throws DiskSpaceCheckerException if the configuration cannot be read. // */ // void configure(Map<String, Object> configuration) throws DiskSpaceCheckerException; // // /** // * Does the implementation require an HTTP client for remote access? // * @return {@code true} if the checker requires HTTP access. // */ // boolean requiresHttpClient(); // // /** // * Set the HTTP client to use for remote access. This will be supplied and managed // * by DropWizard, avoiding the requirement to implement your own. // * @param httpClient the client to use. // */ // void setHttpClient(Client httpClient); // // /** // * Set the disk space threshold to use to check for available space. // * @param threshold the threshold. // */ // void setThreshold(DiskSpaceThreshold threshold); // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // Path: harahachibu/src/test/java/uk/co/flax/harahachibu/health/DiskSpaceCheckerHealthCheckTest.java import com.codahale.metrics.health.HealthCheck; import com.codahale.metrics.health.HealthCheck.Result; import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.services.DiskSpaceChecker; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.health; /** * Unit tests for the generic disk space checker healthcheck. * * Created by mlp on 19/04/16. */ public class DiskSpaceCheckerHealthCheckTest { private final DiskSpaceChecker checker = mock(DiskSpaceChecker.class); private DiskSpaceCheckerHealthCheck healthCheck; @Before public void setup() { healthCheck = new DiskSpaceCheckerHealthCheck(checker); } @Test public void returnsUnhealthyWhenCheckerThrowsException() throws Exception {
when(checker.isSpaceAvailable()).thenThrow(new DiskSpaceCheckerException("Error"));
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/health/ElasticsearchClientHealthCheck.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/ElasticsearchClusterStats.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class ElasticsearchClusterStats { // // @JsonProperty("timestamp") // private final long timestamp; // // @JsonProperty("cluster_name") // private final String clusterName; // // @JsonProperty("status") // private final String status; // // @JsonProperty(value = "nodes") // private final ElasticsearchClusterNodes nodes; // // public ElasticsearchClusterStats(@JsonProperty("timestamp") long timestamp, // @JsonProperty("cluster_name") String clusterName, // @JsonProperty("status") String status, // @JsonProperty("nodes") ElasticsearchClusterNodes nodes) { // this.timestamp = timestamp; // this.clusterName = clusterName; // this.status = status; // this.nodes = nodes; // } // // public long getTimestamp() { // return timestamp; // } // // public String getClusterName() { // return clusterName; // } // // public String getStatus() { // return status; // } // // public ElasticsearchClusterNodes getNodes() { // return nodes; // } // // public long getFilesystemFreeBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getFreeBytes(); // } // return 0; // } // // public long getFilesystemAvailableBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getAvailableBytes(); // } // return 0; // } // // public long getFilesystemTotalBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getTotalBytes(); // } // return 0; // } // // private ElasticsearchClusterFilesystem getFilesystem() { // if (nodes != null) { // return nodes.getFileSystem(); // } // return null; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/impl/ElasticsearchClient.java // public class ElasticsearchClient { // // private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchClient.class); // // static final String CLUSTER_STATS_ENDPOINT = "/_cluster/stats"; // // private final Client client; // private final String baseUrl; // private final long cacheMs; // // private ElasticsearchClusterStats latestStats; // private long lastUpdate; // // private final Object statsLock = new Object(); // // public ElasticsearchClient(Client client, String baseUrl, long cacheMs) { // this.client = client; // this.baseUrl = baseUrl; // this.cacheMs = cacheMs; // } // // public ElasticsearchClusterStats getClusterStats() throws DiskSpaceCheckerException { // final ElasticsearchClusterStats stats; // // if (cacheUpToDate()) { // stats = latestStats; // } else { // stats = getRemoteClusterStats(); // synchronized (statsLock) { // this.latestStats = stats; // this.lastUpdate = System.currentTimeMillis(); // } // } // // return stats; // } // // private boolean cacheUpToDate() { // return latestStats != null && lastUpdate > (System.currentTimeMillis() - cacheMs); // } // // private ElasticsearchClusterStats getRemoteClusterStats() throws DiskSpaceCheckerException { // try { // LOGGER.debug("Retrieving stats from cluster"); // return client.target(baseUrl + CLUSTER_STATS_ENDPOINT) // .request(MediaType.APPLICATION_JSON) // .buildGet() // .invoke(ElasticsearchClusterStats.class); // } catch (Exception e) { // LOGGER.error("Exception thrown getting cluster stats from {}: {}", baseUrl, e.getMessage()); // throw new DiskSpaceCheckerException(e); // } // } // // }
import com.codahale.metrics.health.HealthCheck; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.ElasticsearchClusterStats; import uk.co.flax.harahachibu.services.impl.ElasticsearchClient;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.health; /** * Healthcheck for the Elasticsearch Client class. * * Created by mlp on 19/04/16. */ public class ElasticsearchClientHealthCheck extends HealthCheck { private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchClientHealthCheck.class); private static final String CLUSTER_HEALTH_MSG = "Cluster status: %s";
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/ElasticsearchClusterStats.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class ElasticsearchClusterStats { // // @JsonProperty("timestamp") // private final long timestamp; // // @JsonProperty("cluster_name") // private final String clusterName; // // @JsonProperty("status") // private final String status; // // @JsonProperty(value = "nodes") // private final ElasticsearchClusterNodes nodes; // // public ElasticsearchClusterStats(@JsonProperty("timestamp") long timestamp, // @JsonProperty("cluster_name") String clusterName, // @JsonProperty("status") String status, // @JsonProperty("nodes") ElasticsearchClusterNodes nodes) { // this.timestamp = timestamp; // this.clusterName = clusterName; // this.status = status; // this.nodes = nodes; // } // // public long getTimestamp() { // return timestamp; // } // // public String getClusterName() { // return clusterName; // } // // public String getStatus() { // return status; // } // // public ElasticsearchClusterNodes getNodes() { // return nodes; // } // // public long getFilesystemFreeBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getFreeBytes(); // } // return 0; // } // // public long getFilesystemAvailableBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getAvailableBytes(); // } // return 0; // } // // public long getFilesystemTotalBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getTotalBytes(); // } // return 0; // } // // private ElasticsearchClusterFilesystem getFilesystem() { // if (nodes != null) { // return nodes.getFileSystem(); // } // return null; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/impl/ElasticsearchClient.java // public class ElasticsearchClient { // // private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchClient.class); // // static final String CLUSTER_STATS_ENDPOINT = "/_cluster/stats"; // // private final Client client; // private final String baseUrl; // private final long cacheMs; // // private ElasticsearchClusterStats latestStats; // private long lastUpdate; // // private final Object statsLock = new Object(); // // public ElasticsearchClient(Client client, String baseUrl, long cacheMs) { // this.client = client; // this.baseUrl = baseUrl; // this.cacheMs = cacheMs; // } // // public ElasticsearchClusterStats getClusterStats() throws DiskSpaceCheckerException { // final ElasticsearchClusterStats stats; // // if (cacheUpToDate()) { // stats = latestStats; // } else { // stats = getRemoteClusterStats(); // synchronized (statsLock) { // this.latestStats = stats; // this.lastUpdate = System.currentTimeMillis(); // } // } // // return stats; // } // // private boolean cacheUpToDate() { // return latestStats != null && lastUpdate > (System.currentTimeMillis() - cacheMs); // } // // private ElasticsearchClusterStats getRemoteClusterStats() throws DiskSpaceCheckerException { // try { // LOGGER.debug("Retrieving stats from cluster"); // return client.target(baseUrl + CLUSTER_STATS_ENDPOINT) // .request(MediaType.APPLICATION_JSON) // .buildGet() // .invoke(ElasticsearchClusterStats.class); // } catch (Exception e) { // LOGGER.error("Exception thrown getting cluster stats from {}: {}", baseUrl, e.getMessage()); // throw new DiskSpaceCheckerException(e); // } // } // // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/health/ElasticsearchClientHealthCheck.java import com.codahale.metrics.health.HealthCheck; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.ElasticsearchClusterStats; import uk.co.flax.harahachibu.services.impl.ElasticsearchClient; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.health; /** * Healthcheck for the Elasticsearch Client class. * * Created by mlp on 19/04/16. */ public class ElasticsearchClientHealthCheck extends HealthCheck { private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchClientHealthCheck.class); private static final String CLUSTER_HEALTH_MSG = "Cluster status: %s";
private final ElasticsearchClient client;
flaxsearch/harahachibu
harahachibu/src/test/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManagerTest.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // }
import org.junit.Test; import uk.co.flax.harahachibu.services.data.DiskSpace; import java.util.Collections; import java.util.HashSet; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.services; /** * Unit tests for the ClusterDiskSpaceManager. * Created by mlp on 18/04/16. */ public class ClusterDiskSpaceManagerTest { private static final String TEST_SERVER = "test.localhost"; private final Set<String> servers = new HashSet<>(Collections.singleton(TEST_SERVER)); private final ClusterDiskSpaceManager manager = new ClusterDiskSpaceManager(servers); @Test(expected = uk.co.flax.harahachibu.services.DiskSpaceCheckerException.class) public void throwsExceptionWhenServerNotKnown() throws Exception {
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // } // Path: harahachibu/src/test/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManagerTest.java import org.junit.Test; import uk.co.flax.harahachibu.services.data.DiskSpace; import java.util.Collections; import java.util.HashSet; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.services; /** * Unit tests for the ClusterDiskSpaceManager. * Created by mlp on 18/04/16. */ public class ClusterDiskSpaceManagerTest { private static final String TEST_SERVER = "test.localhost"; private final Set<String> servers = new HashSet<>(Collections.singleton(TEST_SERVER)); private final ClusterDiskSpaceManager manager = new ClusterDiskSpaceManager(servers); @Test(expected = uk.co.flax.harahachibu.services.DiskSpaceCheckerException.class) public void throwsExceptionWhenServerNotKnown() throws Exception {
manager.setDiskSpace("blah", new DiskSpace(0, 0));
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // }
import uk.co.flax.harahachibu.services.data.DiskSpace; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.services; /** * Manager class for tracking disk space across a cluster. * * Created by mlp on 18/04/16. */ public class ClusterDiskSpaceManager { private final Set<String> servers;
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java import uk.co.flax.harahachibu.services.data.DiskSpace; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.services; /** * Manager class for tracking disk space across a cluster. * * Created by mlp on 18/04/16. */ public class ClusterDiskSpaceManager { private final Set<String> servers;
private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>();
flaxsearch/harahachibu
harahachibu/src/test/java/uk/co/flax/harahachibu/services/impl/ElasticsearchClientTest.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/ElasticsearchClusterStats.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class ElasticsearchClusterStats { // // @JsonProperty("timestamp") // private final long timestamp; // // @JsonProperty("cluster_name") // private final String clusterName; // // @JsonProperty("status") // private final String status; // // @JsonProperty(value = "nodes") // private final ElasticsearchClusterNodes nodes; // // public ElasticsearchClusterStats(@JsonProperty("timestamp") long timestamp, // @JsonProperty("cluster_name") String clusterName, // @JsonProperty("status") String status, // @JsonProperty("nodes") ElasticsearchClusterNodes nodes) { // this.timestamp = timestamp; // this.clusterName = clusterName; // this.status = status; // this.nodes = nodes; // } // // public long getTimestamp() { // return timestamp; // } // // public String getClusterName() { // return clusterName; // } // // public String getStatus() { // return status; // } // // public ElasticsearchClusterNodes getNodes() { // return nodes; // } // // public long getFilesystemFreeBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getFreeBytes(); // } // return 0; // } // // public long getFilesystemAvailableBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getAvailableBytes(); // } // return 0; // } // // public long getFilesystemTotalBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getTotalBytes(); // } // return 0; // } // // private ElasticsearchClusterFilesystem getFilesystem() { // if (nodes != null) { // return nodes.getFileSystem(); // } // return null; // } // // }
import com.codahale.metrics.MetricRegistry; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; import io.dropwizard.setup.Environment; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockserver.client.server.MockServerClient; import org.mockserver.model.Header; import org.mockserver.model.JsonBody; import org.mockserver.verify.VerificationTimes; import uk.co.flax.harahachibu.services.data.ElasticsearchClusterStats; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.client.Client; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; import static org.mockserver.integration.ClientAndServer.startClientAndServer; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response;
esClient.getClusterStats(); } @Test(expected = uk.co.flax.harahachibu.services.DiskSpaceCheckerException.class) public void throwsExceptionWhenServerNotRunning() throws Exception { mockServer.stop(); esClient.getClusterStats(); } @Test(expected = uk.co.flax.harahachibu.services.DiskSpaceCheckerException.class) public void throwsExceptionWhenServerTimesOut() throws Exception { // Default DW Jersey client timeout is 500ms mockServer.when(request().withPath(ElasticsearchClient.CLUSTER_STATS_ENDPOINT)) .respond(response() .withDelay(TimeUnit.SECONDS, 5) .withBody(new JsonBody(clusterStatsJson)) .withHeaders(new Header("Content-Type", "application/json")) .withStatusCode(HttpServletResponse.SC_OK)); esClient.getClusterStats(); } @Test public void returnsClusterStats() throws Exception { mockServer.when(request().withPath(ElasticsearchClient.CLUSTER_STATS_ENDPOINT)) .respond(response() .withBody(new JsonBody(clusterStatsJson)) .withHeaders(new Header("Content-Type", "application/json")) .withStatusCode(HttpServletResponse.SC_OK));
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/ElasticsearchClusterStats.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class ElasticsearchClusterStats { // // @JsonProperty("timestamp") // private final long timestamp; // // @JsonProperty("cluster_name") // private final String clusterName; // // @JsonProperty("status") // private final String status; // // @JsonProperty(value = "nodes") // private final ElasticsearchClusterNodes nodes; // // public ElasticsearchClusterStats(@JsonProperty("timestamp") long timestamp, // @JsonProperty("cluster_name") String clusterName, // @JsonProperty("status") String status, // @JsonProperty("nodes") ElasticsearchClusterNodes nodes) { // this.timestamp = timestamp; // this.clusterName = clusterName; // this.status = status; // this.nodes = nodes; // } // // public long getTimestamp() { // return timestamp; // } // // public String getClusterName() { // return clusterName; // } // // public String getStatus() { // return status; // } // // public ElasticsearchClusterNodes getNodes() { // return nodes; // } // // public long getFilesystemFreeBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getFreeBytes(); // } // return 0; // } // // public long getFilesystemAvailableBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getAvailableBytes(); // } // return 0; // } // // public long getFilesystemTotalBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getTotalBytes(); // } // return 0; // } // // private ElasticsearchClusterFilesystem getFilesystem() { // if (nodes != null) { // return nodes.getFileSystem(); // } // return null; // } // // } // Path: harahachibu/src/test/java/uk/co/flax/harahachibu/services/impl/ElasticsearchClientTest.java import com.codahale.metrics.MetricRegistry; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; import io.dropwizard.setup.Environment; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockserver.client.server.MockServerClient; import org.mockserver.model.Header; import org.mockserver.model.JsonBody; import org.mockserver.verify.VerificationTimes; import uk.co.flax.harahachibu.services.data.ElasticsearchClusterStats; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.client.Client; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; import static org.mockserver.integration.ClientAndServer.startClientAndServer; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; esClient.getClusterStats(); } @Test(expected = uk.co.flax.harahachibu.services.DiskSpaceCheckerException.class) public void throwsExceptionWhenServerNotRunning() throws Exception { mockServer.stop(); esClient.getClusterStats(); } @Test(expected = uk.co.flax.harahachibu.services.DiskSpaceCheckerException.class) public void throwsExceptionWhenServerTimesOut() throws Exception { // Default DW Jersey client timeout is 500ms mockServer.when(request().withPath(ElasticsearchClient.CLUSTER_STATS_ENDPOINT)) .respond(response() .withDelay(TimeUnit.SECONDS, 5) .withBody(new JsonBody(clusterStatsJson)) .withHeaders(new Header("Content-Type", "application/json")) .withStatusCode(HttpServletResponse.SC_OK)); esClient.getClusterStats(); } @Test public void returnsClusterStats() throws Exception { mockServer.when(request().withPath(ElasticsearchClient.CLUSTER_STATS_ENDPOINT)) .respond(response() .withBody(new JsonBody(clusterStatsJson)) .withHeaders(new Header("Content-Type", "application/json")) .withStatusCode(HttpServletResponse.SC_OK));
ElasticsearchClusterStats clusterStats = esClient.getClusterStats();
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/servlets/DiskSpaceFilter.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceChecker.java // public interface DiskSpaceChecker { // // /** // * Check whether space is available on the disk or cluster of // * disks. // * @return {@code true} if space is available, {@code false} if not // * (including if server calls fail). // * @throws DiskSpaceCheckerException if problems occur checking the // * disks. // */ // boolean isSpaceAvailable() throws DiskSpaceCheckerException; // // /** // * Pass configuration properties into the checker instance, for custom // * checkers. // * @param configuration a {@link Map} of configuration details. // * @throws DiskSpaceCheckerException if the configuration cannot be read. // */ // void configure(Map<String, Object> configuration) throws DiskSpaceCheckerException; // // /** // * Does the implementation require an HTTP client for remote access? // * @return {@code true} if the checker requires HTTP access. // */ // boolean requiresHttpClient(); // // /** // * Set the HTTP client to use for remote access. This will be supplied and managed // * by DropWizard, avoiding the requirement to implement your own. // * @param httpClient the client to use. // */ // void setHttpClient(Client httpClient); // // /** // * Set the disk space threshold to use to check for available space. // * @param threshold the threshold. // */ // void setThreshold(DiskSpaceThreshold threshold); // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.config.ProxyConfiguration; import uk.co.flax.harahachibu.services.DiskSpaceChecker; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.servlets; /** * Filter run on all incoming requests. * <p> * <p> * There are a number of paths through the filter: * </p> * <p> * <ul> * <li>if the request is for a local resource, it is passed straight through;</li> * <li>if the request is not for a local resource, it is checked to see if it is a * path that requires a disk space check. If so, the check is run. If the check passes, * the URI path is modified to start with "/proxy", and passed through, otherwise a * 500 status code is set in the response.</li> * </ul> * <p> * Created by mlp on 13/04/16. */ public class DiskSpaceFilter implements Filter { private static final Logger LOGGER = LoggerFactory.getLogger(DiskSpaceFilter.class);
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceChecker.java // public interface DiskSpaceChecker { // // /** // * Check whether space is available on the disk or cluster of // * disks. // * @return {@code true} if space is available, {@code false} if not // * (including if server calls fail). // * @throws DiskSpaceCheckerException if problems occur checking the // * disks. // */ // boolean isSpaceAvailable() throws DiskSpaceCheckerException; // // /** // * Pass configuration properties into the checker instance, for custom // * checkers. // * @param configuration a {@link Map} of configuration details. // * @throws DiskSpaceCheckerException if the configuration cannot be read. // */ // void configure(Map<String, Object> configuration) throws DiskSpaceCheckerException; // // /** // * Does the implementation require an HTTP client for remote access? // * @return {@code true} if the checker requires HTTP access. // */ // boolean requiresHttpClient(); // // /** // * Set the HTTP client to use for remote access. This will be supplied and managed // * by DropWizard, avoiding the requirement to implement your own. // * @param httpClient the client to use. // */ // void setHttpClient(Client httpClient); // // /** // * Set the disk space threshold to use to check for available space. // * @param threshold the threshold. // */ // void setThreshold(DiskSpaceThreshold threshold); // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/servlets/DiskSpaceFilter.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.config.ProxyConfiguration; import uk.co.flax.harahachibu.services.DiskSpaceChecker; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.servlets; /** * Filter run on all incoming requests. * <p> * <p> * There are a number of paths through the filter: * </p> * <p> * <ul> * <li>if the request is for a local resource, it is passed straight through;</li> * <li>if the request is not for a local resource, it is checked to see if it is a * path that requires a disk space check. If so, the check is run. If the check passes, * the URI path is modified to start with "/proxy", and passed through, otherwise a * 500 status code is set in the response.</li> * </ul> * <p> * Created by mlp on 13/04/16. */ public class DiskSpaceFilter implements Filter { private static final Logger LOGGER = LoggerFactory.getLogger(DiskSpaceFilter.class);
private final DiskSpaceChecker spaceChecker;
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/servlets/DiskSpaceFilter.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceChecker.java // public interface DiskSpaceChecker { // // /** // * Check whether space is available on the disk or cluster of // * disks. // * @return {@code true} if space is available, {@code false} if not // * (including if server calls fail). // * @throws DiskSpaceCheckerException if problems occur checking the // * disks. // */ // boolean isSpaceAvailable() throws DiskSpaceCheckerException; // // /** // * Pass configuration properties into the checker instance, for custom // * checkers. // * @param configuration a {@link Map} of configuration details. // * @throws DiskSpaceCheckerException if the configuration cannot be read. // */ // void configure(Map<String, Object> configuration) throws DiskSpaceCheckerException; // // /** // * Does the implementation require an HTTP client for remote access? // * @return {@code true} if the checker requires HTTP access. // */ // boolean requiresHttpClient(); // // /** // * Set the HTTP client to use for remote access. This will be supplied and managed // * by DropWizard, avoiding the requirement to implement your own. // * @param httpClient the client to use. // */ // void setHttpClient(Client httpClient); // // /** // * Set the disk space threshold to use to check for available space. // * @param threshold the threshold. // */ // void setThreshold(DiskSpaceThreshold threshold); // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.config.ProxyConfiguration; import uk.co.flax.harahachibu.services.DiskSpaceChecker; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.servlets; /** * Filter run on all incoming requests. * <p> * <p> * There are a number of paths through the filter: * </p> * <p> * <ul> * <li>if the request is for a local resource, it is passed straight through;</li> * <li>if the request is not for a local resource, it is checked to see if it is a * path that requires a disk space check. If so, the check is run. If the check passes, * the URI path is modified to start with "/proxy", and passed through, otherwise a * 500 status code is set in the response.</li> * </ul> * <p> * Created by mlp on 13/04/16. */ public class DiskSpaceFilter implements Filter { private static final Logger LOGGER = LoggerFactory.getLogger(DiskSpaceFilter.class); private final DiskSpaceChecker spaceChecker;
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceChecker.java // public interface DiskSpaceChecker { // // /** // * Check whether space is available on the disk or cluster of // * disks. // * @return {@code true} if space is available, {@code false} if not // * (including if server calls fail). // * @throws DiskSpaceCheckerException if problems occur checking the // * disks. // */ // boolean isSpaceAvailable() throws DiskSpaceCheckerException; // // /** // * Pass configuration properties into the checker instance, for custom // * checkers. // * @param configuration a {@link Map} of configuration details. // * @throws DiskSpaceCheckerException if the configuration cannot be read. // */ // void configure(Map<String, Object> configuration) throws DiskSpaceCheckerException; // // /** // * Does the implementation require an HTTP client for remote access? // * @return {@code true} if the checker requires HTTP access. // */ // boolean requiresHttpClient(); // // /** // * Set the HTTP client to use for remote access. This will be supplied and managed // * by DropWizard, avoiding the requirement to implement your own. // * @param httpClient the client to use. // */ // void setHttpClient(Client httpClient); // // /** // * Set the disk space threshold to use to check for available space. // * @param threshold the threshold. // */ // void setThreshold(DiskSpaceThreshold threshold); // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/servlets/DiskSpaceFilter.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.config.ProxyConfiguration; import uk.co.flax.harahachibu.services.DiskSpaceChecker; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.servlets; /** * Filter run on all incoming requests. * <p> * <p> * There are a number of paths through the filter: * </p> * <p> * <ul> * <li>if the request is for a local resource, it is passed straight through;</li> * <li>if the request is not for a local resource, it is checked to see if it is a * path that requires a disk space check. If so, the check is run. If the check passes, * the URI path is modified to start with "/proxy", and passed through, otherwise a * 500 status code is set in the response.</li> * </ul> * <p> * Created by mlp on 13/04/16. */ public class DiskSpaceFilter implements Filter { private static final Logger LOGGER = LoggerFactory.getLogger(DiskSpaceFilter.class); private final DiskSpaceChecker spaceChecker;
private final ProxyConfiguration proxyConfiguration;
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/servlets/DiskSpaceFilter.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceChecker.java // public interface DiskSpaceChecker { // // /** // * Check whether space is available on the disk or cluster of // * disks. // * @return {@code true} if space is available, {@code false} if not // * (including if server calls fail). // * @throws DiskSpaceCheckerException if problems occur checking the // * disks. // */ // boolean isSpaceAvailable() throws DiskSpaceCheckerException; // // /** // * Pass configuration properties into the checker instance, for custom // * checkers. // * @param configuration a {@link Map} of configuration details. // * @throws DiskSpaceCheckerException if the configuration cannot be read. // */ // void configure(Map<String, Object> configuration) throws DiskSpaceCheckerException; // // /** // * Does the implementation require an HTTP client for remote access? // * @return {@code true} if the checker requires HTTP access. // */ // boolean requiresHttpClient(); // // /** // * Set the HTTP client to use for remote access. This will be supplied and managed // * by DropWizard, avoiding the requirement to implement your own. // * @param httpClient the client to use. // */ // void setHttpClient(Client httpClient); // // /** // * Set the disk space threshold to use to check for available space. // * @param threshold the threshold. // */ // void setThreshold(DiskSpaceThreshold threshold); // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.config.ProxyConfiguration; import uk.co.flax.harahachibu.services.DiskSpaceChecker; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.servlets; /** * Filter run on all incoming requests. * <p> * <p> * There are a number of paths through the filter: * </p> * <p> * <ul> * <li>if the request is for a local resource, it is passed straight through;</li> * <li>if the request is not for a local resource, it is checked to see if it is a * path that requires a disk space check. If so, the check is run. If the check passes, * the URI path is modified to start with "/proxy", and passed through, otherwise a * 500 status code is set in the response.</li> * </ul> * <p> * Created by mlp on 13/04/16. */ public class DiskSpaceFilter implements Filter { private static final Logger LOGGER = LoggerFactory.getLogger(DiskSpaceFilter.class); private final DiskSpaceChecker spaceChecker; private final ProxyConfiguration proxyConfiguration; private final String[] localPaths; public DiskSpaceFilter(DiskSpaceChecker spaceChecker, ProxyConfiguration proxyConfiguration, String... localPaths) { this.spaceChecker = spaceChecker; this.proxyConfiguration = proxyConfiguration; this.localPaths = localPaths; } @Override public void init(FilterConfig filterConfig) throws ServletException { LOGGER.info("Initialising DiskSpaceFilter..."); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; if (isUriInLocalPaths(httpRequest)) { // Ignore and pass through LOGGER.debug("Passing through request for {}", httpRequest.getRequestURI()); chain.doFilter(request, response); } else { if (isUriInCheckPaths(httpRequest)) { // Check the server state try { if (!spaceChecker.isSpaceAvailable()) { ((HttpServletResponse) response).sendError(proxyConfiguration.getErrorStatus()); }
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceChecker.java // public interface DiskSpaceChecker { // // /** // * Check whether space is available on the disk or cluster of // * disks. // * @return {@code true} if space is available, {@code false} if not // * (including if server calls fail). // * @throws DiskSpaceCheckerException if problems occur checking the // * disks. // */ // boolean isSpaceAvailable() throws DiskSpaceCheckerException; // // /** // * Pass configuration properties into the checker instance, for custom // * checkers. // * @param configuration a {@link Map} of configuration details. // * @throws DiskSpaceCheckerException if the configuration cannot be read. // */ // void configure(Map<String, Object> configuration) throws DiskSpaceCheckerException; // // /** // * Does the implementation require an HTTP client for remote access? // * @return {@code true} if the checker requires HTTP access. // */ // boolean requiresHttpClient(); // // /** // * Set the HTTP client to use for remote access. This will be supplied and managed // * by DropWizard, avoiding the requirement to implement your own. // * @param httpClient the client to use. // */ // void setHttpClient(Client httpClient); // // /** // * Set the disk space threshold to use to check for available space. // * @param threshold the threshold. // */ // void setThreshold(DiskSpaceThreshold threshold); // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/servlets/DiskSpaceFilter.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.config.ProxyConfiguration; import uk.co.flax.harahachibu.services.DiskSpaceChecker; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.servlets; /** * Filter run on all incoming requests. * <p> * <p> * There are a number of paths through the filter: * </p> * <p> * <ul> * <li>if the request is for a local resource, it is passed straight through;</li> * <li>if the request is not for a local resource, it is checked to see if it is a * path that requires a disk space check. If so, the check is run. If the check passes, * the URI path is modified to start with "/proxy", and passed through, otherwise a * 500 status code is set in the response.</li> * </ul> * <p> * Created by mlp on 13/04/16. */ public class DiskSpaceFilter implements Filter { private static final Logger LOGGER = LoggerFactory.getLogger(DiskSpaceFilter.class); private final DiskSpaceChecker spaceChecker; private final ProxyConfiguration proxyConfiguration; private final String[] localPaths; public DiskSpaceFilter(DiskSpaceChecker spaceChecker, ProxyConfiguration proxyConfiguration, String... localPaths) { this.spaceChecker = spaceChecker; this.proxyConfiguration = proxyConfiguration; this.localPaths = localPaths; } @Override public void init(FilterConfig filterConfig) throws ServletException { LOGGER.info("Initialising DiskSpaceFilter..."); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; if (isUriInLocalPaths(httpRequest)) { // Ignore and pass through LOGGER.debug("Passing through request for {}", httpRequest.getRequestURI()); chain.doFilter(request, response); } else { if (isUriInCheckPaths(httpRequest)) { // Check the server state try { if (!spaceChecker.isSpaceAvailable()) { ((HttpServletResponse) response).sendError(proxyConfiguration.getErrorStatus()); }
} catch (DiskSpaceCheckerException e) {
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/health/ClusterDiskSpaceManagerHealthCheck.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // }
import com.codahale.metrics.health.HealthCheck; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.data.DiskSpace; import java.util.Date; import java.util.Set;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.health; /** * HealthCheck for the ClusterDiskSpaceManager. * * Created by mlp on 19/04/16. */ public class ClusterDiskSpaceManagerHealthCheck extends HealthCheck { static final int EXPIRY_TIME_MINS = 5;
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/health/ClusterDiskSpaceManagerHealthCheck.java import com.codahale.metrics.health.HealthCheck; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.data.DiskSpace; import java.util.Date; import java.util.Set; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.health; /** * HealthCheck for the ClusterDiskSpaceManager. * * Created by mlp on 19/04/16. */ public class ClusterDiskSpaceManagerHealthCheck extends HealthCheck { static final int EXPIRY_TIME_MINS = 5;
private final ClusterDiskSpaceManager manager;
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/health/ClusterDiskSpaceManagerHealthCheck.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // }
import com.codahale.metrics.health.HealthCheck; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.data.DiskSpace; import java.util.Date; import java.util.Set;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.health; /** * HealthCheck for the ClusterDiskSpaceManager. * * Created by mlp on 19/04/16. */ public class ClusterDiskSpaceManagerHealthCheck extends HealthCheck { static final int EXPIRY_TIME_MINS = 5; private final ClusterDiskSpaceManager manager; public ClusterDiskSpaceManagerHealthCheck(ClusterDiskSpaceManager manager) { this.manager = manager; } @Override protected Result check() throws Exception { final Result result; StringBuilder message = new StringBuilder(); boolean healthy = true; for (String server : manager.getServers()) { if (message.length() > 0) { message.append("; "); } if (manager.getDiskSpace().get(server) == null) { message.append(server).append(" : no disk space recorded"); healthy = false; } else {
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/health/ClusterDiskSpaceManagerHealthCheck.java import com.codahale.metrics.health.HealthCheck; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.data.DiskSpace; import java.util.Date; import java.util.Set; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.health; /** * HealthCheck for the ClusterDiskSpaceManager. * * Created by mlp on 19/04/16. */ public class ClusterDiskSpaceManagerHealthCheck extends HealthCheck { static final int EXPIRY_TIME_MINS = 5; private final ClusterDiskSpaceManager manager; public ClusterDiskSpaceManagerHealthCheck(ClusterDiskSpaceManager manager) { this.manager = manager; } @Override protected Result check() throws Exception { final Result result; StringBuilder message = new StringBuilder(); boolean healthy = true; for (String server : manager.getServers()) { if (message.length() > 0) { message.append("; "); } if (manager.getDiskSpace().get(server) == null) { message.append(server).append(" : no disk space recorded"); healthy = false; } else {
DiskSpace disk = manager.getDiskSpace().get(server);
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/health/DiskSpaceCheckerHealthCheck.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceChecker.java // public interface DiskSpaceChecker { // // /** // * Check whether space is available on the disk or cluster of // * disks. // * @return {@code true} if space is available, {@code false} if not // * (including if server calls fail). // * @throws DiskSpaceCheckerException if problems occur checking the // * disks. // */ // boolean isSpaceAvailable() throws DiskSpaceCheckerException; // // /** // * Pass configuration properties into the checker instance, for custom // * checkers. // * @param configuration a {@link Map} of configuration details. // * @throws DiskSpaceCheckerException if the configuration cannot be read. // */ // void configure(Map<String, Object> configuration) throws DiskSpaceCheckerException; // // /** // * Does the implementation require an HTTP client for remote access? // * @return {@code true} if the checker requires HTTP access. // */ // boolean requiresHttpClient(); // // /** // * Set the HTTP client to use for remote access. This will be supplied and managed // * by DropWizard, avoiding the requirement to implement your own. // * @param httpClient the client to use. // */ // void setHttpClient(Client httpClient); // // /** // * Set the disk space threshold to use to check for available space. // * @param threshold the threshold. // */ // void setThreshold(DiskSpaceThreshold threshold); // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // }
import com.codahale.metrics.health.HealthCheck; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.services.DiskSpaceChecker; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.health; /** * Generic disk checker health check. * <p> * Created by mlp on 19/04/16. */ public class DiskSpaceCheckerHealthCheck extends HealthCheck { private static final Logger LOGGER = LoggerFactory.getLogger(DiskSpaceCheckerHealthCheck.class);
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceChecker.java // public interface DiskSpaceChecker { // // /** // * Check whether space is available on the disk or cluster of // * disks. // * @return {@code true} if space is available, {@code false} if not // * (including if server calls fail). // * @throws DiskSpaceCheckerException if problems occur checking the // * disks. // */ // boolean isSpaceAvailable() throws DiskSpaceCheckerException; // // /** // * Pass configuration properties into the checker instance, for custom // * checkers. // * @param configuration a {@link Map} of configuration details. // * @throws DiskSpaceCheckerException if the configuration cannot be read. // */ // void configure(Map<String, Object> configuration) throws DiskSpaceCheckerException; // // /** // * Does the implementation require an HTTP client for remote access? // * @return {@code true} if the checker requires HTTP access. // */ // boolean requiresHttpClient(); // // /** // * Set the HTTP client to use for remote access. This will be supplied and managed // * by DropWizard, avoiding the requirement to implement your own. // * @param httpClient the client to use. // */ // void setHttpClient(Client httpClient); // // /** // * Set the disk space threshold to use to check for available space. // * @param threshold the threshold. // */ // void setThreshold(DiskSpaceThreshold threshold); // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/health/DiskSpaceCheckerHealthCheck.java import com.codahale.metrics.health.HealthCheck; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.services.DiskSpaceChecker; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.health; /** * Generic disk checker health check. * <p> * Created by mlp on 19/04/16. */ public class DiskSpaceCheckerHealthCheck extends HealthCheck { private static final Logger LOGGER = LoggerFactory.getLogger(DiskSpaceCheckerHealthCheck.class);
private final DiskSpaceChecker checker;
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/health/DiskSpaceCheckerHealthCheck.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceChecker.java // public interface DiskSpaceChecker { // // /** // * Check whether space is available on the disk or cluster of // * disks. // * @return {@code true} if space is available, {@code false} if not // * (including if server calls fail). // * @throws DiskSpaceCheckerException if problems occur checking the // * disks. // */ // boolean isSpaceAvailable() throws DiskSpaceCheckerException; // // /** // * Pass configuration properties into the checker instance, for custom // * checkers. // * @param configuration a {@link Map} of configuration details. // * @throws DiskSpaceCheckerException if the configuration cannot be read. // */ // void configure(Map<String, Object> configuration) throws DiskSpaceCheckerException; // // /** // * Does the implementation require an HTTP client for remote access? // * @return {@code true} if the checker requires HTTP access. // */ // boolean requiresHttpClient(); // // /** // * Set the HTTP client to use for remote access. This will be supplied and managed // * by DropWizard, avoiding the requirement to implement your own. // * @param httpClient the client to use. // */ // void setHttpClient(Client httpClient); // // /** // * Set the disk space threshold to use to check for available space. // * @param threshold the threshold. // */ // void setThreshold(DiskSpaceThreshold threshold); // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // }
import com.codahale.metrics.health.HealthCheck; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.services.DiskSpaceChecker; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.health; /** * Generic disk checker health check. * <p> * Created by mlp on 19/04/16. */ public class DiskSpaceCheckerHealthCheck extends HealthCheck { private static final Logger LOGGER = LoggerFactory.getLogger(DiskSpaceCheckerHealthCheck.class); private final DiskSpaceChecker checker; public DiskSpaceCheckerHealthCheck(DiskSpaceChecker checker) { this.checker = checker; } @Override protected Result check() throws Exception { try { if (checker.isSpaceAvailable()) { return Result.healthy(); } else { return Result.unhealthy("DiskSpaceChecker returns no space available"); }
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceChecker.java // public interface DiskSpaceChecker { // // /** // * Check whether space is available on the disk or cluster of // * disks. // * @return {@code true} if space is available, {@code false} if not // * (including if server calls fail). // * @throws DiskSpaceCheckerException if problems occur checking the // * disks. // */ // boolean isSpaceAvailable() throws DiskSpaceCheckerException; // // /** // * Pass configuration properties into the checker instance, for custom // * checkers. // * @param configuration a {@link Map} of configuration details. // * @throws DiskSpaceCheckerException if the configuration cannot be read. // */ // void configure(Map<String, Object> configuration) throws DiskSpaceCheckerException; // // /** // * Does the implementation require an HTTP client for remote access? // * @return {@code true} if the checker requires HTTP access. // */ // boolean requiresHttpClient(); // // /** // * Set the HTTP client to use for remote access. This will be supplied and managed // * by DropWizard, avoiding the requirement to implement your own. // * @param httpClient the client to use. // */ // void setHttpClient(Client httpClient); // // /** // * Set the disk space threshold to use to check for available space. // * @param threshold the threshold. // */ // void setThreshold(DiskSpaceThreshold threshold); // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/health/DiskSpaceCheckerHealthCheck.java import com.codahale.metrics.health.HealthCheck; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.services.DiskSpaceChecker; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.health; /** * Generic disk checker health check. * <p> * Created by mlp on 19/04/16. */ public class DiskSpaceCheckerHealthCheck extends HealthCheck { private static final Logger LOGGER = LoggerFactory.getLogger(DiskSpaceCheckerHealthCheck.class); private final DiskSpaceChecker checker; public DiskSpaceCheckerHealthCheck(DiskSpaceChecker checker) { this.checker = checker; } @Override protected Result check() throws Exception { try { if (checker.isSpaceAvailable()) { return Result.healthy(); } else { return Result.unhealthy("DiskSpaceChecker returns no space available"); }
} catch (DiskSpaceCheckerException e) {
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceThreshold.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // }
import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.services.data.DiskSpace; import java.util.regex.Matcher; import java.util.regex.Pattern;
// FALL THROUGH case "M": value = value * KILOBYTE; // FALL THROUGH case "K": value = value * KILOBYTE; t = new DiskSpaceThreshold(value, false); break; default: throw new DiskSpaceCheckerException("Unexpected unit value: " + unit); } } return t; } public long getThresholdValue() { return thresholdValue; } public boolean isPercentage() { return percentage; } /** * Check whether or not a {@link DiskSpace} object representing * space on a server is within this threshold. * @param diskSpace the disk space data. * @return {code true} if the space available is within the threshold value. */
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceThreshold.java import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.services.data.DiskSpace; import java.util.regex.Matcher; import java.util.regex.Pattern; // FALL THROUGH case "M": value = value * KILOBYTE; // FALL THROUGH case "K": value = value * KILOBYTE; t = new DiskSpaceThreshold(value, false); break; default: throw new DiskSpaceCheckerException("Unexpected unit value: " + unit); } } return t; } public long getThresholdValue() { return thresholdValue; } public boolean isPercentage() { return percentage; } /** * Check whether or not a {@link DiskSpace} object representing * space on a server is within this threshold. * @param diskSpace the disk space data. * @return {code true} if the space available is within the threshold value. */
public boolean withinThreshold(DiskSpace diskSpace) {
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/services/impl/ElasticsearchClient.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/ElasticsearchClusterStats.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class ElasticsearchClusterStats { // // @JsonProperty("timestamp") // private final long timestamp; // // @JsonProperty("cluster_name") // private final String clusterName; // // @JsonProperty("status") // private final String status; // // @JsonProperty(value = "nodes") // private final ElasticsearchClusterNodes nodes; // // public ElasticsearchClusterStats(@JsonProperty("timestamp") long timestamp, // @JsonProperty("cluster_name") String clusterName, // @JsonProperty("status") String status, // @JsonProperty("nodes") ElasticsearchClusterNodes nodes) { // this.timestamp = timestamp; // this.clusterName = clusterName; // this.status = status; // this.nodes = nodes; // } // // public long getTimestamp() { // return timestamp; // } // // public String getClusterName() { // return clusterName; // } // // public String getStatus() { // return status; // } // // public ElasticsearchClusterNodes getNodes() { // return nodes; // } // // public long getFilesystemFreeBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getFreeBytes(); // } // return 0; // } // // public long getFilesystemAvailableBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getAvailableBytes(); // } // return 0; // } // // public long getFilesystemTotalBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getTotalBytes(); // } // return 0; // } // // private ElasticsearchClusterFilesystem getFilesystem() { // if (nodes != null) { // return nodes.getFileSystem(); // } // return null; // } // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.ElasticsearchClusterStats; import javax.ws.rs.client.Client; import javax.ws.rs.core.MediaType; import java.io.IOException;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.services.impl; /** * Client class for retrieving cluster stats from ES. * * Created by mlp on 15/04/16. */ public class ElasticsearchClient { private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchClient.class); static final String CLUSTER_STATS_ENDPOINT = "/_cluster/stats"; private final Client client; private final String baseUrl; private final long cacheMs;
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/ElasticsearchClusterStats.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class ElasticsearchClusterStats { // // @JsonProperty("timestamp") // private final long timestamp; // // @JsonProperty("cluster_name") // private final String clusterName; // // @JsonProperty("status") // private final String status; // // @JsonProperty(value = "nodes") // private final ElasticsearchClusterNodes nodes; // // public ElasticsearchClusterStats(@JsonProperty("timestamp") long timestamp, // @JsonProperty("cluster_name") String clusterName, // @JsonProperty("status") String status, // @JsonProperty("nodes") ElasticsearchClusterNodes nodes) { // this.timestamp = timestamp; // this.clusterName = clusterName; // this.status = status; // this.nodes = nodes; // } // // public long getTimestamp() { // return timestamp; // } // // public String getClusterName() { // return clusterName; // } // // public String getStatus() { // return status; // } // // public ElasticsearchClusterNodes getNodes() { // return nodes; // } // // public long getFilesystemFreeBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getFreeBytes(); // } // return 0; // } // // public long getFilesystemAvailableBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getAvailableBytes(); // } // return 0; // } // // public long getFilesystemTotalBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getTotalBytes(); // } // return 0; // } // // private ElasticsearchClusterFilesystem getFilesystem() { // if (nodes != null) { // return nodes.getFileSystem(); // } // return null; // } // // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/impl/ElasticsearchClient.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.ElasticsearchClusterStats; import javax.ws.rs.client.Client; import javax.ws.rs.core.MediaType; import java.io.IOException; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.services.impl; /** * Client class for retrieving cluster stats from ES. * * Created by mlp on 15/04/16. */ public class ElasticsearchClient { private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchClient.class); static final String CLUSTER_STATS_ENDPOINT = "/_cluster/stats"; private final Client client; private final String baseUrl; private final long cacheMs;
private ElasticsearchClusterStats latestStats;
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/services/impl/ElasticsearchClient.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/ElasticsearchClusterStats.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class ElasticsearchClusterStats { // // @JsonProperty("timestamp") // private final long timestamp; // // @JsonProperty("cluster_name") // private final String clusterName; // // @JsonProperty("status") // private final String status; // // @JsonProperty(value = "nodes") // private final ElasticsearchClusterNodes nodes; // // public ElasticsearchClusterStats(@JsonProperty("timestamp") long timestamp, // @JsonProperty("cluster_name") String clusterName, // @JsonProperty("status") String status, // @JsonProperty("nodes") ElasticsearchClusterNodes nodes) { // this.timestamp = timestamp; // this.clusterName = clusterName; // this.status = status; // this.nodes = nodes; // } // // public long getTimestamp() { // return timestamp; // } // // public String getClusterName() { // return clusterName; // } // // public String getStatus() { // return status; // } // // public ElasticsearchClusterNodes getNodes() { // return nodes; // } // // public long getFilesystemFreeBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getFreeBytes(); // } // return 0; // } // // public long getFilesystemAvailableBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getAvailableBytes(); // } // return 0; // } // // public long getFilesystemTotalBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getTotalBytes(); // } // return 0; // } // // private ElasticsearchClusterFilesystem getFilesystem() { // if (nodes != null) { // return nodes.getFileSystem(); // } // return null; // } // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.ElasticsearchClusterStats; import javax.ws.rs.client.Client; import javax.ws.rs.core.MediaType; import java.io.IOException;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.services.impl; /** * Client class for retrieving cluster stats from ES. * * Created by mlp on 15/04/16. */ public class ElasticsearchClient { private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchClient.class); static final String CLUSTER_STATS_ENDPOINT = "/_cluster/stats"; private final Client client; private final String baseUrl; private final long cacheMs; private ElasticsearchClusterStats latestStats; private long lastUpdate; private final Object statsLock = new Object(); public ElasticsearchClient(Client client, String baseUrl, long cacheMs) { this.client = client; this.baseUrl = baseUrl; this.cacheMs = cacheMs; }
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/ElasticsearchClusterStats.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class ElasticsearchClusterStats { // // @JsonProperty("timestamp") // private final long timestamp; // // @JsonProperty("cluster_name") // private final String clusterName; // // @JsonProperty("status") // private final String status; // // @JsonProperty(value = "nodes") // private final ElasticsearchClusterNodes nodes; // // public ElasticsearchClusterStats(@JsonProperty("timestamp") long timestamp, // @JsonProperty("cluster_name") String clusterName, // @JsonProperty("status") String status, // @JsonProperty("nodes") ElasticsearchClusterNodes nodes) { // this.timestamp = timestamp; // this.clusterName = clusterName; // this.status = status; // this.nodes = nodes; // } // // public long getTimestamp() { // return timestamp; // } // // public String getClusterName() { // return clusterName; // } // // public String getStatus() { // return status; // } // // public ElasticsearchClusterNodes getNodes() { // return nodes; // } // // public long getFilesystemFreeBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getFreeBytes(); // } // return 0; // } // // public long getFilesystemAvailableBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getAvailableBytes(); // } // return 0; // } // // public long getFilesystemTotalBytes() { // ElasticsearchClusterFilesystem fs = getFilesystem(); // if (fs != null) { // return fs.getTotalBytes(); // } // return 0; // } // // private ElasticsearchClusterFilesystem getFilesystem() { // if (nodes != null) { // return nodes.getFileSystem(); // } // return null; // } // // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/impl/ElasticsearchClient.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.ElasticsearchClusterStats; import javax.ws.rs.client.Client; import javax.ws.rs.core.MediaType; import java.io.IOException; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.services.impl; /** * Client class for retrieving cluster stats from ES. * * Created by mlp on 15/04/16. */ public class ElasticsearchClient { private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchClient.class); static final String CLUSTER_STATS_ENDPOINT = "/_cluster/stats"; private final Client client; private final String baseUrl; private final long cacheMs; private ElasticsearchClusterStats latestStats; private long lastUpdate; private final Object statsLock = new Object(); public ElasticsearchClient(Client client, String baseUrl, long cacheMs) { this.client = client; this.baseUrl = baseUrl; this.cacheMs = cacheMs; }
public ElasticsearchClusterStats getClusterStats() throws DiskSpaceCheckerException {
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/HaraHachiBuConfiguration.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/DiskSpaceConfiguration.java // public class DiskSpaceConfiguration { // // public static final String ELASTICSEARCH_CHECKER = "elasticsearch"; // public static final String SOLR_LOCAL_CHECKER = "solr"; // public static final String CLUSTER_CHECKER = "cluster"; // // @NotNull // private String checkerType; // // @NotNull // private String threshold; // // @NotNull // private Map<String, Object> configuration = new HashMap<>(); // // // public String getCheckerType() { // return checkerType; // } // // public void setCheckerType(String checkerType) { // this.checkerType = checkerType; // } // // public String getThreshold() { // return threshold; // } // // public void setThreshold(String threshold) { // this.threshold = threshold; // } // // public Map<String, Object> getConfiguration() { // return configuration; // } // // public void setConfiguration(Map<String, Object> configuration) { // this.configuration = configuration; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // }
import io.dropwizard.Configuration; import io.dropwizard.client.JerseyClientConfiguration; import uk.co.flax.harahachibu.config.DiskSpaceConfiguration; import uk.co.flax.harahachibu.config.ProxyConfiguration; import javax.validation.Valid; import javax.validation.constraints.NotNull;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu; /** * Base configuration class for the Hara Hachi Bu proxy application. * * Created by mlp on 13/04/16. */ public class HaraHachiBuConfiguration extends Configuration { @Valid @NotNull
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/DiskSpaceConfiguration.java // public class DiskSpaceConfiguration { // // public static final String ELASTICSEARCH_CHECKER = "elasticsearch"; // public static final String SOLR_LOCAL_CHECKER = "solr"; // public static final String CLUSTER_CHECKER = "cluster"; // // @NotNull // private String checkerType; // // @NotNull // private String threshold; // // @NotNull // private Map<String, Object> configuration = new HashMap<>(); // // // public String getCheckerType() { // return checkerType; // } // // public void setCheckerType(String checkerType) { // this.checkerType = checkerType; // } // // public String getThreshold() { // return threshold; // } // // public void setThreshold(String threshold) { // this.threshold = threshold; // } // // public Map<String, Object> getConfiguration() { // return configuration; // } // // public void setConfiguration(Map<String, Object> configuration) { // this.configuration = configuration; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/HaraHachiBuConfiguration.java import io.dropwizard.Configuration; import io.dropwizard.client.JerseyClientConfiguration; import uk.co.flax.harahachibu.config.DiskSpaceConfiguration; import uk.co.flax.harahachibu.config.ProxyConfiguration; import javax.validation.Valid; import javax.validation.constraints.NotNull; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu; /** * Base configuration class for the Hara Hachi Bu proxy application. * * Created by mlp on 13/04/16. */ public class HaraHachiBuConfiguration extends Configuration { @Valid @NotNull
private ProxyConfiguration proxy;
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/HaraHachiBuConfiguration.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/DiskSpaceConfiguration.java // public class DiskSpaceConfiguration { // // public static final String ELASTICSEARCH_CHECKER = "elasticsearch"; // public static final String SOLR_LOCAL_CHECKER = "solr"; // public static final String CLUSTER_CHECKER = "cluster"; // // @NotNull // private String checkerType; // // @NotNull // private String threshold; // // @NotNull // private Map<String, Object> configuration = new HashMap<>(); // // // public String getCheckerType() { // return checkerType; // } // // public void setCheckerType(String checkerType) { // this.checkerType = checkerType; // } // // public String getThreshold() { // return threshold; // } // // public void setThreshold(String threshold) { // this.threshold = threshold; // } // // public Map<String, Object> getConfiguration() { // return configuration; // } // // public void setConfiguration(Map<String, Object> configuration) { // this.configuration = configuration; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // }
import io.dropwizard.Configuration; import io.dropwizard.client.JerseyClientConfiguration; import uk.co.flax.harahachibu.config.DiskSpaceConfiguration; import uk.co.flax.harahachibu.config.ProxyConfiguration; import javax.validation.Valid; import javax.validation.constraints.NotNull;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu; /** * Base configuration class for the Hara Hachi Bu proxy application. * * Created by mlp on 13/04/16. */ public class HaraHachiBuConfiguration extends Configuration { @Valid @NotNull private ProxyConfiguration proxy; @Valid @NotNull private JerseyClientConfiguration jerseyClient = new JerseyClientConfiguration(); @Valid @NotNull
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/DiskSpaceConfiguration.java // public class DiskSpaceConfiguration { // // public static final String ELASTICSEARCH_CHECKER = "elasticsearch"; // public static final String SOLR_LOCAL_CHECKER = "solr"; // public static final String CLUSTER_CHECKER = "cluster"; // // @NotNull // private String checkerType; // // @NotNull // private String threshold; // // @NotNull // private Map<String, Object> configuration = new HashMap<>(); // // // public String getCheckerType() { // return checkerType; // } // // public void setCheckerType(String checkerType) { // this.checkerType = checkerType; // } // // public String getThreshold() { // return threshold; // } // // public void setThreshold(String threshold) { // this.threshold = threshold; // } // // public Map<String, Object> getConfiguration() { // return configuration; // } // // public void setConfiguration(Map<String, Object> configuration) { // this.configuration = configuration; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/HaraHachiBuConfiguration.java import io.dropwizard.Configuration; import io.dropwizard.client.JerseyClientConfiguration; import uk.co.flax.harahachibu.config.DiskSpaceConfiguration; import uk.co.flax.harahachibu.config.ProxyConfiguration; import javax.validation.Valid; import javax.validation.constraints.NotNull; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu; /** * Base configuration class for the Hara Hachi Bu proxy application. * * Created by mlp on 13/04/16. */ public class HaraHachiBuConfiguration extends Configuration { @Valid @NotNull private ProxyConfiguration proxy; @Valid @NotNull private JerseyClientConfiguration jerseyClient = new JerseyClientConfiguration(); @Valid @NotNull
private DiskSpaceConfiguration diskSpace;
flaxsearch/harahachibu
harahachibu/src/test/java/uk/co/flax/harahachibu/services/impl/SolrDiskSpaceCheckerTest.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceThreshold.java // public class DiskSpaceThreshold { // // private static final Logger LOGGER = LoggerFactory.getLogger(DiskSpaceThreshold.class); // // private static final Pattern THRESHOLD_PATTERN = Pattern.compile("^(\\d+)\\s*([KMG%])?$", Pattern.CASE_INSENSITIVE); // // private static final int KILOBYTE = 1024; // // private long thresholdValue; // private boolean percentage; // // DiskSpaceThreshold(final long threshold, final boolean isPercentage) { // this.thresholdValue = threshold; // this.percentage = isPercentage; // } // // /** // * Parse a threshold string and return the corresponding DiskSpaceThreshold object. // * @param thresholdString the string to parse. // * @return a DiskSpaceThreshold representing the threshold value, and whether it // * is a percentage. // * @throws DiskSpaceCheckerException if the string cannot be parsed, or the value // * makes no sense (percentage above 100, negative value, etc.). // */ // public static DiskSpaceThreshold parse(String thresholdString) throws DiskSpaceCheckerException { // if (thresholdString.startsWith("-")) { // throw new DiskSpaceCheckerException("Negative threshold string not allowed: " + thresholdString); // } // // Matcher m = THRESHOLD_PATTERN.matcher(thresholdString); // if (!m.matches()) { // throw new DiskSpaceCheckerException("Cannot parse threshold string " + thresholdString); // } // // DiskSpaceThreshold t; // // long value = Long.valueOf(m.group(1)); // if (StringUtils.isBlank(m.group(2))) { // t = new DiskSpaceThreshold(value, false); // } else { // String unit = m.group(2).toUpperCase(); // // switch (unit) { // case "%": // if (value > 100) { // throw new DiskSpaceCheckerException("Percentage value higher than 100%: " + thresholdString); // } else { // t = new DiskSpaceThreshold(value, true); // } // break; // case "G": // value = value * KILOBYTE; // // FALL THROUGH // case "M": // value = value * KILOBYTE; // // FALL THROUGH // case "K": // value = value * KILOBYTE; // t = new DiskSpaceThreshold(value, false); // break; // default: // throw new DiskSpaceCheckerException("Unexpected unit value: " + unit); // } // } // // return t; // } // // public long getThresholdValue() { // return thresholdValue; // } // // public boolean isPercentage() { // return percentage; // } // // /** // * Check whether or not a {@link DiskSpace} object representing // * space on a server is within this threshold. // * @param diskSpace the disk space data. // * @return {code true} if the space available is within the threshold value. // */ // public boolean withinThreshold(DiskSpace diskSpace) { // return withinThreshold(diskSpace.getFreeSpace(), diskSpace.getMaxSpace()); // } // // /** // * Check whether or not the space available is within this threshold. // * @param freeSpace the free space on the drive. // * @param maxSpace the maximum space on the drive (required for percentage // * thresholds). // * @return {code true} if the space is within the threshold value. // */ // public boolean withinThreshold(long freeSpace, long maxSpace) { // boolean ret = true; // // if (isPercentage()) { // // Work out percentage free space // if (maxSpace == 0) { // LOGGER.warn("Skipping withinThreshold() percentage calculation - maxSpace == 0"); // ret = false; // } else { // int freePercent = Math.round(((float) freeSpace / maxSpace) * 100); // if (freePercent <= thresholdValue) { // LOGGER.debug("Threshold percentage check fails: freeSpace={}, maxSpace={}, percent free={}, threshold={}%", // freeSpace, maxSpace, freePercent, thresholdValue); // ret = false; // } // } // } else { // if (freeSpace <= thresholdValue) { // LOGGER.debug("Threshold check fails: freeSpace={}, threshold={}", freeSpace, thresholdValue); // ret = false; // } // } // // return ret; // } // // }
import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.services.DiskSpaceThreshold; import java.io.IOException; import java.nio.file.FileStore; import java.util.HashMap; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.services.impl; /** * Unit tests for the local Solr disk space checker implementation. * * Created by mlp on 18/04/16. */ public class SolrDiskSpaceCheckerTest { private SolrDiskSpaceChecker checker; private Map<String, Object> configuration = new HashMap<>();
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceThreshold.java // public class DiskSpaceThreshold { // // private static final Logger LOGGER = LoggerFactory.getLogger(DiskSpaceThreshold.class); // // private static final Pattern THRESHOLD_PATTERN = Pattern.compile("^(\\d+)\\s*([KMG%])?$", Pattern.CASE_INSENSITIVE); // // private static final int KILOBYTE = 1024; // // private long thresholdValue; // private boolean percentage; // // DiskSpaceThreshold(final long threshold, final boolean isPercentage) { // this.thresholdValue = threshold; // this.percentage = isPercentage; // } // // /** // * Parse a threshold string and return the corresponding DiskSpaceThreshold object. // * @param thresholdString the string to parse. // * @return a DiskSpaceThreshold representing the threshold value, and whether it // * is a percentage. // * @throws DiskSpaceCheckerException if the string cannot be parsed, or the value // * makes no sense (percentage above 100, negative value, etc.). // */ // public static DiskSpaceThreshold parse(String thresholdString) throws DiskSpaceCheckerException { // if (thresholdString.startsWith("-")) { // throw new DiskSpaceCheckerException("Negative threshold string not allowed: " + thresholdString); // } // // Matcher m = THRESHOLD_PATTERN.matcher(thresholdString); // if (!m.matches()) { // throw new DiskSpaceCheckerException("Cannot parse threshold string " + thresholdString); // } // // DiskSpaceThreshold t; // // long value = Long.valueOf(m.group(1)); // if (StringUtils.isBlank(m.group(2))) { // t = new DiskSpaceThreshold(value, false); // } else { // String unit = m.group(2).toUpperCase(); // // switch (unit) { // case "%": // if (value > 100) { // throw new DiskSpaceCheckerException("Percentage value higher than 100%: " + thresholdString); // } else { // t = new DiskSpaceThreshold(value, true); // } // break; // case "G": // value = value * KILOBYTE; // // FALL THROUGH // case "M": // value = value * KILOBYTE; // // FALL THROUGH // case "K": // value = value * KILOBYTE; // t = new DiskSpaceThreshold(value, false); // break; // default: // throw new DiskSpaceCheckerException("Unexpected unit value: " + unit); // } // } // // return t; // } // // public long getThresholdValue() { // return thresholdValue; // } // // public boolean isPercentage() { // return percentage; // } // // /** // * Check whether or not a {@link DiskSpace} object representing // * space on a server is within this threshold. // * @param diskSpace the disk space data. // * @return {code true} if the space available is within the threshold value. // */ // public boolean withinThreshold(DiskSpace diskSpace) { // return withinThreshold(diskSpace.getFreeSpace(), diskSpace.getMaxSpace()); // } // // /** // * Check whether or not the space available is within this threshold. // * @param freeSpace the free space on the drive. // * @param maxSpace the maximum space on the drive (required for percentage // * thresholds). // * @return {code true} if the space is within the threshold value. // */ // public boolean withinThreshold(long freeSpace, long maxSpace) { // boolean ret = true; // // if (isPercentage()) { // // Work out percentage free space // if (maxSpace == 0) { // LOGGER.warn("Skipping withinThreshold() percentage calculation - maxSpace == 0"); // ret = false; // } else { // int freePercent = Math.round(((float) freeSpace / maxSpace) * 100); // if (freePercent <= thresholdValue) { // LOGGER.debug("Threshold percentage check fails: freeSpace={}, maxSpace={}, percent free={}, threshold={}%", // freeSpace, maxSpace, freePercent, thresholdValue); // ret = false; // } // } // } else { // if (freeSpace <= thresholdValue) { // LOGGER.debug("Threshold check fails: freeSpace={}, threshold={}", freeSpace, thresholdValue); // ret = false; // } // } // // return ret; // } // // } // Path: harahachibu/src/test/java/uk/co/flax/harahachibu/services/impl/SolrDiskSpaceCheckerTest.java import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.services.DiskSpaceThreshold; import java.io.IOException; import java.nio.file.FileStore; import java.util.HashMap; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.services.impl; /** * Unit tests for the local Solr disk space checker implementation. * * Created by mlp on 18/04/16. */ public class SolrDiskSpaceCheckerTest { private SolrDiskSpaceChecker checker; private Map<String, Object> configuration = new HashMap<>();
private DiskSpaceThreshold threshold = mock(DiskSpaceThreshold.class);
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/resources/SetSpaceResource.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/api/SetSpaceResponse.java // public class SetSpaceResponse { // // public enum ResponseCode { // OK, ERROR // }; // // @JsonProperty("status") // private final ResponseCode responseCode; // @JsonProperty("message") // private final String message; // // public SetSpaceResponse(ResponseCode code, String message) { // this.responseCode = code; // this.message = message; // } // // public static SetSpaceResponse okResponse() { // return new SetSpaceResponse(ResponseCode.OK, null); // } // // public ResponseCode getResponseCode() { // return responseCode; // } // // public String getMessage() { // return message; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // }
import uk.co.flax.harahachibu.api.SetSpaceResponse; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.DiskSpace; import javax.ws.rs.*; import javax.ws.rs.core.MediaType;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.resources; /** * Endpoint to allow disk space to be set for remote servers. * * Created by mlp on 14/04/16. */ @Path("/setSpace/{host}/{freeSpace}/{maxSpace}") public class SetSpaceResource {
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/api/SetSpaceResponse.java // public class SetSpaceResponse { // // public enum ResponseCode { // OK, ERROR // }; // // @JsonProperty("status") // private final ResponseCode responseCode; // @JsonProperty("message") // private final String message; // // public SetSpaceResponse(ResponseCode code, String message) { // this.responseCode = code; // this.message = message; // } // // public static SetSpaceResponse okResponse() { // return new SetSpaceResponse(ResponseCode.OK, null); // } // // public ResponseCode getResponseCode() { // return responseCode; // } // // public String getMessage() { // return message; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/resources/SetSpaceResource.java import uk.co.flax.harahachibu.api.SetSpaceResponse; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.DiskSpace; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.resources; /** * Endpoint to allow disk space to be set for remote servers. * * Created by mlp on 14/04/16. */ @Path("/setSpace/{host}/{freeSpace}/{maxSpace}") public class SetSpaceResource {
private final ClusterDiskSpaceManager clusterManager;
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/resources/SetSpaceResource.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/api/SetSpaceResponse.java // public class SetSpaceResponse { // // public enum ResponseCode { // OK, ERROR // }; // // @JsonProperty("status") // private final ResponseCode responseCode; // @JsonProperty("message") // private final String message; // // public SetSpaceResponse(ResponseCode code, String message) { // this.responseCode = code; // this.message = message; // } // // public static SetSpaceResponse okResponse() { // return new SetSpaceResponse(ResponseCode.OK, null); // } // // public ResponseCode getResponseCode() { // return responseCode; // } // // public String getMessage() { // return message; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // }
import uk.co.flax.harahachibu.api.SetSpaceResponse; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.DiskSpace; import javax.ws.rs.*; import javax.ws.rs.core.MediaType;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.resources; /** * Endpoint to allow disk space to be set for remote servers. * * Created by mlp on 14/04/16. */ @Path("/setSpace/{host}/{freeSpace}/{maxSpace}") public class SetSpaceResource { private final ClusterDiskSpaceManager clusterManager; public SetSpaceResource(ClusterDiskSpaceManager clusterManager) { this.clusterManager = clusterManager; } @POST @Produces(MediaType.APPLICATION_JSON)
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/api/SetSpaceResponse.java // public class SetSpaceResponse { // // public enum ResponseCode { // OK, ERROR // }; // // @JsonProperty("status") // private final ResponseCode responseCode; // @JsonProperty("message") // private final String message; // // public SetSpaceResponse(ResponseCode code, String message) { // this.responseCode = code; // this.message = message; // } // // public static SetSpaceResponse okResponse() { // return new SetSpaceResponse(ResponseCode.OK, null); // } // // public ResponseCode getResponseCode() { // return responseCode; // } // // public String getMessage() { // return message; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/resources/SetSpaceResource.java import uk.co.flax.harahachibu.api.SetSpaceResponse; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.DiskSpace; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.resources; /** * Endpoint to allow disk space to be set for remote servers. * * Created by mlp on 14/04/16. */ @Path("/setSpace/{host}/{freeSpace}/{maxSpace}") public class SetSpaceResource { private final ClusterDiskSpaceManager clusterManager; public SetSpaceResource(ClusterDiskSpaceManager clusterManager) { this.clusterManager = clusterManager; } @POST @Produces(MediaType.APPLICATION_JSON)
public SetSpaceResponse handlePost(@PathParam("host") String server,
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/resources/SetSpaceResource.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/api/SetSpaceResponse.java // public class SetSpaceResponse { // // public enum ResponseCode { // OK, ERROR // }; // // @JsonProperty("status") // private final ResponseCode responseCode; // @JsonProperty("message") // private final String message; // // public SetSpaceResponse(ResponseCode code, String message) { // this.responseCode = code; // this.message = message; // } // // public static SetSpaceResponse okResponse() { // return new SetSpaceResponse(ResponseCode.OK, null); // } // // public ResponseCode getResponseCode() { // return responseCode; // } // // public String getMessage() { // return message; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // }
import uk.co.flax.harahachibu.api.SetSpaceResponse; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.DiskSpace; import javax.ws.rs.*; import javax.ws.rs.core.MediaType;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.resources; /** * Endpoint to allow disk space to be set for remote servers. * * Created by mlp on 14/04/16. */ @Path("/setSpace/{host}/{freeSpace}/{maxSpace}") public class SetSpaceResource { private final ClusterDiskSpaceManager clusterManager; public SetSpaceResource(ClusterDiskSpaceManager clusterManager) { this.clusterManager = clusterManager; } @POST @Produces(MediaType.APPLICATION_JSON) public SetSpaceResponse handlePost(@PathParam("host") String server, @PathParam("freeSpace") long freeSpace, @PathParam("maxSpace") long maxSpace) { SetSpaceResponse response; try {
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/api/SetSpaceResponse.java // public class SetSpaceResponse { // // public enum ResponseCode { // OK, ERROR // }; // // @JsonProperty("status") // private final ResponseCode responseCode; // @JsonProperty("message") // private final String message; // // public SetSpaceResponse(ResponseCode code, String message) { // this.responseCode = code; // this.message = message; // } // // public static SetSpaceResponse okResponse() { // return new SetSpaceResponse(ResponseCode.OK, null); // } // // public ResponseCode getResponseCode() { // return responseCode; // } // // public String getMessage() { // return message; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/resources/SetSpaceResource.java import uk.co.flax.harahachibu.api.SetSpaceResponse; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.DiskSpace; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.resources; /** * Endpoint to allow disk space to be set for remote servers. * * Created by mlp on 14/04/16. */ @Path("/setSpace/{host}/{freeSpace}/{maxSpace}") public class SetSpaceResource { private final ClusterDiskSpaceManager clusterManager; public SetSpaceResource(ClusterDiskSpaceManager clusterManager) { this.clusterManager = clusterManager; } @POST @Produces(MediaType.APPLICATION_JSON) public SetSpaceResponse handlePost(@PathParam("host") String server, @PathParam("freeSpace") long freeSpace, @PathParam("maxSpace") long maxSpace) { SetSpaceResponse response; try {
clusterManager.setDiskSpace(server, new DiskSpace(freeSpace, maxSpace));
flaxsearch/harahachibu
harahachibu/src/main/java/uk/co/flax/harahachibu/resources/SetSpaceResource.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/api/SetSpaceResponse.java // public class SetSpaceResponse { // // public enum ResponseCode { // OK, ERROR // }; // // @JsonProperty("status") // private final ResponseCode responseCode; // @JsonProperty("message") // private final String message; // // public SetSpaceResponse(ResponseCode code, String message) { // this.responseCode = code; // this.message = message; // } // // public static SetSpaceResponse okResponse() { // return new SetSpaceResponse(ResponseCode.OK, null); // } // // public ResponseCode getResponseCode() { // return responseCode; // } // // public String getMessage() { // return message; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // }
import uk.co.flax.harahachibu.api.SetSpaceResponse; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.DiskSpace; import javax.ws.rs.*; import javax.ws.rs.core.MediaType;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.resources; /** * Endpoint to allow disk space to be set for remote servers. * * Created by mlp on 14/04/16. */ @Path("/setSpace/{host}/{freeSpace}/{maxSpace}") public class SetSpaceResource { private final ClusterDiskSpaceManager clusterManager; public SetSpaceResource(ClusterDiskSpaceManager clusterManager) { this.clusterManager = clusterManager; } @POST @Produces(MediaType.APPLICATION_JSON) public SetSpaceResponse handlePost(@PathParam("host") String server, @PathParam("freeSpace") long freeSpace, @PathParam("maxSpace") long maxSpace) { SetSpaceResponse response; try { clusterManager.setDiskSpace(server, new DiskSpace(freeSpace, maxSpace)); response = SetSpaceResponse.okResponse();
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/api/SetSpaceResponse.java // public class SetSpaceResponse { // // public enum ResponseCode { // OK, ERROR // }; // // @JsonProperty("status") // private final ResponseCode responseCode; // @JsonProperty("message") // private final String message; // // public SetSpaceResponse(ResponseCode code, String message) { // this.responseCode = code; // this.message = message; // } // // public static SetSpaceResponse okResponse() { // return new SetSpaceResponse(ResponseCode.OK, null); // } // // public ResponseCode getResponseCode() { // return responseCode; // } // // public String getMessage() { // return message; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/ClusterDiskSpaceManager.java // public class ClusterDiskSpaceManager { // // private final Set<String> servers; // private final Map<String, DiskSpace> diskSpaceMap = new ConcurrentHashMap<>(); // // /** // * Construct the ClusterDiskSpaceManager. // * @param servers the set of valid servers for the cluster. // */ // public ClusterDiskSpaceManager(Set<String> servers) { // this.servers = servers; // } // // /** // * Set the disk space for a server. // * @param server the server. // * @param space the DiskSpace object holding the disk space details. // * @throws DiskSpaceCheckerException if the server is not in the server list // * used to construct the manager. // */ // public void setDiskSpace(String server, DiskSpace space) throws DiskSpaceCheckerException { // if (!servers.contains(server)) { // throw new DiskSpaceCheckerException("Unrecognised server " + server); // } // // diskSpaceMap.put(server, space); // } // // /** // * Get the current map of server - disk space statuses. // * @return the map. // */ // public Map<String, DiskSpace> getDiskSpace() { // return diskSpaceMap; // } // // /** // * Get the list of servers for which we should have disk space settings. // * @return the servers. // */ // public Set<String> getServers() { // return servers; // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/DiskSpaceCheckerException.java // public class DiskSpaceCheckerException extends Exception { // // public DiskSpaceCheckerException() { // super(); // } // // public DiskSpaceCheckerException(String message) { // super(message); // } // // public DiskSpaceCheckerException(String message, Throwable cause) { // super(message, cause); // } // // public DiskSpaceCheckerException(Throwable cause) { // super(cause); // } // // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/services/data/DiskSpace.java // public class DiskSpace { // // private final long freeSpace; // private final long maxSpace; // private final Date creationDate = new Date(); // // public DiskSpace(long freeSpace, long maxSpace) { // this.freeSpace = freeSpace; // this.maxSpace = maxSpace; // } // // public long getFreeSpace() { // return freeSpace; // } // // public long getMaxSpace() { // return maxSpace; // } // // public Date getCreationDate() { // return creationDate; // } // // } // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/resources/SetSpaceResource.java import uk.co.flax.harahachibu.api.SetSpaceResponse; import uk.co.flax.harahachibu.services.ClusterDiskSpaceManager; import uk.co.flax.harahachibu.services.DiskSpaceCheckerException; import uk.co.flax.harahachibu.services.data.DiskSpace; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu.resources; /** * Endpoint to allow disk space to be set for remote servers. * * Created by mlp on 14/04/16. */ @Path("/setSpace/{host}/{freeSpace}/{maxSpace}") public class SetSpaceResource { private final ClusterDiskSpaceManager clusterManager; public SetSpaceResource(ClusterDiskSpaceManager clusterManager) { this.clusterManager = clusterManager; } @POST @Produces(MediaType.APPLICATION_JSON) public SetSpaceResponse handlePost(@PathParam("host") String server, @PathParam("freeSpace") long freeSpace, @PathParam("maxSpace") long maxSpace) { SetSpaceResponse response; try { clusterManager.setDiskSpace(server, new DiskSpace(freeSpace, maxSpace)); response = SetSpaceResponse.okResponse();
} catch (DiskSpaceCheckerException e) {
flaxsearch/harahachibu
harahachibu/src/test/java/uk/co/flax/harahachibu/HaraHachiBuApplicationTest.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/DiskSpaceConfiguration.java // public class DiskSpaceConfiguration { // // public static final String ELASTICSEARCH_CHECKER = "elasticsearch"; // public static final String SOLR_LOCAL_CHECKER = "solr"; // public static final String CLUSTER_CHECKER = "cluster"; // // @NotNull // private String checkerType; // // @NotNull // private String threshold; // // @NotNull // private Map<String, Object> configuration = new HashMap<>(); // // // public String getCheckerType() { // return checkerType; // } // // public void setCheckerType(String checkerType) { // this.checkerType = checkerType; // } // // public String getThreshold() { // return threshold; // } // // public void setThreshold(String threshold) { // this.threshold = threshold; // } // // public Map<String, Object> getConfiguration() { // return configuration; // } // // public void setConfiguration(Map<String, Object> configuration) { // this.configuration = configuration; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/servlets/DiskSpaceProxyServlet.java // public class DiskSpaceProxyServlet extends ProxyServlet { // // public static final String PROXY_PATH_PREFIX = "/proxy"; // // public static final String DESTINATION_SERVER_PARAM = "destinationServerPrefix"; // // private static final Logger LOGGER = LoggerFactory.getLogger(DiskSpaceProxyServlet.class); // // @Override // protected String rewriteTarget(HttpServletRequest request) { // final String target; // // if (!validateDestination(request.getServerName(), request.getServerPort())) { // target = null; // } else { // final String path = request.getRequestURI(); // // if (StringUtils.isBlank(path)) { // LOGGER.debug("No path given extracted from {}", request.getRequestURI()); // target = null; // } else if (!path.startsWith(PROXY_PATH_PREFIX)) { // target = null; // } else { // final String shortPath = path.substring(PROXY_PATH_PREFIX.length()); // final StringBuilder targetBuilder = new StringBuilder(getInitParameter(DESTINATION_SERVER_PARAM)) // .append(shortPath); // if (StringUtils.isNotBlank(request.getQueryString())) { // targetBuilder.append("?").append(request.getQueryString()); // } // // target = targetBuilder.toString(); // } // } // // return target; // } // // }
import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.*; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.health.HealthCheckRegistry; import io.dropwizard.jersey.setup.JerseyEnvironment; import io.dropwizard.jetty.setup.ServletEnvironment; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; import io.dropwizard.setup.Environment; import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.config.DiskSpaceConfiguration; import uk.co.flax.harahachibu.config.ProxyConfiguration; import uk.co.flax.harahachibu.servlets.DiskSpaceProxyServlet; import javax.servlet.Filter; import javax.servlet.FilterRegistration; import javax.servlet.ServletRegistration;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu; /** * Unit tests for the Hara Hachi Bu application class. * * Created by mlp on 13/04/16. */ public class HaraHachiBuApplicationTest { private final LifecycleEnvironment lifecycleEnvironment = spy(new LifecycleEnvironment()); private final MetricRegistry metrics = new MetricRegistry(); private final Environment environment = mock(Environment.class); private final ServletEnvironment servlets = mock(ServletEnvironment.class); private final FilterRegistration.Dynamic filterDynamic = mock(FilterRegistration.Dynamic.class); private final ServletRegistration.Dynamic servletDynamic = mock(ServletRegistration.Dynamic.class); private final JerseyEnvironment jersey = mock(JerseyEnvironment.class); private final HealthCheckRegistry healthChecks = mock(HealthCheckRegistry.class); private final HaraHachiBuApplication application = new HaraHachiBuApplication(); private final HaraHachiBuConfiguration config = new HaraHachiBuConfiguration();
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/DiskSpaceConfiguration.java // public class DiskSpaceConfiguration { // // public static final String ELASTICSEARCH_CHECKER = "elasticsearch"; // public static final String SOLR_LOCAL_CHECKER = "solr"; // public static final String CLUSTER_CHECKER = "cluster"; // // @NotNull // private String checkerType; // // @NotNull // private String threshold; // // @NotNull // private Map<String, Object> configuration = new HashMap<>(); // // // public String getCheckerType() { // return checkerType; // } // // public void setCheckerType(String checkerType) { // this.checkerType = checkerType; // } // // public String getThreshold() { // return threshold; // } // // public void setThreshold(String threshold) { // this.threshold = threshold; // } // // public Map<String, Object> getConfiguration() { // return configuration; // } // // public void setConfiguration(Map<String, Object> configuration) { // this.configuration = configuration; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/servlets/DiskSpaceProxyServlet.java // public class DiskSpaceProxyServlet extends ProxyServlet { // // public static final String PROXY_PATH_PREFIX = "/proxy"; // // public static final String DESTINATION_SERVER_PARAM = "destinationServerPrefix"; // // private static final Logger LOGGER = LoggerFactory.getLogger(DiskSpaceProxyServlet.class); // // @Override // protected String rewriteTarget(HttpServletRequest request) { // final String target; // // if (!validateDestination(request.getServerName(), request.getServerPort())) { // target = null; // } else { // final String path = request.getRequestURI(); // // if (StringUtils.isBlank(path)) { // LOGGER.debug("No path given extracted from {}", request.getRequestURI()); // target = null; // } else if (!path.startsWith(PROXY_PATH_PREFIX)) { // target = null; // } else { // final String shortPath = path.substring(PROXY_PATH_PREFIX.length()); // final StringBuilder targetBuilder = new StringBuilder(getInitParameter(DESTINATION_SERVER_PARAM)) // .append(shortPath); // if (StringUtils.isNotBlank(request.getQueryString())) { // targetBuilder.append("?").append(request.getQueryString()); // } // // target = targetBuilder.toString(); // } // } // // return target; // } // // } // Path: harahachibu/src/test/java/uk/co/flax/harahachibu/HaraHachiBuApplicationTest.java import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.*; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.health.HealthCheckRegistry; import io.dropwizard.jersey.setup.JerseyEnvironment; import io.dropwizard.jetty.setup.ServletEnvironment; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; import io.dropwizard.setup.Environment; import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.config.DiskSpaceConfiguration; import uk.co.flax.harahachibu.config.ProxyConfiguration; import uk.co.flax.harahachibu.servlets.DiskSpaceProxyServlet; import javax.servlet.Filter; import javax.servlet.FilterRegistration; import javax.servlet.ServletRegistration; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu; /** * Unit tests for the Hara Hachi Bu application class. * * Created by mlp on 13/04/16. */ public class HaraHachiBuApplicationTest { private final LifecycleEnvironment lifecycleEnvironment = spy(new LifecycleEnvironment()); private final MetricRegistry metrics = new MetricRegistry(); private final Environment environment = mock(Environment.class); private final ServletEnvironment servlets = mock(ServletEnvironment.class); private final FilterRegistration.Dynamic filterDynamic = mock(FilterRegistration.Dynamic.class); private final ServletRegistration.Dynamic servletDynamic = mock(ServletRegistration.Dynamic.class); private final JerseyEnvironment jersey = mock(JerseyEnvironment.class); private final HealthCheckRegistry healthChecks = mock(HealthCheckRegistry.class); private final HaraHachiBuApplication application = new HaraHachiBuApplication(); private final HaraHachiBuConfiguration config = new HaraHachiBuConfiguration();
private final ProxyConfiguration proxyConfiguration = new ProxyConfiguration();
flaxsearch/harahachibu
harahachibu/src/test/java/uk/co/flax/harahachibu/HaraHachiBuApplicationTest.java
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/DiskSpaceConfiguration.java // public class DiskSpaceConfiguration { // // public static final String ELASTICSEARCH_CHECKER = "elasticsearch"; // public static final String SOLR_LOCAL_CHECKER = "solr"; // public static final String CLUSTER_CHECKER = "cluster"; // // @NotNull // private String checkerType; // // @NotNull // private String threshold; // // @NotNull // private Map<String, Object> configuration = new HashMap<>(); // // // public String getCheckerType() { // return checkerType; // } // // public void setCheckerType(String checkerType) { // this.checkerType = checkerType; // } // // public String getThreshold() { // return threshold; // } // // public void setThreshold(String threshold) { // this.threshold = threshold; // } // // public Map<String, Object> getConfiguration() { // return configuration; // } // // public void setConfiguration(Map<String, Object> configuration) { // this.configuration = configuration; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/servlets/DiskSpaceProxyServlet.java // public class DiskSpaceProxyServlet extends ProxyServlet { // // public static final String PROXY_PATH_PREFIX = "/proxy"; // // public static final String DESTINATION_SERVER_PARAM = "destinationServerPrefix"; // // private static final Logger LOGGER = LoggerFactory.getLogger(DiskSpaceProxyServlet.class); // // @Override // protected String rewriteTarget(HttpServletRequest request) { // final String target; // // if (!validateDestination(request.getServerName(), request.getServerPort())) { // target = null; // } else { // final String path = request.getRequestURI(); // // if (StringUtils.isBlank(path)) { // LOGGER.debug("No path given extracted from {}", request.getRequestURI()); // target = null; // } else if (!path.startsWith(PROXY_PATH_PREFIX)) { // target = null; // } else { // final String shortPath = path.substring(PROXY_PATH_PREFIX.length()); // final StringBuilder targetBuilder = new StringBuilder(getInitParameter(DESTINATION_SERVER_PARAM)) // .append(shortPath); // if (StringUtils.isNotBlank(request.getQueryString())) { // targetBuilder.append("?").append(request.getQueryString()); // } // // target = targetBuilder.toString(); // } // } // // return target; // } // // }
import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.*; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.health.HealthCheckRegistry; import io.dropwizard.jersey.setup.JerseyEnvironment; import io.dropwizard.jetty.setup.ServletEnvironment; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; import io.dropwizard.setup.Environment; import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.config.DiskSpaceConfiguration; import uk.co.flax.harahachibu.config.ProxyConfiguration; import uk.co.flax.harahachibu.servlets.DiskSpaceProxyServlet; import javax.servlet.Filter; import javax.servlet.FilterRegistration; import javax.servlet.ServletRegistration;
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu; /** * Unit tests for the Hara Hachi Bu application class. * * Created by mlp on 13/04/16. */ public class HaraHachiBuApplicationTest { private final LifecycleEnvironment lifecycleEnvironment = spy(new LifecycleEnvironment()); private final MetricRegistry metrics = new MetricRegistry(); private final Environment environment = mock(Environment.class); private final ServletEnvironment servlets = mock(ServletEnvironment.class); private final FilterRegistration.Dynamic filterDynamic = mock(FilterRegistration.Dynamic.class); private final ServletRegistration.Dynamic servletDynamic = mock(ServletRegistration.Dynamic.class); private final JerseyEnvironment jersey = mock(JerseyEnvironment.class); private final HealthCheckRegistry healthChecks = mock(HealthCheckRegistry.class); private final HaraHachiBuApplication application = new HaraHachiBuApplication(); private final HaraHachiBuConfiguration config = new HaraHachiBuConfiguration(); private final ProxyConfiguration proxyConfiguration = new ProxyConfiguration();
// Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/DiskSpaceConfiguration.java // public class DiskSpaceConfiguration { // // public static final String ELASTICSEARCH_CHECKER = "elasticsearch"; // public static final String SOLR_LOCAL_CHECKER = "solr"; // public static final String CLUSTER_CHECKER = "cluster"; // // @NotNull // private String checkerType; // // @NotNull // private String threshold; // // @NotNull // private Map<String, Object> configuration = new HashMap<>(); // // // public String getCheckerType() { // return checkerType; // } // // public void setCheckerType(String checkerType) { // this.checkerType = checkerType; // } // // public String getThreshold() { // return threshold; // } // // public void setThreshold(String threshold) { // this.threshold = threshold; // } // // public Map<String, Object> getConfiguration() { // return configuration; // } // // public void setConfiguration(Map<String, Object> configuration) { // this.configuration = configuration; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/config/ProxyConfiguration.java // public class ProxyConfiguration { // // private int errorStatus = 503; // // @NotNull // private String destinationServer; // // private List<String> checkUrls = new ArrayList<>(); // // public int getErrorStatus() { // return errorStatus; // } // // public void setErrorStatus(int status) { // this.errorStatus = status; // } // // public String getDestinationServer() { // return destinationServer; // } // // public void setDestinationServer(String destinationServer) { // this.destinationServer = destinationServer; // } // // public List<String> getCheckUrls() { // return checkUrls; // } // // public void setCheckUrls(List<String> checkUrls) { // this.checkUrls = checkUrls; // } // } // // Path: harahachibu/src/main/java/uk/co/flax/harahachibu/servlets/DiskSpaceProxyServlet.java // public class DiskSpaceProxyServlet extends ProxyServlet { // // public static final String PROXY_PATH_PREFIX = "/proxy"; // // public static final String DESTINATION_SERVER_PARAM = "destinationServerPrefix"; // // private static final Logger LOGGER = LoggerFactory.getLogger(DiskSpaceProxyServlet.class); // // @Override // protected String rewriteTarget(HttpServletRequest request) { // final String target; // // if (!validateDestination(request.getServerName(), request.getServerPort())) { // target = null; // } else { // final String path = request.getRequestURI(); // // if (StringUtils.isBlank(path)) { // LOGGER.debug("No path given extracted from {}", request.getRequestURI()); // target = null; // } else if (!path.startsWith(PROXY_PATH_PREFIX)) { // target = null; // } else { // final String shortPath = path.substring(PROXY_PATH_PREFIX.length()); // final StringBuilder targetBuilder = new StringBuilder(getInitParameter(DESTINATION_SERVER_PARAM)) // .append(shortPath); // if (StringUtils.isNotBlank(request.getQueryString())) { // targetBuilder.append("?").append(request.getQueryString()); // } // // target = targetBuilder.toString(); // } // } // // return target; // } // // } // Path: harahachibu/src/test/java/uk/co/flax/harahachibu/HaraHachiBuApplicationTest.java import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.*; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.health.HealthCheckRegistry; import io.dropwizard.jersey.setup.JerseyEnvironment; import io.dropwizard.jetty.setup.ServletEnvironment; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; import io.dropwizard.setup.Environment; import org.junit.Before; import org.junit.Test; import uk.co.flax.harahachibu.config.DiskSpaceConfiguration; import uk.co.flax.harahachibu.config.ProxyConfiguration; import uk.co.flax.harahachibu.servlets.DiskSpaceProxyServlet; import javax.servlet.Filter; import javax.servlet.FilterRegistration; import javax.servlet.ServletRegistration; /** * Copyright (c) 2016 Lemur Consulting Ltd. * <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 uk.co.flax.harahachibu; /** * Unit tests for the Hara Hachi Bu application class. * * Created by mlp on 13/04/16. */ public class HaraHachiBuApplicationTest { private final LifecycleEnvironment lifecycleEnvironment = spy(new LifecycleEnvironment()); private final MetricRegistry metrics = new MetricRegistry(); private final Environment environment = mock(Environment.class); private final ServletEnvironment servlets = mock(ServletEnvironment.class); private final FilterRegistration.Dynamic filterDynamic = mock(FilterRegistration.Dynamic.class); private final ServletRegistration.Dynamic servletDynamic = mock(ServletRegistration.Dynamic.class); private final JerseyEnvironment jersey = mock(JerseyEnvironment.class); private final HealthCheckRegistry healthChecks = mock(HealthCheckRegistry.class); private final HaraHachiBuApplication application = new HaraHachiBuApplication(); private final HaraHachiBuConfiguration config = new HaraHachiBuConfiguration(); private final ProxyConfiguration proxyConfiguration = new ProxyConfiguration();
private final DiskSpaceConfiguration diskSpaceConfiguration = new DiskSpaceConfiguration();
MicBrain/Topographic-Maps
trip/Road.java
// Path: trip/Main.java // static void error(String format, Object... args) { // throw new IllegalArgumentException(String.format(format, args)); // }
import static trip.Main.error;
package trip; /** Represents a road between two Locations. * @author P. N. Hilfinger */ class Road { /** A Road whose name is NAME, going in DIRECTION, and of given * LENGTH. */ Road(String name, Direction direction, double length) { if (length < 0) {
// Path: trip/Main.java // static void error(String format, Object... args) { // throw new IllegalArgumentException(String.format(format, args)); // } // Path: trip/Road.java import static trip.Main.error; package trip; /** Represents a road between two Locations. * @author P. N. Hilfinger */ class Road { /** A Road whose name is NAME, going in DIRECTION, and of given * LENGTH. */ Road(String name, Direction direction, double length) { if (length < 0) {
error("Road %s given negative length.", length);
MicBrain/Topographic-Maps
make/Maker.java
// Path: graph/DepthFirstTraversal.java // public class DepthFirstTraversal extends Traversal { // // /** A depth-first Traversal of G, using FRINGE as the fringe. */ // protected DepthFirstTraversal(Graph G) { // super(G, Collections.asLifoQueue(new ArrayDeque<Integer>())); // } // // @Override // protected boolean visit(int v) { // return super.visit(v); // } // // @Override // protected boolean postVisit(int v) { // return super.postVisit(v); // } // // @Override // protected boolean shouldPostVisit(int v) { // return true; // } // } // // Path: make/Main.java // static void error(String format, Object... args) { // throw new IllegalArgumentException(String.format(format, args)); // }
import graph.DepthFirstTraversal; import java.io.FileReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.NoSuchElementException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Set; import java.util.Scanner; import java.io.FileNotFoundException; import static java.util.Arrays.asList; import static make.Main.error;
package make; /** Represents a makefile. * @author P. N. Hilfinger */ class Maker { /** Describes Makefile lines that are ignored. */ static final Pattern IGNORED = Pattern.compile("\\s*(#.*)?"); /** Describes a rule header in a makefile: TARGET: DEPENDENCIES. */ static final Pattern HEADER = Pattern.compile("([^:\\s]+)\\s*:\\s*(.*?)\\s*"); /** Describes a sequence of valid targets and whitespace. */ static final Pattern TARGETS = Pattern.compile("[^:=#\\\\]*$"); /** Describes an indented command line. */ static final Pattern COMMAND = Pattern.compile("(\\s+.*)"); /** Describes the separator on dependencies lines. */ static final Pattern SPACES = Pattern.compile("\\p{Blank}+"); /** Read and store the ages of existing targets from the * file named FILEINFONAME. */ void readFileAges(String fileInfoName) { String name; name = "<unknown>"; int sucTime = 10; try { Scanner inp = new Scanner(new FileReader(fileInfoName)); _currentTime = inp.nextInt(); while (inp.hasNext()) { String dest = inp.next(); boolean firstCond = TARGETS.matcher(dest).matches(); if (!firstCond) {
// Path: graph/DepthFirstTraversal.java // public class DepthFirstTraversal extends Traversal { // // /** A depth-first Traversal of G, using FRINGE as the fringe. */ // protected DepthFirstTraversal(Graph G) { // super(G, Collections.asLifoQueue(new ArrayDeque<Integer>())); // } // // @Override // protected boolean visit(int v) { // return super.visit(v); // } // // @Override // protected boolean postVisit(int v) { // return super.postVisit(v); // } // // @Override // protected boolean shouldPostVisit(int v) { // return true; // } // } // // Path: make/Main.java // static void error(String format, Object... args) { // throw new IllegalArgumentException(String.format(format, args)); // } // Path: make/Maker.java import graph.DepthFirstTraversal; import java.io.FileReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.NoSuchElementException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Set; import java.util.Scanner; import java.io.FileNotFoundException; import static java.util.Arrays.asList; import static make.Main.error; package make; /** Represents a makefile. * @author P. N. Hilfinger */ class Maker { /** Describes Makefile lines that are ignored. */ static final Pattern IGNORED = Pattern.compile("\\s*(#.*)?"); /** Describes a rule header in a makefile: TARGET: DEPENDENCIES. */ static final Pattern HEADER = Pattern.compile("([^:\\s]+)\\s*:\\s*(.*?)\\s*"); /** Describes a sequence of valid targets and whitespace. */ static final Pattern TARGETS = Pattern.compile("[^:=#\\\\]*$"); /** Describes an indented command line. */ static final Pattern COMMAND = Pattern.compile("(\\s+.*)"); /** Describes the separator on dependencies lines. */ static final Pattern SPACES = Pattern.compile("\\p{Blank}+"); /** Read and store the ages of existing targets from the * file named FILEINFONAME. */ void readFileAges(String fileInfoName) { String name; name = "<unknown>"; int sucTime = 10; try { Scanner inp = new Scanner(new FileReader(fileInfoName)); _currentTime = inp.nextInt(); while (inp.hasNext()) { String dest = inp.next(); boolean firstCond = TARGETS.matcher(dest).matches(); if (!firstCond) {
error("Illegal Target: '%s'", dest);
MicBrain/Topographic-Maps
make/Maker.java
// Path: graph/DepthFirstTraversal.java // public class DepthFirstTraversal extends Traversal { // // /** A depth-first Traversal of G, using FRINGE as the fringe. */ // protected DepthFirstTraversal(Graph G) { // super(G, Collections.asLifoQueue(new ArrayDeque<Integer>())); // } // // @Override // protected boolean visit(int v) { // return super.visit(v); // } // // @Override // protected boolean postVisit(int v) { // return super.postVisit(v); // } // // @Override // protected boolean shouldPostVisit(int v) { // return true; // } // } // // Path: make/Main.java // static void error(String format, Object... args) { // throw new IllegalArgumentException(String.format(format, args)); // }
import graph.DepthFirstTraversal; import java.io.FileReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.NoSuchElementException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Set; import java.util.Scanner; import java.io.FileNotFoundException; import static java.util.Arrays.asList; import static make.Main.error;
/** Return my dependence graph. */ final Depends getGraph() { return _depends; } /** Return the initial age of TARGET, if it exists, or null if it * does not. */ final Integer getInitialAge(String target) { return _ages.get(target); } /** Returns the current time (to be attached to rebuilt targets). */ final int getCurrentTime() { return _currentTime; } /** The current time. Should be no earlier than the time on the * latest file. */ private int _currentTime; /** The makefile dependency graph. */ private Depends _depends = new Depends(); /** Mapping of target names to their ages. */ private HashMap<String, Integer> _ages = new HashMap<>(); /** Mapping of target names to their Rules. */ private HashMap<String, Rule> _targets = new HashMap<>(); /** Depth-first traversal of my vertices. */ private MakeTraversal _traversal; /** Traversal for make dependency graph. */
// Path: graph/DepthFirstTraversal.java // public class DepthFirstTraversal extends Traversal { // // /** A depth-first Traversal of G, using FRINGE as the fringe. */ // protected DepthFirstTraversal(Graph G) { // super(G, Collections.asLifoQueue(new ArrayDeque<Integer>())); // } // // @Override // protected boolean visit(int v) { // return super.visit(v); // } // // @Override // protected boolean postVisit(int v) { // return super.postVisit(v); // } // // @Override // protected boolean shouldPostVisit(int v) { // return true; // } // } // // Path: make/Main.java // static void error(String format, Object... args) { // throw new IllegalArgumentException(String.format(format, args)); // } // Path: make/Maker.java import graph.DepthFirstTraversal; import java.io.FileReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.NoSuchElementException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Set; import java.util.Scanner; import java.io.FileNotFoundException; import static java.util.Arrays.asList; import static make.Main.error; /** Return my dependence graph. */ final Depends getGraph() { return _depends; } /** Return the initial age of TARGET, if it exists, or null if it * does not. */ final Integer getInitialAge(String target) { return _ages.get(target); } /** Returns the current time (to be attached to rebuilt targets). */ final int getCurrentTime() { return _currentTime; } /** The current time. Should be no earlier than the time on the * latest file. */ private int _currentTime; /** The makefile dependency graph. */ private Depends _depends = new Depends(); /** Mapping of target names to their ages. */ private HashMap<String, Integer> _ages = new HashMap<>(); /** Mapping of target names to their Rules. */ private HashMap<String, Rule> _targets = new HashMap<>(); /** Depth-first traversal of my vertices. */ private MakeTraversal _traversal; /** Traversal for make dependency graph. */
class MakeTraversal extends DepthFirstTraversal {
MicBrain/Topographic-Maps
make/Rule.java
// Path: graph/Iteration.java // public abstract class Iteration<Type> // implements Iterator<Type>, Iterable<Type> { // // @Override // public Iterator<Type> iterator() { // return this; // } // // @Override // public void remove() { // throw new UnsupportedOperationException("remove not supported"); // } // // /** A wrapper class that turns an Iterator<TYPE> into an Iteration<TYPE>. */ // private static class SimpleIteration<Type> extends Iteration<Type> { // /** ITER as an iteration. */ // SimpleIteration(Iterator<Type> iter) { // _iter = iter; // } // // @Override // public boolean hasNext() { // return _iter.hasNext(); // } // // @Override // public Type next() { // return _iter.next(); // } // // /** The iterator with which I was constructed. */ // private Iterator<Type> _iter; // } // // /** Returns an Iteration<TYPE> that delegates to IT. */ // static <Type> Iteration<Type> iteration(Iterator<Type> it) { // return new SimpleIteration<>(it); // } // // /** Returns an Iteration<TYPE> that delegates to ITERABLE. */ // static <Type> Iteration<Type> iteration(Iterable<Type> iterable) { // return new SimpleIteration<>(iterable.iterator()); // } // // } // // Path: make/Main.java // static void error(String format, Object... args) { // throw new IllegalArgumentException(String.format(format, args)); // }
import java.util.ArrayList; import java.util.List; import graph.Iteration; import static make.Main.error;
package make; /** Represents the rules concerning a single target in a makefile. * @author P. N. Hilfinger */ class Rule { /** A new Rule for TARGET. Adds corresponding vertex to MAKER's dependence * graph. */ Rule(Maker maker, String target) { _maker = maker; _depends = _maker.getGraph(); _target = target; _vertex = _depends.add(this); _time = _maker.getInitialAge(target); _finished = false; } /** Add the target of DEPENDENT to my dependencies. */ void addDependency(Rule dependent) { _depends.add(dependent); _depends.add(getVertex(), dependent.getVertex()); } /** Add COMMANDS to my command set. Signals IllegalStateException if * COMMANDS is non-empty, but I already have a non-empty command set. */ void addCommands(List<String> commands) { try { if (_commands.size() != 0) { if (commands.size() != 0) {
// Path: graph/Iteration.java // public abstract class Iteration<Type> // implements Iterator<Type>, Iterable<Type> { // // @Override // public Iterator<Type> iterator() { // return this; // } // // @Override // public void remove() { // throw new UnsupportedOperationException("remove not supported"); // } // // /** A wrapper class that turns an Iterator<TYPE> into an Iteration<TYPE>. */ // private static class SimpleIteration<Type> extends Iteration<Type> { // /** ITER as an iteration. */ // SimpleIteration(Iterator<Type> iter) { // _iter = iter; // } // // @Override // public boolean hasNext() { // return _iter.hasNext(); // } // // @Override // public Type next() { // return _iter.next(); // } // // /** The iterator with which I was constructed. */ // private Iterator<Type> _iter; // } // // /** Returns an Iteration<TYPE> that delegates to IT. */ // static <Type> Iteration<Type> iteration(Iterator<Type> it) { // return new SimpleIteration<>(it); // } // // /** Returns an Iteration<TYPE> that delegates to ITERABLE. */ // static <Type> Iteration<Type> iteration(Iterable<Type> iterable) { // return new SimpleIteration<>(iterable.iterator()); // } // // } // // Path: make/Main.java // static void error(String format, Object... args) { // throw new IllegalArgumentException(String.format(format, args)); // } // Path: make/Rule.java import java.util.ArrayList; import java.util.List; import graph.Iteration; import static make.Main.error; package make; /** Represents the rules concerning a single target in a makefile. * @author P. N. Hilfinger */ class Rule { /** A new Rule for TARGET. Adds corresponding vertex to MAKER's dependence * graph. */ Rule(Maker maker, String target) { _maker = maker; _depends = _maker.getGraph(); _target = target; _vertex = _depends.add(this); _time = _maker.getInitialAge(target); _finished = false; } /** Add the target of DEPENDENT to my dependencies. */ void addDependency(Rule dependent) { _depends.add(dependent); _depends.add(getVertex(), dependent.getVertex()); } /** Add COMMANDS to my command set. Signals IllegalStateException if * COMMANDS is non-empty, but I already have a non-empty command set. */ void addCommands(List<String> commands) { try { if (_commands.size() != 0) { if (commands.size() != 0) {
error("Input and commands are not empty.");
MicBrain/Topographic-Maps
make/Rule.java
// Path: graph/Iteration.java // public abstract class Iteration<Type> // implements Iterator<Type>, Iterable<Type> { // // @Override // public Iterator<Type> iterator() { // return this; // } // // @Override // public void remove() { // throw new UnsupportedOperationException("remove not supported"); // } // // /** A wrapper class that turns an Iterator<TYPE> into an Iteration<TYPE>. */ // private static class SimpleIteration<Type> extends Iteration<Type> { // /** ITER as an iteration. */ // SimpleIteration(Iterator<Type> iter) { // _iter = iter; // } // // @Override // public boolean hasNext() { // return _iter.hasNext(); // } // // @Override // public Type next() { // return _iter.next(); // } // // /** The iterator with which I was constructed. */ // private Iterator<Type> _iter; // } // // /** Returns an Iteration<TYPE> that delegates to IT. */ // static <Type> Iteration<Type> iteration(Iterator<Type> it) { // return new SimpleIteration<>(it); // } // // /** Returns an Iteration<TYPE> that delegates to ITERABLE. */ // static <Type> Iteration<Type> iteration(Iterable<Type> iterable) { // return new SimpleIteration<>(iterable.iterator()); // } // // } // // Path: make/Main.java // static void error(String format, Object... args) { // throw new IllegalArgumentException(String.format(format, args)); // }
import java.util.ArrayList; import java.util.List; import graph.Iteration; import static make.Main.error;
package make; /** Represents the rules concerning a single target in a makefile. * @author P. N. Hilfinger */ class Rule { /** A new Rule for TARGET. Adds corresponding vertex to MAKER's dependence * graph. */ Rule(Maker maker, String target) { _maker = maker; _depends = _maker.getGraph(); _target = target; _vertex = _depends.add(this); _time = _maker.getInitialAge(target); _finished = false; } /** Add the target of DEPENDENT to my dependencies. */ void addDependency(Rule dependent) { _depends.add(dependent); _depends.add(getVertex(), dependent.getVertex()); } /** Add COMMANDS to my command set. Signals IllegalStateException if * COMMANDS is non-empty, but I already have a non-empty command set. */ void addCommands(List<String> commands) { try { if (_commands.size() != 0) { if (commands.size() != 0) { error("Input and commands are not empty."); } } } catch (IllegalStateException exp) { error("Not legal."); } for (String comm : commands) { _commands.add(comm); } } /** Return the vertex representing me. */ int getVertex() { return _vertex; } /** Return my target. */ String getTarget() { return _target; } /** Return my target's current change time. */ Integer getTime() { return _time; } /** Return true iff I have not yet been brought up to date. */ boolean isUnfinished() { return !_finished; } /** Check that dependencies are in fact built before it's time to rebuild * a node. */ private void checkFinishedDependencies() { boolean checker = true;
// Path: graph/Iteration.java // public abstract class Iteration<Type> // implements Iterator<Type>, Iterable<Type> { // // @Override // public Iterator<Type> iterator() { // return this; // } // // @Override // public void remove() { // throw new UnsupportedOperationException("remove not supported"); // } // // /** A wrapper class that turns an Iterator<TYPE> into an Iteration<TYPE>. */ // private static class SimpleIteration<Type> extends Iteration<Type> { // /** ITER as an iteration. */ // SimpleIteration(Iterator<Type> iter) { // _iter = iter; // } // // @Override // public boolean hasNext() { // return _iter.hasNext(); // } // // @Override // public Type next() { // return _iter.next(); // } // // /** The iterator with which I was constructed. */ // private Iterator<Type> _iter; // } // // /** Returns an Iteration<TYPE> that delegates to IT. */ // static <Type> Iteration<Type> iteration(Iterator<Type> it) { // return new SimpleIteration<>(it); // } // // /** Returns an Iteration<TYPE> that delegates to ITERABLE. */ // static <Type> Iteration<Type> iteration(Iterable<Type> iterable) { // return new SimpleIteration<>(iterable.iterator()); // } // // } // // Path: make/Main.java // static void error(String format, Object... args) { // throw new IllegalArgumentException(String.format(format, args)); // } // Path: make/Rule.java import java.util.ArrayList; import java.util.List; import graph.Iteration; import static make.Main.error; package make; /** Represents the rules concerning a single target in a makefile. * @author P. N. Hilfinger */ class Rule { /** A new Rule for TARGET. Adds corresponding vertex to MAKER's dependence * graph. */ Rule(Maker maker, String target) { _maker = maker; _depends = _maker.getGraph(); _target = target; _vertex = _depends.add(this); _time = _maker.getInitialAge(target); _finished = false; } /** Add the target of DEPENDENT to my dependencies. */ void addDependency(Rule dependent) { _depends.add(dependent); _depends.add(getVertex(), dependent.getVertex()); } /** Add COMMANDS to my command set. Signals IllegalStateException if * COMMANDS is non-empty, but I already have a non-empty command set. */ void addCommands(List<String> commands) { try { if (_commands.size() != 0) { if (commands.size() != 0) { error("Input and commands are not empty."); } } } catch (IllegalStateException exp) { error("Not legal."); } for (String comm : commands) { _commands.add(comm); } } /** Return the vertex representing me. */ int getVertex() { return _vertex; } /** Return my target. */ String getTarget() { return _target; } /** Return my target's current change time. */ Integer getTime() { return _time; } /** Return true iff I have not yet been brought up to date. */ boolean isUnfinished() { return !_finished; } /** Check that dependencies are in fact built before it's time to rebuild * a node. */ private void checkFinishedDependencies() { boolean checker = true;
Iteration<Integer> par = _depends.successors(getVertex());
MicBrain/Topographic-Maps
trip/Direction.java
// Path: trip/Main.java // static void error(String format, Object... args) { // throw new IllegalArgumentException(String.format(format, args)); // }
import static trip.Main.error;
package trip; /** Represents the direction of a road segment. * @author P. N. Hilfinger */ enum Direction { /** Directions: NS (from north to south), SN (from south to * north), WE (from west to east), EW (from east to west). */ NS("south"), SN("north"), WE("east"), EW("west"); /** A new Direction, supplying DIRNAME as the full name of the * forward direction. */ Direction(String dirName) { _dirName = dirName; } /** Return the direction opposite me. */ Direction reverse() { switch (this) { case NS: return SN; case SN: return NS; case EW: return WE; case WE: return EW; default: return this; } } /** Returns a printable, English name for my "to" direction. */ String fullName() { return _dirName; } /** Returns valueOf(NAME), but gives a more specific message on error. */ static Direction parse(String name) { try { return valueOf(name); } catch (IllegalArgumentException excp) {
// Path: trip/Main.java // static void error(String format, Object... args) { // throw new IllegalArgumentException(String.format(format, args)); // } // Path: trip/Direction.java import static trip.Main.error; package trip; /** Represents the direction of a road segment. * @author P. N. Hilfinger */ enum Direction { /** Directions: NS (from north to south), SN (from south to * north), WE (from west to east), EW (from east to west). */ NS("south"), SN("north"), WE("east"), EW("west"); /** A new Direction, supplying DIRNAME as the full name of the * forward direction. */ Direction(String dirName) { _dirName = dirName; } /** Return the direction opposite me. */ Direction reverse() { switch (this) { case NS: return SN; case SN: return NS; case EW: return WE; case WE: return EW; default: return this; } } /** Returns a printable, English name for my "to" direction. */ String fullName() { return _dirName; } /** Returns valueOf(NAME), but gives a more specific message on error. */ static Direction parse(String name) { try { return valueOf(name); } catch (IllegalArgumentException excp) {
error("improper direction name: %s", name);
dgradecak/alfresco-mvc
alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/config/DefaultAlfrescoMvcServletContextConfiguration.java
// Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/AlfrescoApiResponseInterceptor.java // @ControllerAdvice // public class AlfrescoApiResponseInterceptor implements ResponseBodyAdvice<Object> { // // private final ResourceWebScriptHelper webscriptHelper; // private final boolean globalAlfrescoResponse;; // // public AlfrescoApiResponseInterceptor(final ResourceWebScriptHelper webscriptHelper) { // this(webscriptHelper, false); // } // // public AlfrescoApiResponseInterceptor(final ResourceWebScriptHelper webscriptHelper, // final boolean globalAlfrescoResponse) { // this.webscriptHelper = webscriptHelper; // this.globalAlfrescoResponse = globalAlfrescoResponse; // } // // @Override // public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, // Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, // ServerHttpResponse response) { // // boolean useAlfrescoResponse = globalAlfrescoResponse; // // if (!useAlfrescoResponse) { // AlfrescoRestResponse methodAnnotation = returnType.getMethodAnnotation(AlfrescoRestResponse.class); // if (methodAnnotation == null) { // methodAnnotation = returnType.getContainingClass().getAnnotation(AlfrescoRestResponse.class); // } // // if (methodAnnotation != null) { // useAlfrescoResponse = true; // } // } // // if (useAlfrescoResponse) { // if (!(request instanceof ServletServerHttpRequest)) { // throw new RuntimeException( // "the request must be an instance of org.springframework.http.server.ServletServerHttpRequest"); // } // // HttpServletRequest r = ((ServletServerHttpRequest) request).getServletRequest(); // // if (!(r instanceof WebscriptRequestWrapper)) { // throw new RuntimeException( // "the request must be an instance of com.gradecak.alfresco.mvc.webscript.DispatcherWebscript.WebscriptRequestWrapper. It seems the request is not coming from Alfresco @MVC"); // } // // WebScriptServletRequest a = ((WebscriptRequestWrapper) r).getWebScriptServletRequest(); // // return webscriptHelper.processAdditionsToTheResponse(null, null, null, getDefaultParameters(a), body); // } // // return body; // } // // @Override // public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { // return converterType.isAssignableFrom(MappingJackson2HttpMessageConverter.class); // } // // static public Params getDefaultParameters(WebScriptRequest wsr) { // if (wsr != null) { // final RecognizedParams params = new AlfrescoRecognizedParamsExtractor().getRecognizedParams(wsr); // return Params.valueOf(params, null, null, wsr); // } // Params parameters = Params.valueOf("", null, null); // return parameters; // } // }
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; import java.util.TimeZone; import org.alfresco.rest.framework.jacksonextensions.RestJsonModule; import org.alfresco.rest.framework.webscripts.ResourceWebScriptHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.gradecak.alfresco.mvc.rest.AlfrescoApiResponseInterceptor;
/** * Copyright gradecak.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 com.gradecak.alfresco.mvc.rest.config; @Configuration public class DefaultAlfrescoMvcServletContextConfiguration implements WebMvcConfigurer { private final RestJsonModule alfrescoRestJsonModule; @Autowired public DefaultAlfrescoMvcServletContextConfiguration(RestJsonModule alfrescoRestJsonModule) { this.alfrescoRestJsonModule = alfrescoRestJsonModule; } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { resolvers.add(new ParamsHandlerMethodArgumentResolver()); } @Bean
// Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/AlfrescoApiResponseInterceptor.java // @ControllerAdvice // public class AlfrescoApiResponseInterceptor implements ResponseBodyAdvice<Object> { // // private final ResourceWebScriptHelper webscriptHelper; // private final boolean globalAlfrescoResponse;; // // public AlfrescoApiResponseInterceptor(final ResourceWebScriptHelper webscriptHelper) { // this(webscriptHelper, false); // } // // public AlfrescoApiResponseInterceptor(final ResourceWebScriptHelper webscriptHelper, // final boolean globalAlfrescoResponse) { // this.webscriptHelper = webscriptHelper; // this.globalAlfrescoResponse = globalAlfrescoResponse; // } // // @Override // public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, // Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, // ServerHttpResponse response) { // // boolean useAlfrescoResponse = globalAlfrescoResponse; // // if (!useAlfrescoResponse) { // AlfrescoRestResponse methodAnnotation = returnType.getMethodAnnotation(AlfrescoRestResponse.class); // if (methodAnnotation == null) { // methodAnnotation = returnType.getContainingClass().getAnnotation(AlfrescoRestResponse.class); // } // // if (methodAnnotation != null) { // useAlfrescoResponse = true; // } // } // // if (useAlfrescoResponse) { // if (!(request instanceof ServletServerHttpRequest)) { // throw new RuntimeException( // "the request must be an instance of org.springframework.http.server.ServletServerHttpRequest"); // } // // HttpServletRequest r = ((ServletServerHttpRequest) request).getServletRequest(); // // if (!(r instanceof WebscriptRequestWrapper)) { // throw new RuntimeException( // "the request must be an instance of com.gradecak.alfresco.mvc.webscript.DispatcherWebscript.WebscriptRequestWrapper. It seems the request is not coming from Alfresco @MVC"); // } // // WebScriptServletRequest a = ((WebscriptRequestWrapper) r).getWebScriptServletRequest(); // // return webscriptHelper.processAdditionsToTheResponse(null, null, null, getDefaultParameters(a), body); // } // // return body; // } // // @Override // public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { // return converterType.isAssignableFrom(MappingJackson2HttpMessageConverter.class); // } // // static public Params getDefaultParameters(WebScriptRequest wsr) { // if (wsr != null) { // final RecognizedParams params = new AlfrescoRecognizedParamsExtractor().getRecognizedParams(wsr); // return Params.valueOf(params, null, null, wsr); // } // Params parameters = Params.valueOf("", null, null); // return parameters; // } // } // Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/config/DefaultAlfrescoMvcServletContextConfiguration.java import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; import java.util.TimeZone; import org.alfresco.rest.framework.jacksonextensions.RestJsonModule; import org.alfresco.rest.framework.webscripts.ResourceWebScriptHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.gradecak.alfresco.mvc.rest.AlfrescoApiResponseInterceptor; /** * Copyright gradecak.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 com.gradecak.alfresco.mvc.rest.config; @Configuration public class DefaultAlfrescoMvcServletContextConfiguration implements WebMvcConfigurer { private final RestJsonModule alfrescoRestJsonModule; @Autowired public DefaultAlfrescoMvcServletContextConfiguration(RestJsonModule alfrescoRestJsonModule) { this.alfrescoRestJsonModule = alfrescoRestJsonModule; } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { resolvers.add(new ParamsHandlerMethodArgumentResolver()); } @Bean
public AlfrescoApiResponseInterceptor alfrescoResponseInterceptor(ResourceWebScriptHelper webscriptHelper) {
dgradecak/alfresco-mvc
alfresco-mvc-aop/src/test/java/com/gradecak/alfresco/mvc/aop/RunAsTest.java
// Path: alfresco-mvc-aop/src/test/java/com/gradecak/alfresco/mvc/service/RunAsService.java // @Service // public class RunAsService { // // @Autowired // private ServiceRegistry serviceRegistry; // // @AlfrescoRunAs("user") // public String getNamePropertyAsUser(final NodeRef nodeRef) { // Assert.isTrue("user".equals(AuthenticationUtil.getRunAsUser()), // "[Assertion failed] - this expression must be true"); // return (String) serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME); // } // // @AlfrescoRunAs(AuthenticationUtil.SYSTEM_USER_NAME) // public String getNamePropertyAsSystem(final NodeRef nodeRef) { // Assert.isTrue(AuthenticationUtil.SYSTEM_USER_NAME.equals(AuthenticationUtil.getRunAsUser()), // "[Assertion failed] - this expression must be true"); // return (String) serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME); // } // }
import static org.mockito.Mockito.when; import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.service.ServiceRegistry; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.security.AuthorityService; import org.alfresco.service.cmr.security.MutableAuthenticationService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.gradecak.alfresco.mvc.service.RunAsService;
/** * Copyright gradecak.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 com.gradecak.alfresco.mvc.aop; @ExtendWith(SpringExtension.class) @ContextConfiguration(value = { "classpath:test-aop-context.xml" }) public class RunAsTest { @Mock private MutableAuthenticationService authenticationService; @Mock private AuthorityService authorityService; @Mock private NodeService nodeService; @Autowired private ServiceRegistry serviceRegistry; @Autowired
// Path: alfresco-mvc-aop/src/test/java/com/gradecak/alfresco/mvc/service/RunAsService.java // @Service // public class RunAsService { // // @Autowired // private ServiceRegistry serviceRegistry; // // @AlfrescoRunAs("user") // public String getNamePropertyAsUser(final NodeRef nodeRef) { // Assert.isTrue("user".equals(AuthenticationUtil.getRunAsUser()), // "[Assertion failed] - this expression must be true"); // return (String) serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME); // } // // @AlfrescoRunAs(AuthenticationUtil.SYSTEM_USER_NAME) // public String getNamePropertyAsSystem(final NodeRef nodeRef) { // Assert.isTrue(AuthenticationUtil.SYSTEM_USER_NAME.equals(AuthenticationUtil.getRunAsUser()), // "[Assertion failed] - this expression must be true"); // return (String) serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME); // } // } // Path: alfresco-mvc-aop/src/test/java/com/gradecak/alfresco/mvc/aop/RunAsTest.java import static org.mockito.Mockito.when; import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.service.ServiceRegistry; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.security.AuthorityService; import org.alfresco.service.cmr.security.MutableAuthenticationService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.gradecak.alfresco.mvc.service.RunAsService; /** * Copyright gradecak.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 com.gradecak.alfresco.mvc.aop; @ExtendWith(SpringExtension.class) @ContextConfiguration(value = { "classpath:test-aop-context.xml" }) public class RunAsTest { @Mock private MutableAuthenticationService authenticationService; @Mock private AuthorityService authorityService; @Mock private NodeService nodeService; @Autowired private ServiceRegistry serviceRegistry; @Autowired
private RunAsService service;
dgradecak/alfresco-mvc
alfresco-mvc-aop/src/main/java/com/gradecak/alfresco/mvc/annotation/EnableAlfrescoMvcAop.java
// Path: alfresco-mvc-aop/src/main/java/com/gradecak/alfresco/mvc/aop/AlfrescoProxyRegistrar.java // public class AlfrescoProxyRegistrar implements ImportBeanDefinitionRegistrar { // // public static final String PACKAGE_PROXY_CREATOR_BEAN_NAME = "com.gradecak.alfresco.mvc.aop.alfrescoMvcPackageAutoProxyCreator"; // // public static final String AUTOWIRED_PROCESSOR_BEAN_NAME = // // "org.springframework.beans.factory.annotation.alfrescoMvcAutowiredAnnotationBeanPostProcessor"; // // private AnnotationAttributes attributes; // private AnnotationMetadata metadata; // // public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) { // // Assert.notNull(annotationMetadata, "AnnotationMetadata must not be null!"); // Assert.notNull(registry, "BeanDefinitionRegistry must not be null!"); // // boolean proxyBeanRegistered = false; // for (String beanName : PackageAutoProxyCreator.DEFAULT_INTERCEPTORS) { // if (registry.containsBeanDefinition(beanName)) { // proxyBeanRegistered = true; // break; // } // } // // if (!proxyBeanRegistered) { // XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(registry); // xmlReader.loadBeanDefinitions("classpath:com/gradecak/alfresco-mvc/alfresco-mvc-aop.xml"); // } // // // Guard against calls for sub-classes // if (annotationMetadata.getAnnotationAttributes(EnableAlfrescoMvcAop.class.getName()) == null) { // return; // } // // this.attributes = new AnnotationAttributes( // annotationMetadata.getAnnotationAttributes(EnableAlfrescoMvcAop.class.getName())); // this.metadata = annotationMetadata; // // Iterable<String> basePackages = getBasePackages(); // for (String basePackage : basePackages) { // registerOrEscalateApcAsRequired(PackageAutoProxyCreator.class, registry, null, basePackage); // } // // // if (!registry.containsBeanDefinition(AUTOWIRED_PROCESSOR_BEAN_NAME)) { // // RootBeanDefinition beanDefinition = new // // RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class); // // beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); // // registry.registerBeanDefinition(AUTOWIRED_PROCESSOR_BEAN_NAME, // // beanDefinition); // // } // // // if (!registry.containsBeanDefinition(CONFIGURATION_PROCESSOR_BEAN_NAME)) { // // RootBeanDefinition beanDefinition = new // // RootBeanDefinition(ConfigurationClassPostProcessor.class); // // beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); // // registry.registerBeanDefinition(CONFIGURATION_PROCESSOR_BEAN_NAME, // // beanDefinition); // // } // } // // public Iterable<String> getBasePackages() { // // String[] value = attributes.getStringArray("value"); // String[] basePackages = attributes.getStringArray("basePackages"); // Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses"); // // // Default configuration - return package of annotated class // if (value.length == 0 && basePackages.length == 0 && basePackageClasses.length == 0) { // String className = metadata.getClassName(); // return Collections.singleton(ClassUtils.getPackageName(className)); // } // // Set<String> packages = new HashSet<>(); // packages.addAll(Arrays.asList(value)); // packages.addAll(Arrays.asList(basePackages)); // // for (Class<?> typeName : basePackageClasses) { // packages.add(ClassUtils.getPackageName(typeName)); // } // // return packages; // } // // public static BeanDefinition registerOrEscalateApcAsRequired(Class<PackageAutoProxyCreator> cls, // BeanDefinitionRegistry registry, Object source, String basePackage) { // Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); // // String proxyPackageBeanName = PACKAGE_PROXY_CREATOR_BEAN_NAME + "." + basePackage; // if (registry.containsBeanDefinition(proxyPackageBeanName)) { // return null; // } // // RootBeanDefinition beanDefinition = new RootBeanDefinition(cls); // beanDefinition.setSource(source); // beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE); // beanDefinition.getPropertyValues().add("basePackage", basePackage); // beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); // registry.registerBeanDefinition(proxyPackageBeanName, beanDefinition); // return beanDefinition; // } // }
import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.AdviceMode; import org.springframework.context.annotation.Import; import com.gradecak.alfresco.mvc.aop.AlfrescoProxyRegistrar;
/** * Copyright gradecak.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 com.gradecak.alfresco.mvc.annotation; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited
// Path: alfresco-mvc-aop/src/main/java/com/gradecak/alfresco/mvc/aop/AlfrescoProxyRegistrar.java // public class AlfrescoProxyRegistrar implements ImportBeanDefinitionRegistrar { // // public static final String PACKAGE_PROXY_CREATOR_BEAN_NAME = "com.gradecak.alfresco.mvc.aop.alfrescoMvcPackageAutoProxyCreator"; // // public static final String AUTOWIRED_PROCESSOR_BEAN_NAME = // // "org.springframework.beans.factory.annotation.alfrescoMvcAutowiredAnnotationBeanPostProcessor"; // // private AnnotationAttributes attributes; // private AnnotationMetadata metadata; // // public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) { // // Assert.notNull(annotationMetadata, "AnnotationMetadata must not be null!"); // Assert.notNull(registry, "BeanDefinitionRegistry must not be null!"); // // boolean proxyBeanRegistered = false; // for (String beanName : PackageAutoProxyCreator.DEFAULT_INTERCEPTORS) { // if (registry.containsBeanDefinition(beanName)) { // proxyBeanRegistered = true; // break; // } // } // // if (!proxyBeanRegistered) { // XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(registry); // xmlReader.loadBeanDefinitions("classpath:com/gradecak/alfresco-mvc/alfresco-mvc-aop.xml"); // } // // // Guard against calls for sub-classes // if (annotationMetadata.getAnnotationAttributes(EnableAlfrescoMvcAop.class.getName()) == null) { // return; // } // // this.attributes = new AnnotationAttributes( // annotationMetadata.getAnnotationAttributes(EnableAlfrescoMvcAop.class.getName())); // this.metadata = annotationMetadata; // // Iterable<String> basePackages = getBasePackages(); // for (String basePackage : basePackages) { // registerOrEscalateApcAsRequired(PackageAutoProxyCreator.class, registry, null, basePackage); // } // // // if (!registry.containsBeanDefinition(AUTOWIRED_PROCESSOR_BEAN_NAME)) { // // RootBeanDefinition beanDefinition = new // // RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class); // // beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); // // registry.registerBeanDefinition(AUTOWIRED_PROCESSOR_BEAN_NAME, // // beanDefinition); // // } // // // if (!registry.containsBeanDefinition(CONFIGURATION_PROCESSOR_BEAN_NAME)) { // // RootBeanDefinition beanDefinition = new // // RootBeanDefinition(ConfigurationClassPostProcessor.class); // // beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); // // registry.registerBeanDefinition(CONFIGURATION_PROCESSOR_BEAN_NAME, // // beanDefinition); // // } // } // // public Iterable<String> getBasePackages() { // // String[] value = attributes.getStringArray("value"); // String[] basePackages = attributes.getStringArray("basePackages"); // Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses"); // // // Default configuration - return package of annotated class // if (value.length == 0 && basePackages.length == 0 && basePackageClasses.length == 0) { // String className = metadata.getClassName(); // return Collections.singleton(ClassUtils.getPackageName(className)); // } // // Set<String> packages = new HashSet<>(); // packages.addAll(Arrays.asList(value)); // packages.addAll(Arrays.asList(basePackages)); // // for (Class<?> typeName : basePackageClasses) { // packages.add(ClassUtils.getPackageName(typeName)); // } // // return packages; // } // // public static BeanDefinition registerOrEscalateApcAsRequired(Class<PackageAutoProxyCreator> cls, // BeanDefinitionRegistry registry, Object source, String basePackage) { // Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); // // String proxyPackageBeanName = PACKAGE_PROXY_CREATOR_BEAN_NAME + "." + basePackage; // if (registry.containsBeanDefinition(proxyPackageBeanName)) { // return null; // } // // RootBeanDefinition beanDefinition = new RootBeanDefinition(cls); // beanDefinition.setSource(source); // beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE); // beanDefinition.getPropertyValues().add("basePackage", basePackage); // beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); // registry.registerBeanDefinition(proxyPackageBeanName, beanDefinition); // return beanDefinition; // } // } // Path: alfresco-mvc-aop/src/main/java/com/gradecak/alfresco/mvc/annotation/EnableAlfrescoMvcAop.java import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.AdviceMode; import org.springframework.context.annotation.Import; import com.gradecak.alfresco.mvc.aop.AlfrescoProxyRegistrar; /** * Copyright gradecak.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 com.gradecak.alfresco.mvc.annotation; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited
@Import(AlfrescoProxyRegistrar.class)
dgradecak/alfresco-mvc
alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/config/AlfrescoMvcRestServletContext.java
// Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/controller/TestController.java // @Controller // @RequestMapping("/test") // public class TestController { // // @RequestMapping(value = "/get", method = { RequestMethod.GET }) // public ResponseEntity<?> get(@RequestParam String id) { // return ResponseEntity.ok(id); // } // // @RequestMapping(value = "/headers", method = { RequestMethod.GET }) // public ResponseEntity<?> headers(@RequestHeader MultiValueMap<String, String> headers) { // return ResponseEntity.ok().headers(new HttpHeaders(headers)).body("success"); // } // // @RequestMapping(value = "/cookies", method = { RequestMethod.GET }) // public ResponseEntity<?> cookies(HttpServletRequest req) { // // HttpHeaders headers = new HttpHeaders(); // Cookie[] cookies = req.getCookies(); // for (Cookie cookie : cookies) { // headers.add(cookie.getName(), cookie.getValue()); // } // // return ResponseEntity.ok().headers(new HttpHeaders(headers)).body("success"); // // } // // @RequestMapping(value = "/post", method = { RequestMethod.POST }) // public ResponseEntity<?> post(@RequestParam String id) { // return ResponseEntity.ok(id); // } // // @RequestMapping(value = "/delete", method = { RequestMethod.DELETE }) // public ResponseEntity<?> delete(@RequestParam String id) { // return ResponseEntity.ok(id); // } // // @RequestMapping(value = "/exception", method = { RequestMethod.GET }) // public ResponseEntity<?> exception(@RequestParam String id) { // throw new RuntimeException("test exception"); // } // // @RequestMapping(value = "/body", method = { RequestMethod.POST }) // public ResponseEntity<?> post(@RequestBody Map<String, String> body) { // return ResponseEntity.ok().header("id", body.get("id")).body("success"); // } // // @RequestMapping(value = "/ambigousMethod", method = { RequestMethod.DELETE, RequestMethod.PUT }) // public ResponseEntity<?> ambigousMethod() { // return ResponseEntity.ok().build(); // } // // @RequestMapping(value = "/ambigousMethod", method = { RequestMethod.DELETE }) // public ResponseEntity<?> ambigousMethod2() { // return ResponseEntity.ok().build(); // } // // @RequestMapping(value = "/put", method = { RequestMethod.PUT }) // public ResponseEntity<?> put() { // return ResponseEntity.ok().build(); // } // // @RequestMapping(value = "/download", method = { RequestMethod.GET }) // public ResponseEntity<?> download() throws IOException { // return ResponseEntity.ok() // .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"mvc.delete.desc.xml\"") // .body(new ClassPathResource( // "alfresco/extension/templates/webscripts/alfresco-mvc/mvc.delete.desc.xml")); // } // // @GetMapping(value = "noderef") // public ResponseEntity<?> noderef() throws IOException { // return ResponseEntity.ok(new NodeRef("a://a/a")); // } // // @GetMapping(value = "noderefAlfrescoResponse") // @AlfrescoRestResponse // public ResponseEntity<?> noderefAlfrescoResponse() throws IOException { // return ResponseEntity.ok(new NodeRef("a://a/a")); // } // // @RequestMapping(value = "/exceptionHandler", method = { RequestMethod.GET }) // public ResponseEntity<?> exceptionHandler() { // throw new IllegalArgumentException("test exception"); // } // // @GetMapping(value = "regexp/{regexpchars:.+}") // public ResponseEntity<?> regexpchars(@PathVariable String regexpchars) throws IOException { // return ResponseEntity.ok(regexpchars); // } // // @ExceptionHandler({ IllegalArgumentException.class }) // public ResponseEntity<?> handleIllegalArgumentException(IllegalArgumentException exc) { // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).header("error", "internal server error").build(); // } // }
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.gradecak.alfresco.mvc.controller.TestController; import com.gradecak.alfresco.mvc.rest.annotation.EnableWebAlfrescoMvc;
package com.gradecak.alfresco.mvc.config; @Configuration @EnableWebAlfrescoMvc
// Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/controller/TestController.java // @Controller // @RequestMapping("/test") // public class TestController { // // @RequestMapping(value = "/get", method = { RequestMethod.GET }) // public ResponseEntity<?> get(@RequestParam String id) { // return ResponseEntity.ok(id); // } // // @RequestMapping(value = "/headers", method = { RequestMethod.GET }) // public ResponseEntity<?> headers(@RequestHeader MultiValueMap<String, String> headers) { // return ResponseEntity.ok().headers(new HttpHeaders(headers)).body("success"); // } // // @RequestMapping(value = "/cookies", method = { RequestMethod.GET }) // public ResponseEntity<?> cookies(HttpServletRequest req) { // // HttpHeaders headers = new HttpHeaders(); // Cookie[] cookies = req.getCookies(); // for (Cookie cookie : cookies) { // headers.add(cookie.getName(), cookie.getValue()); // } // // return ResponseEntity.ok().headers(new HttpHeaders(headers)).body("success"); // // } // // @RequestMapping(value = "/post", method = { RequestMethod.POST }) // public ResponseEntity<?> post(@RequestParam String id) { // return ResponseEntity.ok(id); // } // // @RequestMapping(value = "/delete", method = { RequestMethod.DELETE }) // public ResponseEntity<?> delete(@RequestParam String id) { // return ResponseEntity.ok(id); // } // // @RequestMapping(value = "/exception", method = { RequestMethod.GET }) // public ResponseEntity<?> exception(@RequestParam String id) { // throw new RuntimeException("test exception"); // } // // @RequestMapping(value = "/body", method = { RequestMethod.POST }) // public ResponseEntity<?> post(@RequestBody Map<String, String> body) { // return ResponseEntity.ok().header("id", body.get("id")).body("success"); // } // // @RequestMapping(value = "/ambigousMethod", method = { RequestMethod.DELETE, RequestMethod.PUT }) // public ResponseEntity<?> ambigousMethod() { // return ResponseEntity.ok().build(); // } // // @RequestMapping(value = "/ambigousMethod", method = { RequestMethod.DELETE }) // public ResponseEntity<?> ambigousMethod2() { // return ResponseEntity.ok().build(); // } // // @RequestMapping(value = "/put", method = { RequestMethod.PUT }) // public ResponseEntity<?> put() { // return ResponseEntity.ok().build(); // } // // @RequestMapping(value = "/download", method = { RequestMethod.GET }) // public ResponseEntity<?> download() throws IOException { // return ResponseEntity.ok() // .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"mvc.delete.desc.xml\"") // .body(new ClassPathResource( // "alfresco/extension/templates/webscripts/alfresco-mvc/mvc.delete.desc.xml")); // } // // @GetMapping(value = "noderef") // public ResponseEntity<?> noderef() throws IOException { // return ResponseEntity.ok(new NodeRef("a://a/a")); // } // // @GetMapping(value = "noderefAlfrescoResponse") // @AlfrescoRestResponse // public ResponseEntity<?> noderefAlfrescoResponse() throws IOException { // return ResponseEntity.ok(new NodeRef("a://a/a")); // } // // @RequestMapping(value = "/exceptionHandler", method = { RequestMethod.GET }) // public ResponseEntity<?> exceptionHandler() { // throw new IllegalArgumentException("test exception"); // } // // @GetMapping(value = "regexp/{regexpchars:.+}") // public ResponseEntity<?> regexpchars(@PathVariable String regexpchars) throws IOException { // return ResponseEntity.ok(regexpchars); // } // // @ExceptionHandler({ IllegalArgumentException.class }) // public ResponseEntity<?> handleIllegalArgumentException(IllegalArgumentException exc) { // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).header("error", "internal server error").build(); // } // } // Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/config/AlfrescoMvcRestServletContext.java import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.gradecak.alfresco.mvc.controller.TestController; import com.gradecak.alfresco.mvc.rest.annotation.EnableWebAlfrescoMvc; package com.gradecak.alfresco.mvc.config; @Configuration @EnableWebAlfrescoMvc
@ComponentScan(basePackageClasses = { TestController.class })
dgradecak/alfresco-mvc
alfresco-mvc-aop/src/test/java/com/gradecak/alfresco/mvc/aop/TransactionalTest.java
// Path: alfresco-mvc-aop/src/test/java/com/gradecak/alfresco/mvc/service/TransactionalService.java // @Service // public class TransactionalService { // // @Autowired // private ServiceRegistry serviceRegistry; // // @AlfrescoTransaction // public String transactionWriteWithoutPropagation() { // return (String) serviceRegistry.getNodeService().getProperty(null, ContentModel.PROP_NAME); // } // // @AlfrescoTransaction(readOnly = true) // public String transactioReadOnlyWithPropagationRequired() throws SystemException { // return (String) serviceRegistry.getNodeService().getProperty(null, ContentModel.PROP_NAME); // } // // @AlfrescoTransaction(readOnly = true, propagation = Propagation.REQUIRES_NEW) // public String transactioReadOnlyWithPropagationRequiresNew() throws SystemException { // return (String) serviceRegistry.getNodeService().getProperty(null, ContentModel.PROP_NAME); // } // }
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import javax.transaction.SystemException; import org.alfresco.repo.transaction.RetryingTransactionHelper; import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; import org.alfresco.service.ServiceRegistry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.gradecak.alfresco.mvc.service.TransactionalService;
/** * Copyright gradecak.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 com.gradecak.alfresco.mvc.aop; @ExtendWith(SpringExtension.class) @ContextConfiguration(value = { "classpath:test-aop-context.xml" }) public class TransactionalTest { @Mock private RetryingTransactionHelper retryingTransactionHelper; @Autowired private ServiceRegistry serviceRegistry; @Autowired
// Path: alfresco-mvc-aop/src/test/java/com/gradecak/alfresco/mvc/service/TransactionalService.java // @Service // public class TransactionalService { // // @Autowired // private ServiceRegistry serviceRegistry; // // @AlfrescoTransaction // public String transactionWriteWithoutPropagation() { // return (String) serviceRegistry.getNodeService().getProperty(null, ContentModel.PROP_NAME); // } // // @AlfrescoTransaction(readOnly = true) // public String transactioReadOnlyWithPropagationRequired() throws SystemException { // return (String) serviceRegistry.getNodeService().getProperty(null, ContentModel.PROP_NAME); // } // // @AlfrescoTransaction(readOnly = true, propagation = Propagation.REQUIRES_NEW) // public String transactioReadOnlyWithPropagationRequiresNew() throws SystemException { // return (String) serviceRegistry.getNodeService().getProperty(null, ContentModel.PROP_NAME); // } // } // Path: alfresco-mvc-aop/src/test/java/com/gradecak/alfresco/mvc/aop/TransactionalTest.java import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import javax.transaction.SystemException; import org.alfresco.repo.transaction.RetryingTransactionHelper; import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; import org.alfresco.service.ServiceRegistry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.gradecak.alfresco.mvc.service.TransactionalService; /** * Copyright gradecak.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 com.gradecak.alfresco.mvc.aop; @ExtendWith(SpringExtension.class) @ContextConfiguration(value = { "classpath:test-aop-context.xml" }) public class TransactionalTest { @Mock private RetryingTransactionHelper retryingTransactionHelper; @Autowired private ServiceRegistry serviceRegistry; @Autowired
private TransactionalService service;
dgradecak/alfresco-mvc
alfresco-mvc-aop/src/test/java/com/gradecak/alfresco/mvc/service/AuthenticationService.java
// Path: alfresco-mvc-aop/src/main/java/com/gradecak/alfresco/mvc/annotation/AuthenticationType.java // public enum AuthenticationType { // // NONE, // // GUEST, // // USER, // // ADMIN // // }
import org.alfresco.model.ContentModel; import org.alfresco.service.ServiceRegistry; import org.alfresco.service.cmr.repository.NodeRef; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.gradecak.alfresco.mvc.annotation.AlfrescoAuthentication; import com.gradecak.alfresco.mvc.annotation.AuthenticationType;
/** * Copyright gradecak.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 com.gradecak.alfresco.mvc.service; @Service public class AuthenticationService { @Autowired private ServiceRegistry serviceRegistry; @AlfrescoAuthentication public String getNamePropertyAsDefault(final NodeRef nodeRef) { return (String) serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME); }
// Path: alfresco-mvc-aop/src/main/java/com/gradecak/alfresco/mvc/annotation/AuthenticationType.java // public enum AuthenticationType { // // NONE, // // GUEST, // // USER, // // ADMIN // // } // Path: alfresco-mvc-aop/src/test/java/com/gradecak/alfresco/mvc/service/AuthenticationService.java import org.alfresco.model.ContentModel; import org.alfresco.service.ServiceRegistry; import org.alfresco.service.cmr.repository.NodeRef; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.gradecak.alfresco.mvc.annotation.AlfrescoAuthentication; import com.gradecak.alfresco.mvc.annotation.AuthenticationType; /** * Copyright gradecak.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 com.gradecak.alfresco.mvc.service; @Service public class AuthenticationService { @Autowired private ServiceRegistry serviceRegistry; @AlfrescoAuthentication public String getNamePropertyAsDefault(final NodeRef nodeRef) { return (String) serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME); }
@AlfrescoAuthentication(AuthenticationType.USER)
dgradecak/alfresco-mvc
alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/annotation/AlfrescoDispatcherWebscript.java
// Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/config/AlfrescoRestRegistrar.java // public class AlfrescoRestRegistrar implements ImportBeanDefinitionRegistrar { // // private AnnotationAttributes attributes; // // public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) { // // Assert.notNull(annotationMetadata, "AnnotationMetadata must not be null!"); // Assert.notNull(registry, "BeanDefinitionRegistry must not be null!"); // // Map<String, Object> annotationAttributes = annotationMetadata // .getAnnotationAttributes(EnableAlfrescoMvcRest.class.getName()); // if (annotationAttributes == null) { // Map<String, Object> annotationAttributes2 = annotationMetadata // .getAnnotationAttributes(AlfrescoDispatcherWebscript.class.getName()); // // if (annotationAttributes2 != null) { // annotationAttributes = new AnnotationAttributes(); // annotationAttributes.put("value", Collections.singleton(new AnnotationAttributes(annotationAttributes2)) // .toArray(new AnnotationAttributes[0])); // } // // this.attributes = new AnnotationAttributes(annotationAttributes); // // } else { // this.attributes = new AnnotationAttributes(annotationAttributes); // } // // AnnotationAttributes[] dispatcherWebscripts = (AnnotationAttributes[]) attributes.get("value"); // // for (AnnotationAttributes dispatcherWebscript : dispatcherWebscripts) { // processDispatcherWebscript(dispatcherWebscript, registry); // } // // } // // private void processDispatcherWebscript(AnnotationAttributes webscriptAttributes, BeanDefinitionRegistry registry) { // String webscript = webscriptAttributes.getString("name"); // Assert.hasText(webscript, "Webscript name cannot be empty!"); // // Class<?> servletContext = webscriptAttributes.getClass("servletContext"); // // ServletConfigOptions[] servletConfigOptions = (ServletConfigOptions[]) webscriptAttributes // .get("servletConfigOptions"); // Class<? extends WebApplicationContext> servletContextClass = webscriptAttributes // .getClass("servletContextClass"); // HttpMethod[] httpMethods = (HttpMethod[]) webscriptAttributes.get("httpMethods"); // boolean inheritGlobalProperties = (Boolean) webscriptAttributes.get("inheritGlobalProperties"); // // GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); // beanDefinition.setBeanClass(DispatcherWebscript.class); // // DispatcherWebscript ws = new DispatcherWebscript(webscript, inheritGlobalProperties); // ws.setContextClass(servletContextClass); // ws.setContextConfigLocation(servletContext.getName()); // ws.addServletConfigOptions(servletConfigOptions); // beanDefinition.setInstanceSupplier(() -> ws); // beanDefinition.setRole(BeanDefinition.ROLE_APPLICATION); // // registry.registerBeanDefinition(webscript, beanDefinition); // // for (HttpMethod httpMethod : httpMethods) { // registry.registerAlias(webscript, getWebscriptName(webscript, httpMethod)); // } // } // // private String getWebscriptName(String webscript, HttpMethod httpMethod) { // String beanName = "webscript." + webscript + "." + httpMethod.name(); // return beanName.toLowerCase(); // } // } // // Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscript.java // public static enum ServletConfigOptions { // DISABLED_PARENT_HANDLER_MAPPINGS, DISABLED_PARENT_HANDLER_ADAPTERS, DISABLED_PARENT_VIEW_RESOLVERS, // DISABLED_PARENT_HANDLER_EXCEPTION_RESOLVERS // }
import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.Import; import org.springframework.http.HttpMethod; import org.springframework.web.context.WebApplicationContext; import com.gradecak.alfresco.mvc.rest.config.AlfrescoRestRegistrar; import com.gradecak.alfresco.mvc.webscript.DispatcherWebscript.ServletConfigOptions;
/** * Copyright gradecak.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 com.gradecak.alfresco.mvc.rest.annotation; @Repeatable(EnableAlfrescoMvcRest.class) @Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited
// Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/config/AlfrescoRestRegistrar.java // public class AlfrescoRestRegistrar implements ImportBeanDefinitionRegistrar { // // private AnnotationAttributes attributes; // // public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) { // // Assert.notNull(annotationMetadata, "AnnotationMetadata must not be null!"); // Assert.notNull(registry, "BeanDefinitionRegistry must not be null!"); // // Map<String, Object> annotationAttributes = annotationMetadata // .getAnnotationAttributes(EnableAlfrescoMvcRest.class.getName()); // if (annotationAttributes == null) { // Map<String, Object> annotationAttributes2 = annotationMetadata // .getAnnotationAttributes(AlfrescoDispatcherWebscript.class.getName()); // // if (annotationAttributes2 != null) { // annotationAttributes = new AnnotationAttributes(); // annotationAttributes.put("value", Collections.singleton(new AnnotationAttributes(annotationAttributes2)) // .toArray(new AnnotationAttributes[0])); // } // // this.attributes = new AnnotationAttributes(annotationAttributes); // // } else { // this.attributes = new AnnotationAttributes(annotationAttributes); // } // // AnnotationAttributes[] dispatcherWebscripts = (AnnotationAttributes[]) attributes.get("value"); // // for (AnnotationAttributes dispatcherWebscript : dispatcherWebscripts) { // processDispatcherWebscript(dispatcherWebscript, registry); // } // // } // // private void processDispatcherWebscript(AnnotationAttributes webscriptAttributes, BeanDefinitionRegistry registry) { // String webscript = webscriptAttributes.getString("name"); // Assert.hasText(webscript, "Webscript name cannot be empty!"); // // Class<?> servletContext = webscriptAttributes.getClass("servletContext"); // // ServletConfigOptions[] servletConfigOptions = (ServletConfigOptions[]) webscriptAttributes // .get("servletConfigOptions"); // Class<? extends WebApplicationContext> servletContextClass = webscriptAttributes // .getClass("servletContextClass"); // HttpMethod[] httpMethods = (HttpMethod[]) webscriptAttributes.get("httpMethods"); // boolean inheritGlobalProperties = (Boolean) webscriptAttributes.get("inheritGlobalProperties"); // // GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); // beanDefinition.setBeanClass(DispatcherWebscript.class); // // DispatcherWebscript ws = new DispatcherWebscript(webscript, inheritGlobalProperties); // ws.setContextClass(servletContextClass); // ws.setContextConfigLocation(servletContext.getName()); // ws.addServletConfigOptions(servletConfigOptions); // beanDefinition.setInstanceSupplier(() -> ws); // beanDefinition.setRole(BeanDefinition.ROLE_APPLICATION); // // registry.registerBeanDefinition(webscript, beanDefinition); // // for (HttpMethod httpMethod : httpMethods) { // registry.registerAlias(webscript, getWebscriptName(webscript, httpMethod)); // } // } // // private String getWebscriptName(String webscript, HttpMethod httpMethod) { // String beanName = "webscript." + webscript + "." + httpMethod.name(); // return beanName.toLowerCase(); // } // } // // Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscript.java // public static enum ServletConfigOptions { // DISABLED_PARENT_HANDLER_MAPPINGS, DISABLED_PARENT_HANDLER_ADAPTERS, DISABLED_PARENT_VIEW_RESOLVERS, // DISABLED_PARENT_HANDLER_EXCEPTION_RESOLVERS // } // Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/annotation/AlfrescoDispatcherWebscript.java import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.Import; import org.springframework.http.HttpMethod; import org.springframework.web.context.WebApplicationContext; import com.gradecak.alfresco.mvc.rest.config.AlfrescoRestRegistrar; import com.gradecak.alfresco.mvc.webscript.DispatcherWebscript.ServletConfigOptions; /** * Copyright gradecak.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 com.gradecak.alfresco.mvc.rest.annotation; @Repeatable(EnableAlfrescoMvcRest.class) @Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited
@Import(AlfrescoRestRegistrar.class)
dgradecak/alfresco-mvc
alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/annotation/AlfrescoDispatcherWebscript.java
// Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/config/AlfrescoRestRegistrar.java // public class AlfrescoRestRegistrar implements ImportBeanDefinitionRegistrar { // // private AnnotationAttributes attributes; // // public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) { // // Assert.notNull(annotationMetadata, "AnnotationMetadata must not be null!"); // Assert.notNull(registry, "BeanDefinitionRegistry must not be null!"); // // Map<String, Object> annotationAttributes = annotationMetadata // .getAnnotationAttributes(EnableAlfrescoMvcRest.class.getName()); // if (annotationAttributes == null) { // Map<String, Object> annotationAttributes2 = annotationMetadata // .getAnnotationAttributes(AlfrescoDispatcherWebscript.class.getName()); // // if (annotationAttributes2 != null) { // annotationAttributes = new AnnotationAttributes(); // annotationAttributes.put("value", Collections.singleton(new AnnotationAttributes(annotationAttributes2)) // .toArray(new AnnotationAttributes[0])); // } // // this.attributes = new AnnotationAttributes(annotationAttributes); // // } else { // this.attributes = new AnnotationAttributes(annotationAttributes); // } // // AnnotationAttributes[] dispatcherWebscripts = (AnnotationAttributes[]) attributes.get("value"); // // for (AnnotationAttributes dispatcherWebscript : dispatcherWebscripts) { // processDispatcherWebscript(dispatcherWebscript, registry); // } // // } // // private void processDispatcherWebscript(AnnotationAttributes webscriptAttributes, BeanDefinitionRegistry registry) { // String webscript = webscriptAttributes.getString("name"); // Assert.hasText(webscript, "Webscript name cannot be empty!"); // // Class<?> servletContext = webscriptAttributes.getClass("servletContext"); // // ServletConfigOptions[] servletConfigOptions = (ServletConfigOptions[]) webscriptAttributes // .get("servletConfigOptions"); // Class<? extends WebApplicationContext> servletContextClass = webscriptAttributes // .getClass("servletContextClass"); // HttpMethod[] httpMethods = (HttpMethod[]) webscriptAttributes.get("httpMethods"); // boolean inheritGlobalProperties = (Boolean) webscriptAttributes.get("inheritGlobalProperties"); // // GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); // beanDefinition.setBeanClass(DispatcherWebscript.class); // // DispatcherWebscript ws = new DispatcherWebscript(webscript, inheritGlobalProperties); // ws.setContextClass(servletContextClass); // ws.setContextConfigLocation(servletContext.getName()); // ws.addServletConfigOptions(servletConfigOptions); // beanDefinition.setInstanceSupplier(() -> ws); // beanDefinition.setRole(BeanDefinition.ROLE_APPLICATION); // // registry.registerBeanDefinition(webscript, beanDefinition); // // for (HttpMethod httpMethod : httpMethods) { // registry.registerAlias(webscript, getWebscriptName(webscript, httpMethod)); // } // } // // private String getWebscriptName(String webscript, HttpMethod httpMethod) { // String beanName = "webscript." + webscript + "." + httpMethod.name(); // return beanName.toLowerCase(); // } // } // // Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscript.java // public static enum ServletConfigOptions { // DISABLED_PARENT_HANDLER_MAPPINGS, DISABLED_PARENT_HANDLER_ADAPTERS, DISABLED_PARENT_VIEW_RESOLVERS, // DISABLED_PARENT_HANDLER_EXCEPTION_RESOLVERS // }
import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.Import; import org.springframework.http.HttpMethod; import org.springframework.web.context.WebApplicationContext; import com.gradecak.alfresco.mvc.rest.config.AlfrescoRestRegistrar; import com.gradecak.alfresco.mvc.webscript.DispatcherWebscript.ServletConfigOptions;
/** * Copyright gradecak.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 com.gradecak.alfresco.mvc.rest.annotation; @Repeatable(EnableAlfrescoMvcRest.class) @Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Import(AlfrescoRestRegistrar.class) public @interface AlfrescoDispatcherWebscript { String name() default "alfresco-mvc.mvc"; HttpMethod[] httpMethods() default { HttpMethod.GET, HttpMethod.POST, HttpMethod.DELETE, HttpMethod.PUT }; Class<?> servletContext(); Class<? extends WebApplicationContext> servletContextClass() default org.springframework.web.context.support.AnnotationConfigWebApplicationContext.class; boolean inheritGlobalProperties() default false;
// Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/config/AlfrescoRestRegistrar.java // public class AlfrescoRestRegistrar implements ImportBeanDefinitionRegistrar { // // private AnnotationAttributes attributes; // // public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) { // // Assert.notNull(annotationMetadata, "AnnotationMetadata must not be null!"); // Assert.notNull(registry, "BeanDefinitionRegistry must not be null!"); // // Map<String, Object> annotationAttributes = annotationMetadata // .getAnnotationAttributes(EnableAlfrescoMvcRest.class.getName()); // if (annotationAttributes == null) { // Map<String, Object> annotationAttributes2 = annotationMetadata // .getAnnotationAttributes(AlfrescoDispatcherWebscript.class.getName()); // // if (annotationAttributes2 != null) { // annotationAttributes = new AnnotationAttributes(); // annotationAttributes.put("value", Collections.singleton(new AnnotationAttributes(annotationAttributes2)) // .toArray(new AnnotationAttributes[0])); // } // // this.attributes = new AnnotationAttributes(annotationAttributes); // // } else { // this.attributes = new AnnotationAttributes(annotationAttributes); // } // // AnnotationAttributes[] dispatcherWebscripts = (AnnotationAttributes[]) attributes.get("value"); // // for (AnnotationAttributes dispatcherWebscript : dispatcherWebscripts) { // processDispatcherWebscript(dispatcherWebscript, registry); // } // // } // // private void processDispatcherWebscript(AnnotationAttributes webscriptAttributes, BeanDefinitionRegistry registry) { // String webscript = webscriptAttributes.getString("name"); // Assert.hasText(webscript, "Webscript name cannot be empty!"); // // Class<?> servletContext = webscriptAttributes.getClass("servletContext"); // // ServletConfigOptions[] servletConfigOptions = (ServletConfigOptions[]) webscriptAttributes // .get("servletConfigOptions"); // Class<? extends WebApplicationContext> servletContextClass = webscriptAttributes // .getClass("servletContextClass"); // HttpMethod[] httpMethods = (HttpMethod[]) webscriptAttributes.get("httpMethods"); // boolean inheritGlobalProperties = (Boolean) webscriptAttributes.get("inheritGlobalProperties"); // // GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); // beanDefinition.setBeanClass(DispatcherWebscript.class); // // DispatcherWebscript ws = new DispatcherWebscript(webscript, inheritGlobalProperties); // ws.setContextClass(servletContextClass); // ws.setContextConfigLocation(servletContext.getName()); // ws.addServletConfigOptions(servletConfigOptions); // beanDefinition.setInstanceSupplier(() -> ws); // beanDefinition.setRole(BeanDefinition.ROLE_APPLICATION); // // registry.registerBeanDefinition(webscript, beanDefinition); // // for (HttpMethod httpMethod : httpMethods) { // registry.registerAlias(webscript, getWebscriptName(webscript, httpMethod)); // } // } // // private String getWebscriptName(String webscript, HttpMethod httpMethod) { // String beanName = "webscript." + webscript + "." + httpMethod.name(); // return beanName.toLowerCase(); // } // } // // Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscript.java // public static enum ServletConfigOptions { // DISABLED_PARENT_HANDLER_MAPPINGS, DISABLED_PARENT_HANDLER_ADAPTERS, DISABLED_PARENT_VIEW_RESOLVERS, // DISABLED_PARENT_HANDLER_EXCEPTION_RESOLVERS // } // Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/annotation/AlfrescoDispatcherWebscript.java import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.Import; import org.springframework.http.HttpMethod; import org.springframework.web.context.WebApplicationContext; import com.gradecak.alfresco.mvc.rest.config.AlfrescoRestRegistrar; import com.gradecak.alfresco.mvc.webscript.DispatcherWebscript.ServletConfigOptions; /** * Copyright gradecak.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 com.gradecak.alfresco.mvc.rest.annotation; @Repeatable(EnableAlfrescoMvcRest.class) @Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Import(AlfrescoRestRegistrar.class) public @interface AlfrescoDispatcherWebscript { String name() default "alfresco-mvc.mvc"; HttpMethod[] httpMethods() default { HttpMethod.GET, HttpMethod.POST, HttpMethod.DELETE, HttpMethod.PUT }; Class<?> servletContext(); Class<? extends WebApplicationContext> servletContextClass() default org.springframework.web.context.support.AnnotationConfigWebApplicationContext.class; boolean inheritGlobalProperties() default false;
ServletConfigOptions[] servletConfigOptions() default {};
dgradecak/alfresco-mvc
alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/annotation/EnableWebAlfrescoMvc.java
// Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/config/DefaultAlfrescoMvcServletContextConfiguration.java // @Configuration // public class DefaultAlfrescoMvcServletContextConfiguration implements WebMvcConfigurer { // // private final RestJsonModule alfrescoRestJsonModule; // // @Autowired // public DefaultAlfrescoMvcServletContextConfiguration(RestJsonModule alfrescoRestJsonModule) { // this.alfrescoRestJsonModule = alfrescoRestJsonModule; // } // // @Override // public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { // resolvers.add(new ParamsHandlerMethodArgumentResolver()); // } // // @Bean // public AlfrescoApiResponseInterceptor alfrescoResponseInterceptor(ResourceWebScriptHelper webscriptHelper) { // return new AlfrescoApiResponseInterceptor(webscriptHelper); // } // // @Bean // public CommonsMultipartResolver multipartResolver() { // final CommonsMultipartResolver resolver = new CommonsMultipartResolver(); // resolver.setMaxUploadSize(-1); // resolver.setDefaultEncoding("utf-8"); // configureMultipartResolver(resolver); // return resolver; // } // // private void configureMultipartResolver(final CommonsMultipartResolver resolver) { // } // // @Override // public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { // // converters.stream().filter(c -> c instanceof MappingJackson2HttpMessageConverter).forEach(c -> { // Jackson2ObjectMapperBuilder objectMapperBuilder = Jackson2ObjectMapperBuilder.json(); // // ObjectMapper objectMapper = objectMapperBuilder.failOnEmptyBeans(false).failOnUnknownProperties(false) // .build(); // objectMapper.registerModule(alfrescoRestJsonModule); // objectMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_EMPTY); // objectMapper.configOverride(java.util.Map.class) // .setInclude(JsonInclude.Value.construct(JsonInclude.Include.NON_EMPTY, null)); // objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // DateFormat DATE_FORMAT_ISO8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); // DATE_FORMAT_ISO8601.setTimeZone(TimeZone.getTimeZone("UTC")); // objectMapper.setDateFormat(DATE_FORMAT_ISO8601); // objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); // // ((MappingJackson2HttpMessageConverter) c).setObjectMapper(objectMapper); // }); // // // this is from alfresco config in // // org.alfresco.rest.framework.jacksonextensions.JacksonHelper.afterPropertiesSet() // } // }
import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.Import; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import com.gradecak.alfresco.mvc.rest.config.DefaultAlfrescoMvcServletContextConfiguration;
/** * Copyright gradecak.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 com.gradecak.alfresco.mvc.rest.annotation; /** * use this class in order to import * <code>DefaultAlfrescoMvcServletContextConfig</code> and to add @EnableWebMvc. * You can omit this annotation and directly use @EnableWebMvc * * The default configuration reuse the Alfresco jackson configuration * <code>org.alfresco.rest.framework.jacksonextensions.RestJsonModule</code> */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @EnableWebMvc
// Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/config/DefaultAlfrescoMvcServletContextConfiguration.java // @Configuration // public class DefaultAlfrescoMvcServletContextConfiguration implements WebMvcConfigurer { // // private final RestJsonModule alfrescoRestJsonModule; // // @Autowired // public DefaultAlfrescoMvcServletContextConfiguration(RestJsonModule alfrescoRestJsonModule) { // this.alfrescoRestJsonModule = alfrescoRestJsonModule; // } // // @Override // public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { // resolvers.add(new ParamsHandlerMethodArgumentResolver()); // } // // @Bean // public AlfrescoApiResponseInterceptor alfrescoResponseInterceptor(ResourceWebScriptHelper webscriptHelper) { // return new AlfrescoApiResponseInterceptor(webscriptHelper); // } // // @Bean // public CommonsMultipartResolver multipartResolver() { // final CommonsMultipartResolver resolver = new CommonsMultipartResolver(); // resolver.setMaxUploadSize(-1); // resolver.setDefaultEncoding("utf-8"); // configureMultipartResolver(resolver); // return resolver; // } // // private void configureMultipartResolver(final CommonsMultipartResolver resolver) { // } // // @Override // public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { // // converters.stream().filter(c -> c instanceof MappingJackson2HttpMessageConverter).forEach(c -> { // Jackson2ObjectMapperBuilder objectMapperBuilder = Jackson2ObjectMapperBuilder.json(); // // ObjectMapper objectMapper = objectMapperBuilder.failOnEmptyBeans(false).failOnUnknownProperties(false) // .build(); // objectMapper.registerModule(alfrescoRestJsonModule); // objectMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_EMPTY); // objectMapper.configOverride(java.util.Map.class) // .setInclude(JsonInclude.Value.construct(JsonInclude.Include.NON_EMPTY, null)); // objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // DateFormat DATE_FORMAT_ISO8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); // DATE_FORMAT_ISO8601.setTimeZone(TimeZone.getTimeZone("UTC")); // objectMapper.setDateFormat(DATE_FORMAT_ISO8601); // objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); // // ((MappingJackson2HttpMessageConverter) c).setObjectMapper(objectMapper); // }); // // // this is from alfresco config in // // org.alfresco.rest.framework.jacksonextensions.JacksonHelper.afterPropertiesSet() // } // } // Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/annotation/EnableWebAlfrescoMvc.java import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.Import; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import com.gradecak.alfresco.mvc.rest.config.DefaultAlfrescoMvcServletContextConfiguration; /** * Copyright gradecak.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 com.gradecak.alfresco.mvc.rest.annotation; /** * use this class in order to import * <code>DefaultAlfrescoMvcServletContextConfig</code> and to add @EnableWebMvc. * You can omit this annotation and directly use @EnableWebMvc * * The default configuration reuse the Alfresco jackson configuration * <code>org.alfresco.rest.framework.jacksonextensions.RestJsonModule</code> */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @EnableWebMvc
@Import(DefaultAlfrescoMvcServletContextConfiguration.class)
dgradecak/alfresco-mvc
alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/inheritservletconfig/AlfrescoMvcCustomServletConfigModuleConfiguration.java
// Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscript.java // public static enum ServletConfigOptions { // DISABLED_PARENT_HANDLER_MAPPINGS, DISABLED_PARENT_HANDLER_ADAPTERS, DISABLED_PARENT_VIEW_RESOLVERS, // DISABLED_PARENT_HANDLER_EXCEPTION_RESOLVERS // }
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.gradecak.alfresco.mvc.rest.annotation.AlfrescoDispatcherWebscript; import com.gradecak.alfresco.mvc.rest.annotation.EnableAlfrescoMvcRest; import com.gradecak.alfresco.mvc.webscript.DispatcherWebscript.ServletConfigOptions;
/** * Copyright gradecak.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 com.gradecak.alfresco.mvc.inheritservletconfig; @Configuration @ImportResource("web-servlet-test.xml")
// Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscript.java // public static enum ServletConfigOptions { // DISABLED_PARENT_HANDLER_MAPPINGS, DISABLED_PARENT_HANDLER_ADAPTERS, DISABLED_PARENT_VIEW_RESOLVERS, // DISABLED_PARENT_HANDLER_EXCEPTION_RESOLVERS // } // Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/inheritservletconfig/AlfrescoMvcCustomServletConfigModuleConfiguration.java import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.gradecak.alfresco.mvc.rest.annotation.AlfrescoDispatcherWebscript; import com.gradecak.alfresco.mvc.rest.annotation.EnableAlfrescoMvcRest; import com.gradecak.alfresco.mvc.webscript.DispatcherWebscript.ServletConfigOptions; /** * Copyright gradecak.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 com.gradecak.alfresco.mvc.inheritservletconfig; @Configuration @ImportResource("web-servlet-test.xml")
@EnableAlfrescoMvcRest(@AlfrescoDispatcherWebscript(servletContext = AlfrescoMvcServletContext.class, servletConfigOptions = ServletConfigOptions.DISABLED_PARENT_HANDLER_MAPPINGS))
dgradecak/alfresco-mvc
alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscriptMockitoTest.java
// Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/mock/MockWebscriptBuilder.java // public class MockWebscriptBuilder { // // static public MockWebscript singleWebscript(final AbstractWebScript webScript) throws IOException { // return new MockWebscript(webScript); // } // }
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.mock.web.MockServletContext; import com.gradecak.alfresco.mvc.webscript.mock.MockWebscriptBuilder;
/** * Copyright gradecak.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 com.gradecak.alfresco.mvc.webscript; @TestInstance(Lifecycle.PER_CLASS) public class DispatcherWebscriptMockitoTest extends AbstractAlfrescoMvcTest { private @Spy DispatcherWebscript webScript; @BeforeAll public void beforeAll() throws Exception { MockitoAnnotations.initMocks(this); webScript.setServletContext(new MockServletContext()); webScript.setContextConfigLocation("test-webscriptdispatcher-context.xml"); ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(); applicationContext.setConfigLocation("web-context-test.xml"); applicationContext.refresh(); webScript.setApplicationContext(applicationContext); webScript.onApplicationEvent(new ContextRefreshedEvent(applicationContext));
// Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/mock/MockWebscriptBuilder.java // public class MockWebscriptBuilder { // // static public MockWebscript singleWebscript(final AbstractWebScript webScript) throws IOException { // return new MockWebscript(webScript); // } // } // Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscriptMockitoTest.java import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.mock.web.MockServletContext; import com.gradecak.alfresco.mvc.webscript.mock.MockWebscriptBuilder; /** * Copyright gradecak.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 com.gradecak.alfresco.mvc.webscript; @TestInstance(Lifecycle.PER_CLASS) public class DispatcherWebscriptMockitoTest extends AbstractAlfrescoMvcTest { private @Spy DispatcherWebscript webScript; @BeforeAll public void beforeAll() throws Exception { MockitoAnnotations.initMocks(this); webScript.setServletContext(new MockServletContext()); webScript.setContextConfigLocation("test-webscriptdispatcher-context.xml"); ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(); applicationContext.setConfigLocation("web-context-test.xml"); applicationContext.refresh(); webScript.setApplicationContext(applicationContext); webScript.onApplicationEvent(new ContextRefreshedEvent(applicationContext));
mockWebscript = MockWebscriptBuilder.singleWebscript(webScript);
dgradecak/alfresco-mvc
alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscriptSpringAnnotationRepeatableTest.java
// Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/mock/MockWebscriptBuilder.java // public class MockWebscriptBuilder { // // static public MockWebscript singleWebscript(final AbstractWebScript webScript) throws IOException { // return new MockWebscript(webScript); // } // }
import com.gradecak.alfresco.mvc.webscript.mock.MockWebscriptBuilder; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension;
/** * Copyright gradecak.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 com.gradecak.alfresco.mvc.webscript; @ExtendWith(SpringExtension.class) @ContextConfiguration(locations = { "/test-webscriptdispatcher-annotation-repeatable-context.xml" }) @TestInstance(Lifecycle.PER_CLASS) public class DispatcherWebscriptSpringAnnotationRepeatableTest extends AbstractAlfrescoMvcTest { @Autowired private DispatcherWebscript webScript; @BeforeAll public void beforeAll() throws Exception { MockitoAnnotations.initMocks(this);
// Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/mock/MockWebscriptBuilder.java // public class MockWebscriptBuilder { // // static public MockWebscript singleWebscript(final AbstractWebScript webScript) throws IOException { // return new MockWebscript(webScript); // } // } // Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscriptSpringAnnotationRepeatableTest.java import com.gradecak.alfresco.mvc.webscript.mock.MockWebscriptBuilder; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; /** * Copyright gradecak.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 com.gradecak.alfresco.mvc.webscript; @ExtendWith(SpringExtension.class) @ContextConfiguration(locations = { "/test-webscriptdispatcher-annotation-repeatable-context.xml" }) @TestInstance(Lifecycle.PER_CLASS) public class DispatcherWebscriptSpringAnnotationRepeatableTest extends AbstractAlfrescoMvcTest { @Autowired private DispatcherWebscript webScript; @BeforeAll public void beforeAll() throws Exception { MockitoAnnotations.initMocks(this);
mockWebscript = MockWebscriptBuilder.singleWebscript(webScript);
dgradecak/alfresco-mvc
alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscriptSpringAnnotationSingleTest.java
// Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/mock/MockWebscriptBuilder.java // public class MockWebscriptBuilder { // // static public MockWebscript singleWebscript(final AbstractWebScript webScript) throws IOException { // return new MockWebscript(webScript); // } // }
import com.gradecak.alfresco.mvc.webscript.mock.MockWebscriptBuilder; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension;
/** * Copyright gradecak.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 com.gradecak.alfresco.mvc.webscript; @ExtendWith(SpringExtension.class) @ContextConfiguration(locations = { "/test-webscriptdispatcher-annotation-single-context.xml" }) @TestInstance(Lifecycle.PER_CLASS) public class DispatcherWebscriptSpringAnnotationSingleTest extends AbstractAlfrescoMvcTest { @Autowired private DispatcherWebscript webScript; @BeforeAll public void beforeAll() throws Exception { MockitoAnnotations.initMocks(this);
// Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/mock/MockWebscriptBuilder.java // public class MockWebscriptBuilder { // // static public MockWebscript singleWebscript(final AbstractWebScript webScript) throws IOException { // return new MockWebscript(webScript); // } // } // Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscriptSpringAnnotationSingleTest.java import com.gradecak.alfresco.mvc.webscript.mock.MockWebscriptBuilder; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; /** * Copyright gradecak.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 com.gradecak.alfresco.mvc.webscript; @ExtendWith(SpringExtension.class) @ContextConfiguration(locations = { "/test-webscriptdispatcher-annotation-single-context.xml" }) @TestInstance(Lifecycle.PER_CLASS) public class DispatcherWebscriptSpringAnnotationSingleTest extends AbstractAlfrescoMvcTest { @Autowired private DispatcherWebscript webScript; @BeforeAll public void beforeAll() throws Exception { MockitoAnnotations.initMocks(this);
mockWebscript = MockWebscriptBuilder.singleWebscript(webScript);
dgradecak/alfresco-mvc
alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/AlfrescoApiResponseInterceptor.java
// Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscript.java // public class WebscriptRequestWrapper extends HttpServletRequestWrapper { // // private WebScriptServletRequest origReq; // // public WebscriptRequestWrapper(WebScriptServletRequest request) { // super(request.getHttpServletRequest()); // this.origReq = request; // } // // @Override // public String getRequestURI() { // String uri = super.getRequestURI(); // if (uri.contains("$")) { // uri = uri.replaceAll("\\$", "%24"); // } // // String origUri = origReq.getExtensionPath(); // if (origUri.contains("$")) { // origUri = origUri.replaceAll("\\$", "%24"); // } // // Pattern pattern = Pattern.compile("(^" + origReq.getServiceContextPath() + "/)(.*)(/" + origUri + ")"); // Matcher matcher = pattern.matcher(uri); // // if (matcher.find()) { // try { // return matcher.group(EXTENSION_PATH_REGEXP_GROUP_INDEX); // } catch (Exception e) { // // let an empty string be returned // LOGGER.warn("no such group (3) in regexp while URI evaluation", e); // } // } // // return ""; // } // // public String getContextPath() { // return origReq.getContextPath(); // } // // public String getServletPath() { // return ""; // } // // public WebScriptServletRequest getWebScriptServletRequest() { // return origReq; // } // }
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; import com.gradecak.alfresco.mvc.rest.annotation.AlfrescoRestResponse; import com.gradecak.alfresco.mvc.webscript.DispatcherWebscript.WebscriptRequestWrapper; import javax.servlet.http.HttpServletRequest; import org.alfresco.rest.framework.resource.parameters.Params; import org.alfresco.rest.framework.resource.parameters.Params.RecognizedParams; import org.alfresco.rest.framework.webscripts.ResourceWebScriptHelper; import org.springframework.core.MethodParameter; import org.springframework.extensions.webscripts.WebScriptRequest; import org.springframework.extensions.webscripts.servlet.WebScriptServletRequest; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest;
this.webscriptHelper = webscriptHelper; this.globalAlfrescoResponse = globalAlfrescoResponse; } @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { boolean useAlfrescoResponse = globalAlfrescoResponse; if (!useAlfrescoResponse) { AlfrescoRestResponse methodAnnotation = returnType.getMethodAnnotation(AlfrescoRestResponse.class); if (methodAnnotation == null) { methodAnnotation = returnType.getContainingClass().getAnnotation(AlfrescoRestResponse.class); } if (methodAnnotation != null) { useAlfrescoResponse = true; } } if (useAlfrescoResponse) { if (!(request instanceof ServletServerHttpRequest)) { throw new RuntimeException( "the request must be an instance of org.springframework.http.server.ServletServerHttpRequest"); } HttpServletRequest r = ((ServletServerHttpRequest) request).getServletRequest();
// Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscript.java // public class WebscriptRequestWrapper extends HttpServletRequestWrapper { // // private WebScriptServletRequest origReq; // // public WebscriptRequestWrapper(WebScriptServletRequest request) { // super(request.getHttpServletRequest()); // this.origReq = request; // } // // @Override // public String getRequestURI() { // String uri = super.getRequestURI(); // if (uri.contains("$")) { // uri = uri.replaceAll("\\$", "%24"); // } // // String origUri = origReq.getExtensionPath(); // if (origUri.contains("$")) { // origUri = origUri.replaceAll("\\$", "%24"); // } // // Pattern pattern = Pattern.compile("(^" + origReq.getServiceContextPath() + "/)(.*)(/" + origUri + ")"); // Matcher matcher = pattern.matcher(uri); // // if (matcher.find()) { // try { // return matcher.group(EXTENSION_PATH_REGEXP_GROUP_INDEX); // } catch (Exception e) { // // let an empty string be returned // LOGGER.warn("no such group (3) in regexp while URI evaluation", e); // } // } // // return ""; // } // // public String getContextPath() { // return origReq.getContextPath(); // } // // public String getServletPath() { // return ""; // } // // public WebScriptServletRequest getWebScriptServletRequest() { // return origReq; // } // } // Path: alfresco-mvc-rest/src/main/java/com/gradecak/alfresco/mvc/rest/AlfrescoApiResponseInterceptor.java import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; import com.gradecak.alfresco.mvc.rest.annotation.AlfrescoRestResponse; import com.gradecak.alfresco.mvc.webscript.DispatcherWebscript.WebscriptRequestWrapper; import javax.servlet.http.HttpServletRequest; import org.alfresco.rest.framework.resource.parameters.Params; import org.alfresco.rest.framework.resource.parameters.Params.RecognizedParams; import org.alfresco.rest.framework.webscripts.ResourceWebScriptHelper; import org.springframework.core.MethodParameter; import org.springframework.extensions.webscripts.WebScriptRequest; import org.springframework.extensions.webscripts.servlet.WebScriptServletRequest; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; this.webscriptHelper = webscriptHelper; this.globalAlfrescoResponse = globalAlfrescoResponse; } @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { boolean useAlfrescoResponse = globalAlfrescoResponse; if (!useAlfrescoResponse) { AlfrescoRestResponse methodAnnotation = returnType.getMethodAnnotation(AlfrescoRestResponse.class); if (methodAnnotation == null) { methodAnnotation = returnType.getContainingClass().getAnnotation(AlfrescoRestResponse.class); } if (methodAnnotation != null) { useAlfrescoResponse = true; } } if (useAlfrescoResponse) { if (!(request instanceof ServletServerHttpRequest)) { throw new RuntimeException( "the request must be an instance of org.springframework.http.server.ServletServerHttpRequest"); } HttpServletRequest r = ((ServletServerHttpRequest) request).getServletRequest();
if (!(r instanceof WebscriptRequestWrapper)) {
dgradecak/alfresco-mvc
alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscriptSpringXmlTest.java
// Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/mock/MockWebscriptBuilder.java // public class MockWebscriptBuilder { // // static public MockWebscript singleWebscript(final AbstractWebScript webScript) throws IOException { // return new MockWebscript(webScript); // } // }
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.gradecak.alfresco.mvc.webscript.mock.MockWebscriptBuilder;
/** * Copyright gradecak.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 com.gradecak.alfresco.mvc.webscript; @ExtendWith(SpringExtension.class) @ContextConfiguration(locations = { "/web-context-test.xml" }) @TestInstance(Lifecycle.PER_CLASS) public class DispatcherWebscriptSpringXmlTest extends AbstractAlfrescoMvcTest { @Spy @Autowired private DispatcherWebscript webScript; @BeforeAll public void beforeAll() throws Exception { MockitoAnnotations.initMocks(this); webScript.setServletContext(new MockServletContext()); webScript.setContextConfigLocation("test-webscriptdispatcher-context.xml");
// Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/mock/MockWebscriptBuilder.java // public class MockWebscriptBuilder { // // static public MockWebscript singleWebscript(final AbstractWebScript webScript) throws IOException { // return new MockWebscript(webScript); // } // } // Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscriptSpringXmlTest.java import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.gradecak.alfresco.mvc.webscript.mock.MockWebscriptBuilder; /** * Copyright gradecak.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 com.gradecak.alfresco.mvc.webscript; @ExtendWith(SpringExtension.class) @ContextConfiguration(locations = { "/web-context-test.xml" }) @TestInstance(Lifecycle.PER_CLASS) public class DispatcherWebscriptSpringXmlTest extends AbstractAlfrescoMvcTest { @Spy @Autowired private DispatcherWebscript webScript; @BeforeAll public void beforeAll() throws Exception { MockitoAnnotations.initMocks(this); webScript.setServletContext(new MockServletContext()); webScript.setContextConfigLocation("test-webscriptdispatcher-context.xml");
mockWebscript = MockWebscriptBuilder.singleWebscript(webScript);
dgradecak/alfresco-mvc
alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscriptSpringAnnotationEnableTest.java
// Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/mock/MockWebscriptBuilder.java // public class MockWebscriptBuilder { // // static public MockWebscript singleWebscript(final AbstractWebScript webScript) throws IOException { // return new MockWebscript(webScript); // } // }
import com.gradecak.alfresco.mvc.webscript.mock.MockWebscriptBuilder; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension;
/** * Copyright gradecak.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 com.gradecak.alfresco.mvc.webscript; @ExtendWith(SpringExtension.class) @ContextConfiguration(locations = { "/test-webscriptdispatcher-annotation-enable-context.xml" }) @TestInstance(Lifecycle.PER_CLASS) public class DispatcherWebscriptSpringAnnotationEnableTest extends AbstractAlfrescoMvcTest { @Autowired private DispatcherWebscript webScript; @BeforeAll public void beforeAll() throws Exception { MockitoAnnotations.initMocks(this);
// Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/mock/MockWebscriptBuilder.java // public class MockWebscriptBuilder { // // static public MockWebscript singleWebscript(final AbstractWebScript webScript) throws IOException { // return new MockWebscript(webScript); // } // } // Path: alfresco-mvc-rest/src/test/java/com/gradecak/alfresco/mvc/webscript/DispatcherWebscriptSpringAnnotationEnableTest.java import com.gradecak.alfresco.mvc.webscript.mock.MockWebscriptBuilder; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; /** * Copyright gradecak.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 com.gradecak.alfresco.mvc.webscript; @ExtendWith(SpringExtension.class) @ContextConfiguration(locations = { "/test-webscriptdispatcher-annotation-enable-context.xml" }) @TestInstance(Lifecycle.PER_CLASS) public class DispatcherWebscriptSpringAnnotationEnableTest extends AbstractAlfrescoMvcTest { @Autowired private DispatcherWebscript webScript; @BeforeAll public void beforeAll() throws Exception { MockitoAnnotations.initMocks(this);
mockWebscript = MockWebscriptBuilder.singleWebscript(webScript);
dgradecak/alfresco-mvc
alfresco-mvc-aop/src/main/java/com/gradecak/alfresco/mvc/aop/AuthenticationAdvice.java
// Path: alfresco-mvc-aop/src/main/java/com/gradecak/alfresco/mvc/annotation/AuthenticationType.java // public enum AuthenticationType { // // NONE, // // GUEST, // // USER, // // ADMIN // // }
import com.gradecak.alfresco.mvc.annotation.AlfrescoAuthentication; import com.gradecak.alfresco.mvc.annotation.AuthenticationType; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import org.alfresco.repo.security.authentication.AuthenticationException; import org.alfresco.service.ServiceRegistry; import org.alfresco.service.cmr.security.AuthenticationService; import org.alfresco.service.cmr.security.AuthorityService; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.core.BridgeMethodResolver; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils;
/** * Copyright gradecak.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 com.gradecak.alfresco.mvc.aop; public class AuthenticationAdvice implements MethodInterceptor { private final ServiceRegistry serviceRegistry; public AuthenticationAdvice(final ServiceRegistry serviceRegistry) { this.serviceRegistry = serviceRegistry; } public Object invoke(final MethodInvocation invocation) throws Throwable { Class<?> targetClass = invocation.getThis() != null ? invocation.getThis().getClass() : null; Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass); // If we are dealing with method with generic parameters, find the original // method. specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); AlfrescoAuthentication alfrescoAuthentication = parseAnnotation(specificMethod); if (alfrescoAuthentication != null) {
// Path: alfresco-mvc-aop/src/main/java/com/gradecak/alfresco/mvc/annotation/AuthenticationType.java // public enum AuthenticationType { // // NONE, // // GUEST, // // USER, // // ADMIN // // } // Path: alfresco-mvc-aop/src/main/java/com/gradecak/alfresco/mvc/aop/AuthenticationAdvice.java import com.gradecak.alfresco.mvc.annotation.AlfrescoAuthentication; import com.gradecak.alfresco.mvc.annotation.AuthenticationType; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import org.alfresco.repo.security.authentication.AuthenticationException; import org.alfresco.service.ServiceRegistry; import org.alfresco.service.cmr.security.AuthenticationService; import org.alfresco.service.cmr.security.AuthorityService; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.core.BridgeMethodResolver; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; /** * Copyright gradecak.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 com.gradecak.alfresco.mvc.aop; public class AuthenticationAdvice implements MethodInterceptor { private final ServiceRegistry serviceRegistry; public AuthenticationAdvice(final ServiceRegistry serviceRegistry) { this.serviceRegistry = serviceRegistry; } public Object invoke(final MethodInvocation invocation) throws Throwable { Class<?> targetClass = invocation.getThis() != null ? invocation.getThis().getClass() : null; Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass); // If we are dealing with method with generic parameters, find the original // method. specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); AlfrescoAuthentication alfrescoAuthentication = parseAnnotation(specificMethod); if (alfrescoAuthentication != null) {
AuthenticationType authenticationType = alfrescoAuthentication.value();
dgradecak/alfresco-mvc
alfresco-mvc-aop/src/test/java/com/gradecak/alfresco/mvc/aop/AuthenticationTest.java
// Path: alfresco-mvc-aop/src/test/java/com/gradecak/alfresco/mvc/service/AuthenticationService.java // @Service // public class AuthenticationService { // // @Autowired // private ServiceRegistry serviceRegistry; // // @AlfrescoAuthentication // public String getNamePropertyAsDefault(final NodeRef nodeRef) { // return (String) serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME); // } // // @AlfrescoAuthentication(AuthenticationType.USER) // public String getNamePropertyAsUser(final NodeRef nodeRef) { // return (String) serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME); // } // // @AlfrescoAuthentication(AuthenticationType.ADMIN) // public String getNamePropertyAsAdmin(final NodeRef nodeRef) { // return (String) serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME); // } // // @AlfrescoAuthentication(AuthenticationType.NONE) // public String getNamePropertyAsNone(final NodeRef nodeRef) { // return (String) serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME); // } // }
import static org.mockito.Mockito.when; import org.alfresco.repo.security.authentication.AuthenticationException; import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.service.ServiceRegistry; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.security.AuthorityService; import org.alfresco.service.cmr.security.MutableAuthenticationService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.gradecak.alfresco.mvc.service.AuthenticationService;
/** * Copyright gradecak.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 com.gradecak.alfresco.mvc.aop; @ExtendWith(SpringExtension.class) @ContextConfiguration(value = { "classpath:test-aop-context.xml" }) public class AuthenticationTest { @Mock private MutableAuthenticationService authenticationService; @Mock private AuthorityService authorityService; @Mock private NodeService nodeService; @Autowired private ServiceRegistry serviceRegistry; @Autowired
// Path: alfresco-mvc-aop/src/test/java/com/gradecak/alfresco/mvc/service/AuthenticationService.java // @Service // public class AuthenticationService { // // @Autowired // private ServiceRegistry serviceRegistry; // // @AlfrescoAuthentication // public String getNamePropertyAsDefault(final NodeRef nodeRef) { // return (String) serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME); // } // // @AlfrescoAuthentication(AuthenticationType.USER) // public String getNamePropertyAsUser(final NodeRef nodeRef) { // return (String) serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME); // } // // @AlfrescoAuthentication(AuthenticationType.ADMIN) // public String getNamePropertyAsAdmin(final NodeRef nodeRef) { // return (String) serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME); // } // // @AlfrescoAuthentication(AuthenticationType.NONE) // public String getNamePropertyAsNone(final NodeRef nodeRef) { // return (String) serviceRegistry.getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME); // } // } // Path: alfresco-mvc-aop/src/test/java/com/gradecak/alfresco/mvc/aop/AuthenticationTest.java import static org.mockito.Mockito.when; import org.alfresco.repo.security.authentication.AuthenticationException; import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.service.ServiceRegistry; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.security.AuthorityService; import org.alfresco.service.cmr.security.MutableAuthenticationService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.gradecak.alfresco.mvc.service.AuthenticationService; /** * Copyright gradecak.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 com.gradecak.alfresco.mvc.aop; @ExtendWith(SpringExtension.class) @ContextConfiguration(value = { "classpath:test-aop-context.xml" }) public class AuthenticationTest { @Mock private MutableAuthenticationService authenticationService; @Mock private AuthorityService authorityService; @Mock private NodeService nodeService; @Autowired private ServiceRegistry serviceRegistry; @Autowired
private AuthenticationService service;
firepick1/FireBOM
src/main/java/org/firepick/firebom/bom/HtmlRowVisitor.java
// Path: src/main/java/org/firepick/relation/IRow.java // public interface IRow { // IRelation getRelation(); // Object item(int index); // } // // Path: src/main/java/org/firepick/relation/IRowVisitor.java // public interface IRowVisitor { // void visit(IRow row); // }
import org.firepick.relation.IRow; import org.firepick.relation.IRowVisitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.firepick.firebom.bom; /* HtmlRowVisitor.java Copyright (C) 2013 Karl Lew <karl@firepick.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. */ public class HtmlRowVisitor implements IRowVisitor { private static Logger logger = LoggerFactory.getLogger(HtmlRowVisitor.class); private boolean isResolved = true; private boolean lastResolved; public boolean isResolved() { return isResolved; } @Override
// Path: src/main/java/org/firepick/relation/IRow.java // public interface IRow { // IRelation getRelation(); // Object item(int index); // } // // Path: src/main/java/org/firepick/relation/IRowVisitor.java // public interface IRowVisitor { // void visit(IRow row); // } // Path: src/main/java/org/firepick/firebom/bom/HtmlRowVisitor.java import org.firepick.relation.IRow; import org.firepick.relation.IRowVisitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package org.firepick.firebom.bom; /* HtmlRowVisitor.java Copyright (C) 2013 Karl Lew <karl@firepick.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. */ public class HtmlRowVisitor implements IRowVisitor { private static Logger logger = LoggerFactory.getLogger(HtmlRowVisitor.class); private boolean isResolved = true; private boolean lastResolved; public boolean isResolved() { return isResolved; } @Override
public void visit(IRow row) {
firepick1/FireBOM
src/test/java/org/firepick/firebom/MainTest.java
// Path: src/main/java/org/firepick/firebom/bom/BOMFactory.java // public class BOMFactory implements Runnable { // private static Logger logger = LoggerFactory.getLogger(BOMFactory.class); // private final ConcurrentLinkedQueue<BOM> bomQueue = new ConcurrentLinkedQueue<BOM>(); // private OutputType outputType = OutputType.DEFAULT; // private Thread worker; // private PartFactory partFactory; // private boolean workerPaused; // private Lock backgroundLock = new ReentrantLock(); // // public void shutdown() { // logger.info("Shutting down Ehcache"); // CacheManager.getInstance().shutdown(); // } // // public BOM createBOM(URL url) { // BOM bom = new BOM(url); // synchronized (bomQueue) { // bomQueue.add(bom); // if (worker == null) { // worker = new Thread(this); // worker.start(); // } // } // return bom; // } // // @Override // public void run() { // for (; ; ) { // synchronized (bomQueue) { // if (bomQueue.size() == 0) { // worker = null; // return; // } // } // // if (isWorkerPaused()) { // try { // Thread.sleep(500); // } // catch (InterruptedException e) { // logger.error("interrupted", e); // } // } else { // try { // synchronized (bomQueue) { // BOM bom = bomQueue.poll(); // if (bom != null) { // if (!bom.resolve(0)) { // logger.info("Requeing bom for resolve() {}", bom.getUrl()); // bomQueue.add(bom); // } // } // } // } // catch (Exception e) { // logger.error("Could not resolve BOM", e); // } // } // } // } // // public BOMFactory printBOM(PrintStream printStream, BOM bom, IRowVisitor rowVisitor) { // switch (outputType) { // case MARKDOWN: // new BOMMarkdownPrinter().print(bom, printStream, rowVisitor); // break; // case HTML: // new BOMHtmlPrinter().setPrintHtmlWrapper(true).setTitle(bom.getTitle()).print(bom, printStream, rowVisitor); // break; // case HTML_TABLE: // new BOMHtmlPrinter().setPrintHtmlWrapper(false).setTitle(bom.getTitle()).print(bom, printStream, rowVisitor); // break; // default: // case CSV: // new RelationPrinter().print(bom, printStream, rowVisitor); // break; // } // // return this; // } // // public OutputType getOutputType() { // return outputType; // } // // public BOMFactory setOutputType(OutputType outputType) { // this.outputType = outputType; // return this; // } // // public PartFactory getPartFactory() { // if (partFactory == null) { // setPartFactory(PartFactory.getInstance()); // } // return partFactory; // } // // public BOMFactory setPartFactory(PartFactory partFactory) { // this.partFactory = partFactory; // return this; // } // // public boolean isWorkerPaused() { // return workerPaused; // } // // public BOMFactory setWorkerPaused(boolean workerPaused) { // synchronized (bomQueue) { // logger.info("setWorkerPaused({})", workerPaused); // this.workerPaused = workerPaused; // } // return this; // } // // public enum OutputType { // DEFAULT, // MARKDOWN, // HTML, // HTML_TABLE, // CSV // } // // }
import org.firepick.firebom.bom.BOMFactory; import org.junit.Test; import java.io.*; import static org.junit.Assert.assertEquals;
package org.firepick.firebom; /* MainTest.java Copyright (C) 2013 Karl Lew <karl@firepick.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. */ public class MainTest { @Test public void testHelp() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(baos); PrintStream printWriter = new PrintStream(bos); Main.mainStream(new String[0], printWriter); printWriter.flush(); String help = baos.toString(); System.out.println(help); assert(help.contains("USAGE")); assert(help.contains("OPTIONS")); assert(help.contains("EXAMPLES")); } @Test public void testBOMFactory() {
// Path: src/main/java/org/firepick/firebom/bom/BOMFactory.java // public class BOMFactory implements Runnable { // private static Logger logger = LoggerFactory.getLogger(BOMFactory.class); // private final ConcurrentLinkedQueue<BOM> bomQueue = new ConcurrentLinkedQueue<BOM>(); // private OutputType outputType = OutputType.DEFAULT; // private Thread worker; // private PartFactory partFactory; // private boolean workerPaused; // private Lock backgroundLock = new ReentrantLock(); // // public void shutdown() { // logger.info("Shutting down Ehcache"); // CacheManager.getInstance().shutdown(); // } // // public BOM createBOM(URL url) { // BOM bom = new BOM(url); // synchronized (bomQueue) { // bomQueue.add(bom); // if (worker == null) { // worker = new Thread(this); // worker.start(); // } // } // return bom; // } // // @Override // public void run() { // for (; ; ) { // synchronized (bomQueue) { // if (bomQueue.size() == 0) { // worker = null; // return; // } // } // // if (isWorkerPaused()) { // try { // Thread.sleep(500); // } // catch (InterruptedException e) { // logger.error("interrupted", e); // } // } else { // try { // synchronized (bomQueue) { // BOM bom = bomQueue.poll(); // if (bom != null) { // if (!bom.resolve(0)) { // logger.info("Requeing bom for resolve() {}", bom.getUrl()); // bomQueue.add(bom); // } // } // } // } // catch (Exception e) { // logger.error("Could not resolve BOM", e); // } // } // } // } // // public BOMFactory printBOM(PrintStream printStream, BOM bom, IRowVisitor rowVisitor) { // switch (outputType) { // case MARKDOWN: // new BOMMarkdownPrinter().print(bom, printStream, rowVisitor); // break; // case HTML: // new BOMHtmlPrinter().setPrintHtmlWrapper(true).setTitle(bom.getTitle()).print(bom, printStream, rowVisitor); // break; // case HTML_TABLE: // new BOMHtmlPrinter().setPrintHtmlWrapper(false).setTitle(bom.getTitle()).print(bom, printStream, rowVisitor); // break; // default: // case CSV: // new RelationPrinter().print(bom, printStream, rowVisitor); // break; // } // // return this; // } // // public OutputType getOutputType() { // return outputType; // } // // public BOMFactory setOutputType(OutputType outputType) { // this.outputType = outputType; // return this; // } // // public PartFactory getPartFactory() { // if (partFactory == null) { // setPartFactory(PartFactory.getInstance()); // } // return partFactory; // } // // public BOMFactory setPartFactory(PartFactory partFactory) { // this.partFactory = partFactory; // return this; // } // // public boolean isWorkerPaused() { // return workerPaused; // } // // public BOMFactory setWorkerPaused(boolean workerPaused) { // synchronized (bomQueue) { // logger.info("setWorkerPaused({})", workerPaused); // this.workerPaused = workerPaused; // } // return this; // } // // public enum OutputType { // DEFAULT, // MARKDOWN, // HTML, // HTML_TABLE, // CSV // } // // } // Path: src/test/java/org/firepick/firebom/MainTest.java import org.firepick.firebom.bom.BOMFactory; import org.junit.Test; import java.io.*; import static org.junit.Assert.assertEquals; package org.firepick.firebom; /* MainTest.java Copyright (C) 2013 Karl Lew <karl@firepick.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. */ public class MainTest { @Test public void testHelp() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(baos); PrintStream printWriter = new PrintStream(bos); Main.mainStream(new String[0], printWriter); printWriter.flush(); String help = baos.toString(); System.out.println(help); assert(help.contains("USAGE")); assert(help.contains("OPTIONS")); assert(help.contains("EXAMPLES")); } @Test public void testBOMFactory() {
BOMFactory bomFactory = new BOMFactory();
firepick1/FireBOM
src/test/java/org/firepick/firebom/RefreshableTimerTest.java
// Path: src/main/java/org/firepick/firebom/exception/ProxyResolutionException.java // public class ProxyResolutionException extends RuntimeException { // public ProxyResolutionException(Exception e) { // super(e); // } // // public ProxyResolutionException(String message) { // super(message); // } // // public ProxyResolutionException(String message, Exception e) { // super(message, e); // } // }
import org.firepick.firebom.exception.ProxyResolutionException; import org.junit.Test; import static org.junit.Assert.assertEquals;
assertEquals(0, timer.getSamplesSinceRefresh()); assertEquals(10, timer.getRefreshInterval()); assertEquals(10, timer.getSampleInterval()); // Sampling affects refresh/sampling intervals and, therefore, freshness Thread.sleep(50); timer.sample(); assertEquals(1, timer.getSamplesSinceRefresh()); assertEquals(42, timer.getRefreshInterval()); } @Test public void testMinRefreshInterval() { RefreshableTimer timer = new RefreshableTimer(); assertEquals(0, timer.getMinRefreshInterval()); timer.setMinRefreshInterval(100); assertEquals(100, timer.getMinRefreshInterval()); assertEquals(100, timer.getRefreshInterval()); timer.refresh(); assert (timer.isFresh()); assertEquals(100, timer.getMinRefreshInterval()); assertEquals(100, timer.getRefreshInterval()); } public class MockTimer extends RefreshableTimer { @Override public void refresh() { super.refresh();
// Path: src/main/java/org/firepick/firebom/exception/ProxyResolutionException.java // public class ProxyResolutionException extends RuntimeException { // public ProxyResolutionException(Exception e) { // super(e); // } // // public ProxyResolutionException(String message) { // super(message); // } // // public ProxyResolutionException(String message, Exception e) { // super(message, e); // } // } // Path: src/test/java/org/firepick/firebom/RefreshableTimerTest.java import org.firepick.firebom.exception.ProxyResolutionException; import org.junit.Test; import static org.junit.Assert.assertEquals; assertEquals(0, timer.getSamplesSinceRefresh()); assertEquals(10, timer.getRefreshInterval()); assertEquals(10, timer.getSampleInterval()); // Sampling affects refresh/sampling intervals and, therefore, freshness Thread.sleep(50); timer.sample(); assertEquals(1, timer.getSamplesSinceRefresh()); assertEquals(42, timer.getRefreshInterval()); } @Test public void testMinRefreshInterval() { RefreshableTimer timer = new RefreshableTimer(); assertEquals(0, timer.getMinRefreshInterval()); timer.setMinRefreshInterval(100); assertEquals(100, timer.getMinRefreshInterval()); assertEquals(100, timer.getRefreshInterval()); timer.refresh(); assert (timer.isFresh()); assertEquals(100, timer.getMinRefreshInterval()); assertEquals(100, timer.getRefreshInterval()); } public class MockTimer extends RefreshableTimer { @Override public void refresh() { super.refresh();
throw new ProxyResolutionException("test");
firepick1/FireBOM
src/test/java/org/firepick/firebom/RefreshableProxyTester.java
// Path: src/main/java/org/firepick/firebom/exception/ProxyResolutionException.java // public class ProxyResolutionException extends RuntimeException { // public ProxyResolutionException(Exception e) { // super(e); // } // // public ProxyResolutionException(String message) { // super(message); // } // // public ProxyResolutionException(String message, Exception e) { // super(message, e); // } // }
import org.firepick.firebom.exception.ProxyResolutionException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail;
} catch (Exception e) { fail(e.getMessage()); } assert (proxy.isFresh()); assert (proxy.isResolved()); // Sampling has no effect on freshness proxy.sample(); assert (proxy.isFresh()); assert (proxy.isResolved()); testProxyAge(proxy); return this; } public RefreshableProxyTester testRefreshFailure(IRefreshableProxy proxy) { // Initial proxy state testInitialProxyState(proxy); // Sampling has no effect on freshness proxy.sample(); testInitialProxyState(proxy); long ageBefore = proxy.getAge(); try { proxy.refresh(); fail("Expected refresh failure"); } catch (Exception e) {
// Path: src/main/java/org/firepick/firebom/exception/ProxyResolutionException.java // public class ProxyResolutionException extends RuntimeException { // public ProxyResolutionException(Exception e) { // super(e); // } // // public ProxyResolutionException(String message) { // super(message); // } // // public ProxyResolutionException(String message, Exception e) { // super(message, e); // } // } // Path: src/test/java/org/firepick/firebom/RefreshableProxyTester.java import org.firepick.firebom.exception.ProxyResolutionException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; } catch (Exception e) { fail(e.getMessage()); } assert (proxy.isFresh()); assert (proxy.isResolved()); // Sampling has no effect on freshness proxy.sample(); assert (proxy.isFresh()); assert (proxy.isResolved()); testProxyAge(proxy); return this; } public RefreshableProxyTester testRefreshFailure(IRefreshableProxy proxy) { // Initial proxy state testInitialProxyState(proxy); // Sampling has no effect on freshness proxy.sample(); testInitialProxyState(proxy); long ageBefore = proxy.getAge(); try { proxy.refresh(); fail("Expected refresh failure"); } catch (Exception e) {
assert (e instanceof ProxyResolutionException);
firepick1/FireBOM
src/main/java/org/firepick/firebom/part/PartFactory.java
// Path: src/main/java/org/firepick/firebom/exception/ProxyResolutionException.java // public class ProxyResolutionException extends RuntimeException { // public ProxyResolutionException(Exception e) { // super(e); // } // // public ProxyResolutionException(String message) { // super(message); // } // // public ProxyResolutionException(String message, Exception e) { // super(message, e); // } // }
import net.sf.ehcache.CacheManager; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import org.firepick.firebom.exception.ProxyResolutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URL; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.regex.Matcher; import java.util.regex.Pattern;
} else if ("www.sparkfun.com".equalsIgnoreCase(host)) { part = new SparkfunPart(this, url, urlResolver); } else if ("www.adafruit.com".equalsIgnoreCase(host)) { part = new AdafruitPart(this, url, urlResolver); } else if ("www.digikey.com".equalsIgnoreCase(host)) { part = new DigiKeyPart(this, url, urlResolver); } else if ("synthetos.myshopify.com".equalsIgnoreCase(host)) { part = new SynthetosPart(this, url, urlResolver); } else { part = new HtmlPart(this, url, urlResolver); } return part; } @Override public ListIterator<Part> iterator() { Ehcache cache = getCache("org.firepick.firebom.part.Part"); return new CacheIterator(cache); } @Override public void run() { while (refreshQueue.size() > 0) { Part part = refreshQueue.poll(); if (part != null && !part.isFresh()) { try { part.refresh(); } catch (Exception e) { if (e != part.getRefreshException()) {
// Path: src/main/java/org/firepick/firebom/exception/ProxyResolutionException.java // public class ProxyResolutionException extends RuntimeException { // public ProxyResolutionException(Exception e) { // super(e); // } // // public ProxyResolutionException(String message) { // super(message); // } // // public ProxyResolutionException(String message, Exception e) { // super(message, e); // } // } // Path: src/main/java/org/firepick/firebom/part/PartFactory.java import net.sf.ehcache.CacheManager; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import org.firepick.firebom.exception.ProxyResolutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URL; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.regex.Matcher; import java.util.regex.Pattern; } else if ("www.sparkfun.com".equalsIgnoreCase(host)) { part = new SparkfunPart(this, url, urlResolver); } else if ("www.adafruit.com".equalsIgnoreCase(host)) { part = new AdafruitPart(this, url, urlResolver); } else if ("www.digikey.com".equalsIgnoreCase(host)) { part = new DigiKeyPart(this, url, urlResolver); } else if ("synthetos.myshopify.com".equalsIgnoreCase(host)) { part = new SynthetosPart(this, url, urlResolver); } else { part = new HtmlPart(this, url, urlResolver); } return part; } @Override public ListIterator<Part> iterator() { Ehcache cache = getCache("org.firepick.firebom.part.Part"); return new CacheIterator(cache); } @Override public void run() { while (refreshQueue.size() > 0) { Part part = refreshQueue.poll(); if (part != null && !part.isFresh()) { try { part.refresh(); } catch (Exception e) { if (e != part.getRefreshException()) {
throw new ProxyResolutionException("Uncaught exception", e);
firepick1/FireBOM
src/main/java/org/firepick/firebom/part/CachedUrlResolver.java
// Path: src/main/java/org/firepick/firebom/exception/ProxyResolutionException.java // public class ProxyResolutionException extends RuntimeException { // public ProxyResolutionException(Exception e) { // super(e); // } // // public ProxyResolutionException(String message) { // super(message); // } // // public ProxyResolutionException(String message, Exception e) { // super(message, e); // } // }
import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.util.Locale.US; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import org.firepick.firebom.exception.ProxyResolutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.*; import javax.xml.bind.DatatypeConverter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.security.cert.X509Certificate;
isr = new InputStreamReader(connection.getInputStream()); int responseCode = connection.getResponseCode(); if (!isCached) { logger.info("get({}) => {}", url, responseCode); } switch (responseCode) { case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: { String location = connection.getHeaderField("Location"); url = new URL(location); followRedirect = true; break; } default: followRedirect = false; break; } } while (followRedirect && (++nFollows <= 5)); BufferedReader br = new BufferedReader(isr); response = new StringBuilder(); String inputLine; while ((inputLine = br.readLine()) != null) { response.append(inputLine); } br.close(); } catch (Exception e) { cacheElement = new Element(url, e); getCache("URL-contents").put(cacheElement);
// Path: src/main/java/org/firepick/firebom/exception/ProxyResolutionException.java // public class ProxyResolutionException extends RuntimeException { // public ProxyResolutionException(Exception e) { // super(e); // } // // public ProxyResolutionException(String message) { // super(message); // } // // public ProxyResolutionException(String message, Exception e) { // super(message, e); // } // } // Path: src/main/java/org/firepick/firebom/part/CachedUrlResolver.java import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.util.Locale.US; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import org.firepick.firebom.exception.ProxyResolutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.*; import javax.xml.bind.DatatypeConverter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.security.cert.X509Certificate; isr = new InputStreamReader(connection.getInputStream()); int responseCode = connection.getResponseCode(); if (!isCached) { logger.info("get({}) => {}", url, responseCode); } switch (responseCode) { case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: { String location = connection.getHeaderField("Location"); url = new URL(location); followRedirect = true; break; } default: followRedirect = false; break; } } while (followRedirect && (++nFollows <= 5)); BufferedReader br = new BufferedReader(isr); response = new StringBuilder(); String inputLine; while ((inputLine = br.readLine()) != null) { response.append(inputLine); } br.close(); } catch (Exception e) { cacheElement = new Element(url, e); getCache("URL-contents").put(cacheElement);
throw new ProxyResolutionException(url.toString(), e);
firepick1/FireBOM
src/main/java/org/firepick/firebom/part/AmazonPart.java
// Path: src/main/java/org/firepick/firebom/exception/ProxyResolutionException.java // public class ProxyResolutionException extends RuntimeException { // public ProxyResolutionException(Exception e) { // super(e); // } // // public ProxyResolutionException(String message) { // super(message); // } // // public ProxyResolutionException(String message, Exception e) { // super(message, e); // } // }
import org.firepick.firebom.exception.ProxyResolutionException; import java.io.IOException; import java.net.URL; import java.util.regex.Pattern;
setTitleCategory(phrase); } } } String price = PartFactory.getInstance().scrapeText(content, startPrice, endPrice); if (price != null) { setPackageCost(Double.parseDouble(price)); } String unitCostStr = PartFactory.getInstance().scrapeText(content, startUnitCost, endUnitCost); if (unitCostStr != null) { try { // double unitCost = Double.parseDouble(unitCostStr); // long units = PartFactory.estimateQuantity(getPackageCost(), unitCost); // setPackageUnits((double) units); } catch (Exception e) { // ignore } } String[] urlTokens = getUrl().toString().split("/"); String id; switch (urlTokens.length) { case 5: id = urlTokens[4]; break; case 6: case 7: id = urlTokens[5]; break; default:
// Path: src/main/java/org/firepick/firebom/exception/ProxyResolutionException.java // public class ProxyResolutionException extends RuntimeException { // public ProxyResolutionException(Exception e) { // super(e); // } // // public ProxyResolutionException(String message) { // super(message); // } // // public ProxyResolutionException(String message, Exception e) { // super(message, e); // } // } // Path: src/main/java/org/firepick/firebom/part/AmazonPart.java import org.firepick.firebom.exception.ProxyResolutionException; import java.io.IOException; import java.net.URL; import java.util.regex.Pattern; setTitleCategory(phrase); } } } String price = PartFactory.getInstance().scrapeText(content, startPrice, endPrice); if (price != null) { setPackageCost(Double.parseDouble(price)); } String unitCostStr = PartFactory.getInstance().scrapeText(content, startUnitCost, endUnitCost); if (unitCostStr != null) { try { // double unitCost = Double.parseDouble(unitCostStr); // long units = PartFactory.estimateQuantity(getPackageCost(), unitCost); // setPackageUnits((double) units); } catch (Exception e) { // ignore } } String[] urlTokens = getUrl().toString().split("/"); String id; switch (urlTokens.length) { case 5: id = urlTokens[4]; break; case 6: case 7: id = urlTokens[5]; break; default:
throw new ProxyResolutionException("Could not parse www.amazon.com url: " + getUrl());
firepick1/FireBOM
src/main/java/org/firepick/firebom/part/Part.java
// Path: src/main/java/org/firepick/firebom/IPartComparable.java // public interface IPartComparable extends Comparable<IPartComparable> { // Part getPart(); // } // // Path: src/main/java/org/firepick/firebom/IRefreshableProxy.java // public interface IRefreshableProxy { // // /** // * Synchronize proxy with remote resource // */ // void refresh(); // // /** // * A newly constructed proxy is not fresh until it is refreshed. // * Freshness lasts until a refresh timeout. Unsampled proxies stay fresh // * forever. // * @return true if proxy has been recently refreshed or never sampled // */ // boolean isFresh(); // // /** // * Use the information provided by the proxy. Frequently sampled proxies should be // * refreshed more often than rarely sampled proxies. Sampling a proxy affects its // * freshness as well as the refresh interval. // */ // void sample(); // // /** // * A resolved proxy is one that has been successfully refreshed at least once in its // * lifetime. // * @return // */ // boolean isResolved(); // // /** // * Return age since last refresh or construction. // * @return // */ // long getAge(); // // } // // Path: src/main/java/org/firepick/firebom/RefreshableTimer.java // public class RefreshableTimer implements IRefreshableProxy, Serializable { // private long minRefreshInterval; // private long lastRefreshMillis; // private long lastSampleMillis; // private double sensitivity; // private boolean isResolved; // private long samplesSinceRefresh; // private long sampleInterval; // // public RefreshableTimer() { // this(0.8d); // } // // public RefreshableTimer(double sensitivity) { // if (sensitivity < 0 || 1 < sensitivity) { // throw new IllegalArgumentException("sensitivity must be between [0..1]"); // } // this.sensitivity = sensitivity; // this.lastRefreshMillis = System.currentTimeMillis(); // this.lastSampleMillis = lastRefreshMillis; // } // // public void refresh() { // lastRefreshMillis = System.currentTimeMillis(); // samplesSinceRefresh = 0; // isResolved = true; // } // // public void sample() { // samplesSinceRefresh++; // long nowMillis = System.currentTimeMillis(); // long msElapsed = nowMillis - lastSampleMillis; // if (isResolved()) { // sampleInterval =(long)(getSensitivity() * msElapsed + (1 - getSensitivity()) * sampleInterval); // } else { // sampleInterval = Math.max(1, msElapsed); // } // lastSampleMillis = nowMillis; // } // // public boolean isFresh() { // long refreshInterval = getRefreshInterval(); // long ageDiff = refreshInterval - getAge(); // return isResolved() && ageDiff >= 0; // } // // public double getSensitivity() { // return sensitivity; // } // // public long getSamplesSinceRefresh() { // return samplesSinceRefresh; // } // // public boolean isResolved() { // return isResolved; // } // // protected RefreshableTimer setResolved(boolean value) { // isResolved = value; // return this; // } // // public long getAge() { // return System.currentTimeMillis() - lastRefreshMillis; // } // // public long getRefreshInterval() { // Long value = getSampleInterval(); // return Math.max(getMinRefreshInterval(), value); // } // // public long getSampleInterval() { // return sampleInterval; // } // // public long getMinRefreshInterval() { // return minRefreshInterval; // } // // public RefreshableTimer setMinRefreshInterval(long minRefreshInterval) { // this.minRefreshInterval = minRefreshInterval; // return this; // } // } // // Path: src/main/java/org/firepick/firebom/exception/CyclicReferenceException.java // public class CyclicReferenceException extends ProxyResolutionException { // public CyclicReferenceException(Exception e) { // super(e); // } // // public CyclicReferenceException(String message) { // super(message); // } // // public CyclicReferenceException(String message, Exception e) { // super(message, e); // } // } // // Path: src/main/java/org/firepick/firebom/exception/ProxyResolutionException.java // public class ProxyResolutionException extends RuntimeException { // public ProxyResolutionException(Exception e) { // super(e); // } // // public ProxyResolutionException(String message) { // super(message); // } // // public ProxyResolutionException(String message, Exception e) { // super(message, e); // } // }
import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Pattern; import org.firepick.firebom.IPartComparable; import org.firepick.firebom.IRefreshableProxy; import org.firepick.firebom.RefreshableTimer; import org.firepick.firebom.exception.CyclicReferenceException; import org.firepick.firebom.exception.ProxyResolutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections;
setRefreshException(proxyResolutionException); } } // The refresh exception may be temporary, so the proxy is treated as "fresh and resolved with error" isResolved = true; sourceList = null; sourcePartUsage = null; requiredParts.clear(); refreshableTimer.refresh(); return getRefreshException(); } public Part refreshAll() { refresh(); for (PartUsage partUsage : requiredParts) { Part part = partUsage.getPart(); part.refreshAll(); } if (sourcePartUsage != null) { sourcePartUsage.getPart().refresh(); } refresh(); return this; } private void validate(Part part, Part rootPart) { if (part == rootPart) {
// Path: src/main/java/org/firepick/firebom/IPartComparable.java // public interface IPartComparable extends Comparable<IPartComparable> { // Part getPart(); // } // // Path: src/main/java/org/firepick/firebom/IRefreshableProxy.java // public interface IRefreshableProxy { // // /** // * Synchronize proxy with remote resource // */ // void refresh(); // // /** // * A newly constructed proxy is not fresh until it is refreshed. // * Freshness lasts until a refresh timeout. Unsampled proxies stay fresh // * forever. // * @return true if proxy has been recently refreshed or never sampled // */ // boolean isFresh(); // // /** // * Use the information provided by the proxy. Frequently sampled proxies should be // * refreshed more often than rarely sampled proxies. Sampling a proxy affects its // * freshness as well as the refresh interval. // */ // void sample(); // // /** // * A resolved proxy is one that has been successfully refreshed at least once in its // * lifetime. // * @return // */ // boolean isResolved(); // // /** // * Return age since last refresh or construction. // * @return // */ // long getAge(); // // } // // Path: src/main/java/org/firepick/firebom/RefreshableTimer.java // public class RefreshableTimer implements IRefreshableProxy, Serializable { // private long minRefreshInterval; // private long lastRefreshMillis; // private long lastSampleMillis; // private double sensitivity; // private boolean isResolved; // private long samplesSinceRefresh; // private long sampleInterval; // // public RefreshableTimer() { // this(0.8d); // } // // public RefreshableTimer(double sensitivity) { // if (sensitivity < 0 || 1 < sensitivity) { // throw new IllegalArgumentException("sensitivity must be between [0..1]"); // } // this.sensitivity = sensitivity; // this.lastRefreshMillis = System.currentTimeMillis(); // this.lastSampleMillis = lastRefreshMillis; // } // // public void refresh() { // lastRefreshMillis = System.currentTimeMillis(); // samplesSinceRefresh = 0; // isResolved = true; // } // // public void sample() { // samplesSinceRefresh++; // long nowMillis = System.currentTimeMillis(); // long msElapsed = nowMillis - lastSampleMillis; // if (isResolved()) { // sampleInterval =(long)(getSensitivity() * msElapsed + (1 - getSensitivity()) * sampleInterval); // } else { // sampleInterval = Math.max(1, msElapsed); // } // lastSampleMillis = nowMillis; // } // // public boolean isFresh() { // long refreshInterval = getRefreshInterval(); // long ageDiff = refreshInterval - getAge(); // return isResolved() && ageDiff >= 0; // } // // public double getSensitivity() { // return sensitivity; // } // // public long getSamplesSinceRefresh() { // return samplesSinceRefresh; // } // // public boolean isResolved() { // return isResolved; // } // // protected RefreshableTimer setResolved(boolean value) { // isResolved = value; // return this; // } // // public long getAge() { // return System.currentTimeMillis() - lastRefreshMillis; // } // // public long getRefreshInterval() { // Long value = getSampleInterval(); // return Math.max(getMinRefreshInterval(), value); // } // // public long getSampleInterval() { // return sampleInterval; // } // // public long getMinRefreshInterval() { // return minRefreshInterval; // } // // public RefreshableTimer setMinRefreshInterval(long minRefreshInterval) { // this.minRefreshInterval = minRefreshInterval; // return this; // } // } // // Path: src/main/java/org/firepick/firebom/exception/CyclicReferenceException.java // public class CyclicReferenceException extends ProxyResolutionException { // public CyclicReferenceException(Exception e) { // super(e); // } // // public CyclicReferenceException(String message) { // super(message); // } // // public CyclicReferenceException(String message, Exception e) { // super(message, e); // } // } // // Path: src/main/java/org/firepick/firebom/exception/ProxyResolutionException.java // public class ProxyResolutionException extends RuntimeException { // public ProxyResolutionException(Exception e) { // super(e); // } // // public ProxyResolutionException(String message) { // super(message); // } // // public ProxyResolutionException(String message, Exception e) { // super(message, e); // } // } // Path: src/main/java/org/firepick/firebom/part/Part.java import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Pattern; import org.firepick.firebom.IPartComparable; import org.firepick.firebom.IRefreshableProxy; import org.firepick.firebom.RefreshableTimer; import org.firepick.firebom.exception.CyclicReferenceException; import org.firepick.firebom.exception.ProxyResolutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; setRefreshException(proxyResolutionException); } } // The refresh exception may be temporary, so the proxy is treated as "fresh and resolved with error" isResolved = true; sourceList = null; sourcePartUsage = null; requiredParts.clear(); refreshableTimer.refresh(); return getRefreshException(); } public Part refreshAll() { refresh(); for (PartUsage partUsage : requiredParts) { Part part = partUsage.getPart(); part.refreshAll(); } if (sourcePartUsage != null) { sourcePartUsage.getPart().refresh(); } refresh(); return this; } private void validate(Part part, Part rootPart) { if (part == rootPart) {
rootPart.setRefreshException(new CyclicReferenceException("Cyclic part reference detected: " + url));
firepick1/FireBOM
src/main/java/org/firepick/firebom/part/HtmlPart.java
// Path: src/main/java/org/firepick/firebom/exception/ProxyResolutionException.java // public class ProxyResolutionException extends RuntimeException { // public ProxyResolutionException(Exception e) { // super(e); // } // // public ProxyResolutionException(String message) { // super(message); // } // // public ProxyResolutionException(String message, Exception e) { // super(message, e); // } // }
import org.firepick.firebom.exception.ProxyResolutionException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern;
package org.firepick.firebom.part; /* HtmlPart.java Copyright (C) 2013 Karl Lew <karl@firepick.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. */ public class HtmlPart extends Part { protected static final Pattern startTitle = Pattern.compile("<title>"); protected static final Pattern endTitle = Pattern.compile("</title>"); public HtmlPart(PartFactory partFactory, URL url, CachedUrlResolver urlResolver) { super(partFactory, url, urlResolver); } @Override protected void refreshFromRemoteContent(String content) throws IOException { setId("UNSUPPORTED"); setTitle("Unsupported FireBOM vendor http://bit.ly/16jPAOr"); String[] ulParts = content.split("</ul>"); List<String> newSourceList = null; PartUsage newSourcePartUsage = null; List<PartUsage> newRequiredParts = null; for (String ulPart : ulParts) { if (ulPart.contains("@Source")) { newSourceList = parseListItemStrings(ulPart); if (newSourceList.size() == 0) {
// Path: src/main/java/org/firepick/firebom/exception/ProxyResolutionException.java // public class ProxyResolutionException extends RuntimeException { // public ProxyResolutionException(Exception e) { // super(e); // } // // public ProxyResolutionException(String message) { // super(message); // } // // public ProxyResolutionException(String message, Exception e) { // super(message, e); // } // } // Path: src/main/java/org/firepick/firebom/part/HtmlPart.java import org.firepick.firebom.exception.ProxyResolutionException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; package org.firepick.firebom.part; /* HtmlPart.java Copyright (C) 2013 Karl Lew <karl@firepick.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. */ public class HtmlPart extends Part { protected static final Pattern startTitle = Pattern.compile("<title>"); protected static final Pattern endTitle = Pattern.compile("</title>"); public HtmlPart(PartFactory partFactory, URL url, CachedUrlResolver urlResolver) { super(partFactory, url, urlResolver); } @Override protected void refreshFromRemoteContent(String content) throws IOException { setId("UNSUPPORTED"); setTitle("Unsupported FireBOM vendor http://bit.ly/16jPAOr"); String[] ulParts = content.split("</ul>"); List<String> newSourceList = null; PartUsage newSourcePartUsage = null; List<PartUsage> newRequiredParts = null; for (String ulPart : ulParts) { if (ulPart.contains("@Source")) { newSourceList = parseListItemStrings(ulPart); if (newSourceList.size() == 0) {
throw new ProxyResolutionException("Html page has no @Sources tag");
firepick1/FireBOM
src/main/java/org/firepick/firebom/part/McMasterCarrPart.java
// Path: src/main/java/org/firepick/firebom/exception/ProxyResolutionException.java // public class ProxyResolutionException extends RuntimeException { // public ProxyResolutionException(Exception e) { // super(e); // } // // public ProxyResolutionException(String message) { // super(message); // } // // public ProxyResolutionException(String message, Exception e) { // super(message, e); // } // }
import org.firepick.firebom.exception.ProxyResolutionException; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.Map; import java.util.regex.Pattern;
private static Pattern endTitle = Pattern.compile("\","); private static Pattern startPrice = Pattern.compile("\"PrceTxt\":\""); private static Pattern endPrice = Pattern.compile("\""); private static Pattern startPackageUnits = Pattern.compile("\"SellStdPkgQty\":"); private static Pattern endPackageUnits = Pattern.compile(","); private static Pattern startDetail = Pattern.compile("data-mcm-attr-comp-itm-ids=\""); private static Pattern endDetail = Pattern.compile("\""); private static Pattern startDetailItem = Pattern.compile("#"); private static Pattern endDetailIndex = Pattern.compile("$"); private static Pattern startDetailPrice = Pattern.compile("\"PrceTxt\":\"\\$"); private static Pattern endDetailPrice = Pattern.compile("[^0-9.]*\""); private static String userDataUrl = "http://www.mcmaster.com/UserData.aspx"; private static String queryUrlTemplate = "http://www.mcmaster.com/WebParts/Ordering/InLnOrdWebPart/InLnOrdWebPart.aspx?cntnridtxt=InLnOrd_ItmBxRw_1_{PART}&partnbrtxt={PART}&multipartnbrind=false&partnbrslctdmsgcntxtnm=FullPrsnttn&autoslctdind=false"; private static String detailQueryTemplate = "http://www.mcmaster.com/WebParts/Content/ItmPrsnttnWebPart.aspx?partnbrtxt={PART}&attrnm=&attrval=&attrcompitmids=&cntnridtxt=MainContent&proddtllnkclickedInd=true&cntnrWdth=1188"; private static String detailPriceQueryTemplate = "http://www.mcmaster.com/WebParts/Content/ItmPrsnttnDynamicDat.aspx?acttxt=dynamicdat&partnbrtxt={PART}&isinlnspec=true&attrCompIds={DETAIL}"; public McMasterCarrPart(PartFactory partFactory, URL url, CachedUrlResolver urlResolver) { super(partFactory, url, urlResolver); } @Override public URL normalizeUrl(URL url) { String normalizedUrl = url.toString().replaceAll("/=[a-zA-Z0-9]*", ""); try { return new URL(normalizedUrl); } catch (MalformedURLException e) {
// Path: src/main/java/org/firepick/firebom/exception/ProxyResolutionException.java // public class ProxyResolutionException extends RuntimeException { // public ProxyResolutionException(Exception e) { // super(e); // } // // public ProxyResolutionException(String message) { // super(message); // } // // public ProxyResolutionException(String message, Exception e) { // super(message, e); // } // } // Path: src/main/java/org/firepick/firebom/part/McMasterCarrPart.java import org.firepick.firebom.exception.ProxyResolutionException; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.Map; import java.util.regex.Pattern; private static Pattern endTitle = Pattern.compile("\","); private static Pattern startPrice = Pattern.compile("\"PrceTxt\":\""); private static Pattern endPrice = Pattern.compile("\""); private static Pattern startPackageUnits = Pattern.compile("\"SellStdPkgQty\":"); private static Pattern endPackageUnits = Pattern.compile(","); private static Pattern startDetail = Pattern.compile("data-mcm-attr-comp-itm-ids=\""); private static Pattern endDetail = Pattern.compile("\""); private static Pattern startDetailItem = Pattern.compile("#"); private static Pattern endDetailIndex = Pattern.compile("$"); private static Pattern startDetailPrice = Pattern.compile("\"PrceTxt\":\"\\$"); private static Pattern endDetailPrice = Pattern.compile("[^0-9.]*\""); private static String userDataUrl = "http://www.mcmaster.com/UserData.aspx"; private static String queryUrlTemplate = "http://www.mcmaster.com/WebParts/Ordering/InLnOrdWebPart/InLnOrdWebPart.aspx?cntnridtxt=InLnOrd_ItmBxRw_1_{PART}&partnbrtxt={PART}&multipartnbrind=false&partnbrslctdmsgcntxtnm=FullPrsnttn&autoslctdind=false"; private static String detailQueryTemplate = "http://www.mcmaster.com/WebParts/Content/ItmPrsnttnWebPart.aspx?partnbrtxt={PART}&attrnm=&attrval=&attrcompitmids=&cntnridtxt=MainContent&proddtllnkclickedInd=true&cntnrWdth=1188"; private static String detailPriceQueryTemplate = "http://www.mcmaster.com/WebParts/Content/ItmPrsnttnDynamicDat.aspx?acttxt=dynamicdat&partnbrtxt={PART}&isinlnspec=true&attrCompIds={DETAIL}"; public McMasterCarrPart(PartFactory partFactory, URL url, CachedUrlResolver urlResolver) { super(partFactory, url, urlResolver); } @Override public URL normalizeUrl(URL url) { String normalizedUrl = url.toString().replaceAll("/=[a-zA-Z0-9]*", ""); try { return new URL(normalizedUrl); } catch (MalformedURLException e) {
throw new ProxyResolutionException(url.toString(), e);
firepick1/FireBOM
src/main/java/org/firepick/firebom/bom/BOMRowIterator.java
// Path: src/main/java/org/firepick/firebom/IPartComparable.java // public interface IPartComparable extends Comparable<IPartComparable> { // Part getPart(); // } // // Path: src/main/java/org/firepick/firebom/part/VendorComparator.java // public class VendorComparator implements Comparator<IPartComparable> { // @Override // public int compare(IPartComparable o1, IPartComparable o2) { // Part part1 = o1.getPart(); // Part part2 = o2.getPart(); // int cmp = 0; // if (part1 != part2) { // if (part1 == null) { // cmp = -1; // } else if (part2 == null) { // cmp = 1; // } else { // String vendor1 = part1.getVendor(); // String vendor2 = part2.getVendor(); // if (vendor1 != vendor2) { // if (vendor1 == null) { // cmp = -1; // } else if (vendor2 == null) { // cmp = 1; // } else { // cmp = vendor1.compareTo(vendor2); // } // } // } // } // if (cmp == 0) { // cmp = part1.getUrl().toString().compareTo(part2.getUrl().toString()); // } // // return cmp; // } // } // // Path: src/main/java/org/firepick/relation/IRow.java // public interface IRow { // IRelation getRelation(); // Object item(int index); // }
import org.firepick.firebom.IPartComparable; import org.firepick.firebom.part.VendorComparator; import org.firepick.relation.IRow; import java.util.Iterator; import java.util.TreeSet;
package org.firepick.firebom.bom; /* BOMRowIterator.java Copyright (C) 2013 Karl Lew <karl@firepick.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. */ public class BOMRowIterator implements Iterator<IRow> { private Iterator<BOMRow> iterator;
// Path: src/main/java/org/firepick/firebom/IPartComparable.java // public interface IPartComparable extends Comparable<IPartComparable> { // Part getPart(); // } // // Path: src/main/java/org/firepick/firebom/part/VendorComparator.java // public class VendorComparator implements Comparator<IPartComparable> { // @Override // public int compare(IPartComparable o1, IPartComparable o2) { // Part part1 = o1.getPart(); // Part part2 = o2.getPart(); // int cmp = 0; // if (part1 != part2) { // if (part1 == null) { // cmp = -1; // } else if (part2 == null) { // cmp = 1; // } else { // String vendor1 = part1.getVendor(); // String vendor2 = part2.getVendor(); // if (vendor1 != vendor2) { // if (vendor1 == null) { // cmp = -1; // } else if (vendor2 == null) { // cmp = 1; // } else { // cmp = vendor1.compareTo(vendor2); // } // } // } // } // if (cmp == 0) { // cmp = part1.getUrl().toString().compareTo(part2.getUrl().toString()); // } // // return cmp; // } // } // // Path: src/main/java/org/firepick/relation/IRow.java // public interface IRow { // IRelation getRelation(); // Object item(int index); // } // Path: src/main/java/org/firepick/firebom/bom/BOMRowIterator.java import org.firepick.firebom.IPartComparable; import org.firepick.firebom.part.VendorComparator; import org.firepick.relation.IRow; import java.util.Iterator; import java.util.TreeSet; package org.firepick.firebom.bom; /* BOMRowIterator.java Copyright (C) 2013 Karl Lew <karl@firepick.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. */ public class BOMRowIterator implements Iterator<IRow> { private Iterator<BOMRow> iterator;
public BOMRowIterator(Iterator<IPartComparable> iterator) {
firepick1/FireBOM
src/main/java/org/firepick/firebom/bom/BOMRowIterator.java
// Path: src/main/java/org/firepick/firebom/IPartComparable.java // public interface IPartComparable extends Comparable<IPartComparable> { // Part getPart(); // } // // Path: src/main/java/org/firepick/firebom/part/VendorComparator.java // public class VendorComparator implements Comparator<IPartComparable> { // @Override // public int compare(IPartComparable o1, IPartComparable o2) { // Part part1 = o1.getPart(); // Part part2 = o2.getPart(); // int cmp = 0; // if (part1 != part2) { // if (part1 == null) { // cmp = -1; // } else if (part2 == null) { // cmp = 1; // } else { // String vendor1 = part1.getVendor(); // String vendor2 = part2.getVendor(); // if (vendor1 != vendor2) { // if (vendor1 == null) { // cmp = -1; // } else if (vendor2 == null) { // cmp = 1; // } else { // cmp = vendor1.compareTo(vendor2); // } // } // } // } // if (cmp == 0) { // cmp = part1.getUrl().toString().compareTo(part2.getUrl().toString()); // } // // return cmp; // } // } // // Path: src/main/java/org/firepick/relation/IRow.java // public interface IRow { // IRelation getRelation(); // Object item(int index); // }
import org.firepick.firebom.IPartComparable; import org.firepick.firebom.part.VendorComparator; import org.firepick.relation.IRow; import java.util.Iterator; import java.util.TreeSet;
package org.firepick.firebom.bom; /* BOMRowIterator.java Copyright (C) 2013 Karl Lew <karl@firepick.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. */ public class BOMRowIterator implements Iterator<IRow> { private Iterator<BOMRow> iterator; public BOMRowIterator(Iterator<IPartComparable> iterator) {
// Path: src/main/java/org/firepick/firebom/IPartComparable.java // public interface IPartComparable extends Comparable<IPartComparable> { // Part getPart(); // } // // Path: src/main/java/org/firepick/firebom/part/VendorComparator.java // public class VendorComparator implements Comparator<IPartComparable> { // @Override // public int compare(IPartComparable o1, IPartComparable o2) { // Part part1 = o1.getPart(); // Part part2 = o2.getPart(); // int cmp = 0; // if (part1 != part2) { // if (part1 == null) { // cmp = -1; // } else if (part2 == null) { // cmp = 1; // } else { // String vendor1 = part1.getVendor(); // String vendor2 = part2.getVendor(); // if (vendor1 != vendor2) { // if (vendor1 == null) { // cmp = -1; // } else if (vendor2 == null) { // cmp = 1; // } else { // cmp = vendor1.compareTo(vendor2); // } // } // } // } // if (cmp == 0) { // cmp = part1.getUrl().toString().compareTo(part2.getUrl().toString()); // } // // return cmp; // } // } // // Path: src/main/java/org/firepick/relation/IRow.java // public interface IRow { // IRelation getRelation(); // Object item(int index); // } // Path: src/main/java/org/firepick/firebom/bom/BOMRowIterator.java import org.firepick.firebom.IPartComparable; import org.firepick.firebom.part.VendorComparator; import org.firepick.relation.IRow; import java.util.Iterator; import java.util.TreeSet; package org.firepick.firebom.bom; /* BOMRowIterator.java Copyright (C) 2013 Karl Lew <karl@firepick.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. */ public class BOMRowIterator implements Iterator<IRow> { private Iterator<BOMRow> iterator; public BOMRowIterator(Iterator<IPartComparable> iterator) {
TreeSet<BOMRow> treeSet = new TreeSet(new VendorComparator());
firepick1/FireBOM
src/main/java/org/firepick/firebom/bom/BOMMarkdownPrinter.java
// Path: src/main/java/org/firepick/relation/IRelation.java // public interface IRelation extends Iterable<IRow> { // List<IColumnDescription> describeColumns(); // long getRowCount(); // } // // Path: src/main/java/org/firepick/relation/IRow.java // public interface IRow { // IRelation getRelation(); // Object item(int index); // } // // Path: src/main/java/org/firepick/relation/IRowVisitor.java // public interface IRowVisitor { // void visit(IRow row); // } // // Path: src/main/java/org/firepick/relation/RelationPrinter.java // public class RelationPrinter { // private List<IColumnDescription> columnDescriptionList = new ArrayList<IColumnDescription>(); // private String columnSeparator = ", "; // private boolean printTotalRow = true; // private boolean printTitleRow = true; // // public RelationPrinter print(IRelation relation, PrintStream printStream, IRowVisitor rowVisitor) { // if (columnDescriptionList.size() == 0) { // columnDescriptionList = new ArrayList<IColumnDescription>(relation.describeColumns()); // } // // if (printTitleRow) { // printColumnTitles(printStream, relation); // } // synchronized (columnDescriptionList) { // printRows(relation, printStream, rowVisitor); // } // return this; // } // // private void printRows(IRelation relation, PrintStream printStream, IRowVisitor rowVisitor) { // for (IColumnDescription columnDescription : columnDescriptionList) { // columnDescription.getAggregator().clear(); // } // // int iRow = 1; // for (IRow row : relation) { // printRow(printStream, row, iRow++, rowVisitor); // } // // if (printTotalRow) { // printTotalRow(printStream, relation); // } // } // // protected void printTotalRow(PrintStream printStream, IRelation relation) { // int columns = 0; // for (IColumnDescription columnDescription : columnDescriptionList) { // if (columns++ > 0) { // printStream.print(columnSeparator); // } // Object aggregate = columnDescription.getAggregator().getAggregate(); // printValue(printStream, columnDescription, aggregate); // } // printStream.println(); // } // // protected void printRow(PrintStream printStream, IRow row, int iRow, IRowVisitor rowVisitor) { // if (rowVisitor != null) { // rowVisitor.visit(row); // } // // int columns = 0; // for (IColumnDescription columnDescription : columnDescriptionList) { // if (columns++ > 0) { // printStream.print(columnSeparator); // } // Object value = printColumnValue(printStream, columnDescription, row); // if (printTotalRow) { // columnDescription.getAggregator().aggregate(value); // } // } // printStream.println(); // } // // protected Object printColumnValue(PrintStream printStream, IColumnDescription columnDescription, IRow row) { // Object value = row.item(columnDescription.getItemIndex()); // printValue(printStream, columnDescription, value); // return value; // } // // protected void printValue(PrintStream printStream, IColumnDescription columnDescription, Object value) { // Format format = columnDescription.getFormat(); // if (format == null) { // printStream.print(value); // } else { // printStream.print(format.format(value)); // } // } // // private void printColumnTitles(PrintStream printStream, IRelation relation) { // int columns = 0; // for (IColumnDescription columnDescription : columnDescriptionList) { // if (columns++ > 0) { // printStream.print(columnSeparator); // } // String title = columnDescription.getTitle(); // printValue(printStream, columnDescription, title); // } // printStream.println(); // } // // public List<IColumnDescription> getColumnDescriptionList() { // return columnDescriptionList; // } // // public RelationPrinter setColumnDescriptionList(List<IColumnDescription> columnDescriptionList) { // this.columnDescriptionList = columnDescriptionList; // return this; // } // // public String getColumnSeparator() { // return columnSeparator; // } // // public RelationPrinter setColumnSeparator(String columnSeparator) { // this.columnSeparator = columnSeparator; // return this; // } // // public boolean isPrintTotalRow() { // return printTotalRow; // } // // public RelationPrinter setPrintTotalRow(boolean printTotalRow) { // this.printTotalRow = printTotalRow; // return this; // } // // public boolean isPrintTitleRow() { // return printTitleRow; // } // // public RelationPrinter setPrintTitleRow(boolean printTitleRow) { // this.printTitleRow = printTitleRow; // return this; // } // }
import org.firepick.relation.IRelation; import org.firepick.relation.IRow; import org.firepick.relation.IRowVisitor; import org.firepick.relation.RelationPrinter; import java.io.PrintStream; import java.text.DecimalFormat; import java.text.NumberFormat;
package org.firepick.firebom.bom; /* BOMMarkdownPrinter.java Copyright (C) 2013 Karl Lew <karl@firepick.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. */ public class BOMMarkdownPrinter extends RelationPrinter { public BOMMarkdownPrinter() { super.setPrintTitleRow(false); super.setPrintTotalRow(false); } @Override
// Path: src/main/java/org/firepick/relation/IRelation.java // public interface IRelation extends Iterable<IRow> { // List<IColumnDescription> describeColumns(); // long getRowCount(); // } // // Path: src/main/java/org/firepick/relation/IRow.java // public interface IRow { // IRelation getRelation(); // Object item(int index); // } // // Path: src/main/java/org/firepick/relation/IRowVisitor.java // public interface IRowVisitor { // void visit(IRow row); // } // // Path: src/main/java/org/firepick/relation/RelationPrinter.java // public class RelationPrinter { // private List<IColumnDescription> columnDescriptionList = new ArrayList<IColumnDescription>(); // private String columnSeparator = ", "; // private boolean printTotalRow = true; // private boolean printTitleRow = true; // // public RelationPrinter print(IRelation relation, PrintStream printStream, IRowVisitor rowVisitor) { // if (columnDescriptionList.size() == 0) { // columnDescriptionList = new ArrayList<IColumnDescription>(relation.describeColumns()); // } // // if (printTitleRow) { // printColumnTitles(printStream, relation); // } // synchronized (columnDescriptionList) { // printRows(relation, printStream, rowVisitor); // } // return this; // } // // private void printRows(IRelation relation, PrintStream printStream, IRowVisitor rowVisitor) { // for (IColumnDescription columnDescription : columnDescriptionList) { // columnDescription.getAggregator().clear(); // } // // int iRow = 1; // for (IRow row : relation) { // printRow(printStream, row, iRow++, rowVisitor); // } // // if (printTotalRow) { // printTotalRow(printStream, relation); // } // } // // protected void printTotalRow(PrintStream printStream, IRelation relation) { // int columns = 0; // for (IColumnDescription columnDescription : columnDescriptionList) { // if (columns++ > 0) { // printStream.print(columnSeparator); // } // Object aggregate = columnDescription.getAggregator().getAggregate(); // printValue(printStream, columnDescription, aggregate); // } // printStream.println(); // } // // protected void printRow(PrintStream printStream, IRow row, int iRow, IRowVisitor rowVisitor) { // if (rowVisitor != null) { // rowVisitor.visit(row); // } // // int columns = 0; // for (IColumnDescription columnDescription : columnDescriptionList) { // if (columns++ > 0) { // printStream.print(columnSeparator); // } // Object value = printColumnValue(printStream, columnDescription, row); // if (printTotalRow) { // columnDescription.getAggregator().aggregate(value); // } // } // printStream.println(); // } // // protected Object printColumnValue(PrintStream printStream, IColumnDescription columnDescription, IRow row) { // Object value = row.item(columnDescription.getItemIndex()); // printValue(printStream, columnDescription, value); // return value; // } // // protected void printValue(PrintStream printStream, IColumnDescription columnDescription, Object value) { // Format format = columnDescription.getFormat(); // if (format == null) { // printStream.print(value); // } else { // printStream.print(format.format(value)); // } // } // // private void printColumnTitles(PrintStream printStream, IRelation relation) { // int columns = 0; // for (IColumnDescription columnDescription : columnDescriptionList) { // if (columns++ > 0) { // printStream.print(columnSeparator); // } // String title = columnDescription.getTitle(); // printValue(printStream, columnDescription, title); // } // printStream.println(); // } // // public List<IColumnDescription> getColumnDescriptionList() { // return columnDescriptionList; // } // // public RelationPrinter setColumnDescriptionList(List<IColumnDescription> columnDescriptionList) { // this.columnDescriptionList = columnDescriptionList; // return this; // } // // public String getColumnSeparator() { // return columnSeparator; // } // // public RelationPrinter setColumnSeparator(String columnSeparator) { // this.columnSeparator = columnSeparator; // return this; // } // // public boolean isPrintTotalRow() { // return printTotalRow; // } // // public RelationPrinter setPrintTotalRow(boolean printTotalRow) { // this.printTotalRow = printTotalRow; // return this; // } // // public boolean isPrintTitleRow() { // return printTitleRow; // } // // public RelationPrinter setPrintTitleRow(boolean printTitleRow) { // this.printTitleRow = printTitleRow; // return this; // } // } // Path: src/main/java/org/firepick/firebom/bom/BOMMarkdownPrinter.java import org.firepick.relation.IRelation; import org.firepick.relation.IRow; import org.firepick.relation.IRowVisitor; import org.firepick.relation.RelationPrinter; import java.io.PrintStream; import java.text.DecimalFormat; import java.text.NumberFormat; package org.firepick.firebom.bom; /* BOMMarkdownPrinter.java Copyright (C) 2013 Karl Lew <karl@firepick.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. */ public class BOMMarkdownPrinter extends RelationPrinter { public BOMMarkdownPrinter() { super.setPrintTitleRow(false); super.setPrintTotalRow(false); } @Override
public RelationPrinter print(IRelation relation, PrintStream printStream, IRowVisitor rowVisitor) {
firepick1/FireBOM
src/main/java/org/firepick/firebom/bom/BOMMarkdownPrinter.java
// Path: src/main/java/org/firepick/relation/IRelation.java // public interface IRelation extends Iterable<IRow> { // List<IColumnDescription> describeColumns(); // long getRowCount(); // } // // Path: src/main/java/org/firepick/relation/IRow.java // public interface IRow { // IRelation getRelation(); // Object item(int index); // } // // Path: src/main/java/org/firepick/relation/IRowVisitor.java // public interface IRowVisitor { // void visit(IRow row); // } // // Path: src/main/java/org/firepick/relation/RelationPrinter.java // public class RelationPrinter { // private List<IColumnDescription> columnDescriptionList = new ArrayList<IColumnDescription>(); // private String columnSeparator = ", "; // private boolean printTotalRow = true; // private boolean printTitleRow = true; // // public RelationPrinter print(IRelation relation, PrintStream printStream, IRowVisitor rowVisitor) { // if (columnDescriptionList.size() == 0) { // columnDescriptionList = new ArrayList<IColumnDescription>(relation.describeColumns()); // } // // if (printTitleRow) { // printColumnTitles(printStream, relation); // } // synchronized (columnDescriptionList) { // printRows(relation, printStream, rowVisitor); // } // return this; // } // // private void printRows(IRelation relation, PrintStream printStream, IRowVisitor rowVisitor) { // for (IColumnDescription columnDescription : columnDescriptionList) { // columnDescription.getAggregator().clear(); // } // // int iRow = 1; // for (IRow row : relation) { // printRow(printStream, row, iRow++, rowVisitor); // } // // if (printTotalRow) { // printTotalRow(printStream, relation); // } // } // // protected void printTotalRow(PrintStream printStream, IRelation relation) { // int columns = 0; // for (IColumnDescription columnDescription : columnDescriptionList) { // if (columns++ > 0) { // printStream.print(columnSeparator); // } // Object aggregate = columnDescription.getAggregator().getAggregate(); // printValue(printStream, columnDescription, aggregate); // } // printStream.println(); // } // // protected void printRow(PrintStream printStream, IRow row, int iRow, IRowVisitor rowVisitor) { // if (rowVisitor != null) { // rowVisitor.visit(row); // } // // int columns = 0; // for (IColumnDescription columnDescription : columnDescriptionList) { // if (columns++ > 0) { // printStream.print(columnSeparator); // } // Object value = printColumnValue(printStream, columnDescription, row); // if (printTotalRow) { // columnDescription.getAggregator().aggregate(value); // } // } // printStream.println(); // } // // protected Object printColumnValue(PrintStream printStream, IColumnDescription columnDescription, IRow row) { // Object value = row.item(columnDescription.getItemIndex()); // printValue(printStream, columnDescription, value); // return value; // } // // protected void printValue(PrintStream printStream, IColumnDescription columnDescription, Object value) { // Format format = columnDescription.getFormat(); // if (format == null) { // printStream.print(value); // } else { // printStream.print(format.format(value)); // } // } // // private void printColumnTitles(PrintStream printStream, IRelation relation) { // int columns = 0; // for (IColumnDescription columnDescription : columnDescriptionList) { // if (columns++ > 0) { // printStream.print(columnSeparator); // } // String title = columnDescription.getTitle(); // printValue(printStream, columnDescription, title); // } // printStream.println(); // } // // public List<IColumnDescription> getColumnDescriptionList() { // return columnDescriptionList; // } // // public RelationPrinter setColumnDescriptionList(List<IColumnDescription> columnDescriptionList) { // this.columnDescriptionList = columnDescriptionList; // return this; // } // // public String getColumnSeparator() { // return columnSeparator; // } // // public RelationPrinter setColumnSeparator(String columnSeparator) { // this.columnSeparator = columnSeparator; // return this; // } // // public boolean isPrintTotalRow() { // return printTotalRow; // } // // public RelationPrinter setPrintTotalRow(boolean printTotalRow) { // this.printTotalRow = printTotalRow; // return this; // } // // public boolean isPrintTitleRow() { // return printTitleRow; // } // // public RelationPrinter setPrintTitleRow(boolean printTitleRow) { // this.printTitleRow = printTitleRow; // return this; // } // }
import org.firepick.relation.IRelation; import org.firepick.relation.IRow; import org.firepick.relation.IRowVisitor; import org.firepick.relation.RelationPrinter; import java.io.PrintStream; import java.text.DecimalFormat; import java.text.NumberFormat;
package org.firepick.firebom.bom; /* BOMMarkdownPrinter.java Copyright (C) 2013 Karl Lew <karl@firepick.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. */ public class BOMMarkdownPrinter extends RelationPrinter { public BOMMarkdownPrinter() { super.setPrintTitleRow(false); super.setPrintTotalRow(false); } @Override
// Path: src/main/java/org/firepick/relation/IRelation.java // public interface IRelation extends Iterable<IRow> { // List<IColumnDescription> describeColumns(); // long getRowCount(); // } // // Path: src/main/java/org/firepick/relation/IRow.java // public interface IRow { // IRelation getRelation(); // Object item(int index); // } // // Path: src/main/java/org/firepick/relation/IRowVisitor.java // public interface IRowVisitor { // void visit(IRow row); // } // // Path: src/main/java/org/firepick/relation/RelationPrinter.java // public class RelationPrinter { // private List<IColumnDescription> columnDescriptionList = new ArrayList<IColumnDescription>(); // private String columnSeparator = ", "; // private boolean printTotalRow = true; // private boolean printTitleRow = true; // // public RelationPrinter print(IRelation relation, PrintStream printStream, IRowVisitor rowVisitor) { // if (columnDescriptionList.size() == 0) { // columnDescriptionList = new ArrayList<IColumnDescription>(relation.describeColumns()); // } // // if (printTitleRow) { // printColumnTitles(printStream, relation); // } // synchronized (columnDescriptionList) { // printRows(relation, printStream, rowVisitor); // } // return this; // } // // private void printRows(IRelation relation, PrintStream printStream, IRowVisitor rowVisitor) { // for (IColumnDescription columnDescription : columnDescriptionList) { // columnDescription.getAggregator().clear(); // } // // int iRow = 1; // for (IRow row : relation) { // printRow(printStream, row, iRow++, rowVisitor); // } // // if (printTotalRow) { // printTotalRow(printStream, relation); // } // } // // protected void printTotalRow(PrintStream printStream, IRelation relation) { // int columns = 0; // for (IColumnDescription columnDescription : columnDescriptionList) { // if (columns++ > 0) { // printStream.print(columnSeparator); // } // Object aggregate = columnDescription.getAggregator().getAggregate(); // printValue(printStream, columnDescription, aggregate); // } // printStream.println(); // } // // protected void printRow(PrintStream printStream, IRow row, int iRow, IRowVisitor rowVisitor) { // if (rowVisitor != null) { // rowVisitor.visit(row); // } // // int columns = 0; // for (IColumnDescription columnDescription : columnDescriptionList) { // if (columns++ > 0) { // printStream.print(columnSeparator); // } // Object value = printColumnValue(printStream, columnDescription, row); // if (printTotalRow) { // columnDescription.getAggregator().aggregate(value); // } // } // printStream.println(); // } // // protected Object printColumnValue(PrintStream printStream, IColumnDescription columnDescription, IRow row) { // Object value = row.item(columnDescription.getItemIndex()); // printValue(printStream, columnDescription, value); // return value; // } // // protected void printValue(PrintStream printStream, IColumnDescription columnDescription, Object value) { // Format format = columnDescription.getFormat(); // if (format == null) { // printStream.print(value); // } else { // printStream.print(format.format(value)); // } // } // // private void printColumnTitles(PrintStream printStream, IRelation relation) { // int columns = 0; // for (IColumnDescription columnDescription : columnDescriptionList) { // if (columns++ > 0) { // printStream.print(columnSeparator); // } // String title = columnDescription.getTitle(); // printValue(printStream, columnDescription, title); // } // printStream.println(); // } // // public List<IColumnDescription> getColumnDescriptionList() { // return columnDescriptionList; // } // // public RelationPrinter setColumnDescriptionList(List<IColumnDescription> columnDescriptionList) { // this.columnDescriptionList = columnDescriptionList; // return this; // } // // public String getColumnSeparator() { // return columnSeparator; // } // // public RelationPrinter setColumnSeparator(String columnSeparator) { // this.columnSeparator = columnSeparator; // return this; // } // // public boolean isPrintTotalRow() { // return printTotalRow; // } // // public RelationPrinter setPrintTotalRow(boolean printTotalRow) { // this.printTotalRow = printTotalRow; // return this; // } // // public boolean isPrintTitleRow() { // return printTitleRow; // } // // public RelationPrinter setPrintTitleRow(boolean printTitleRow) { // this.printTitleRow = printTitleRow; // return this; // } // } // Path: src/main/java/org/firepick/firebom/bom/BOMMarkdownPrinter.java import org.firepick.relation.IRelation; import org.firepick.relation.IRow; import org.firepick.relation.IRowVisitor; import org.firepick.relation.RelationPrinter; import java.io.PrintStream; import java.text.DecimalFormat; import java.text.NumberFormat; package org.firepick.firebom.bom; /* BOMMarkdownPrinter.java Copyright (C) 2013 Karl Lew <karl@firepick.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. */ public class BOMMarkdownPrinter extends RelationPrinter { public BOMMarkdownPrinter() { super.setPrintTitleRow(false); super.setPrintTotalRow(false); } @Override
public RelationPrinter print(IRelation relation, PrintStream printStream, IRowVisitor rowVisitor) {
xushaomin/apple-deploy
src/main/java/com/appleframework/deploy/dao/TaskMapper.java
// Path: src/main/java/com/appleframework/deploy/entity/Task.java // public class Task implements Serializable { // // private Integer id; // // private Integer projectId; // // private String projectName; // // private String hosts; // // private String title; // // private Integer action; // // private Integer status; // // private String version; // // private String exVersion; // // private Date createAt; // // private Date updateAt; // // private String createBy; // // private String updateBy; // // private static final long serialVersionUID = 1L; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getProjectId() { // return projectId; // } // // public void setProjectId(Integer projectId) { // this.projectId = projectId; // } // // public String getProjectName() { // return projectName; // } // // public void setProjectName(String projectName) { // this.projectName = projectName == null ? null : projectName.trim(); // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title == null ? null : title.trim(); // } // // public Integer getAction() { // return action; // } // // public void setAction(Integer action) { // this.action = action; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version == null ? null : version.trim(); // } // // public String getExVersion() { // return exVersion; // } // // public void setExVersion(String exVersion) { // this.exVersion = exVersion == null ? null : exVersion.trim(); // } // // public Date getCreateAt() { // return createAt; // } // // public void setCreateAt(Date createAt) { // this.createAt = createAt; // } // // public Date getUpdateAt() { // return updateAt; // } // // public void setUpdateAt(Date updateAt) { // this.updateAt = updateAt; // } // // public String getCreateBy() { // return createBy; // } // // public void setCreateBy(String createBy) { // this.createBy = createBy == null ? null : createBy.trim(); // } // // public String getUpdateBy() { // return updateBy; // } // // public void setUpdateBy(String updateBy) { // this.updateBy = updateBy == null ? null : updateBy.trim(); // } // // public String getHosts() { // return hosts; // } // // public void setHosts(String hosts) { // this.hosts = hosts; // } // // }
import org.springframework.stereotype.Repository; import com.appleframework.deploy.entity.Task;
package com.appleframework.deploy.dao; @Repository public interface TaskMapper { int deleteByPrimaryKey(Integer id);
// Path: src/main/java/com/appleframework/deploy/entity/Task.java // public class Task implements Serializable { // // private Integer id; // // private Integer projectId; // // private String projectName; // // private String hosts; // // private String title; // // private Integer action; // // private Integer status; // // private String version; // // private String exVersion; // // private Date createAt; // // private Date updateAt; // // private String createBy; // // private String updateBy; // // private static final long serialVersionUID = 1L; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getProjectId() { // return projectId; // } // // public void setProjectId(Integer projectId) { // this.projectId = projectId; // } // // public String getProjectName() { // return projectName; // } // // public void setProjectName(String projectName) { // this.projectName = projectName == null ? null : projectName.trim(); // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title == null ? null : title.trim(); // } // // public Integer getAction() { // return action; // } // // public void setAction(Integer action) { // this.action = action; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version == null ? null : version.trim(); // } // // public String getExVersion() { // return exVersion; // } // // public void setExVersion(String exVersion) { // this.exVersion = exVersion == null ? null : exVersion.trim(); // } // // public Date getCreateAt() { // return createAt; // } // // public void setCreateAt(Date createAt) { // this.createAt = createAt; // } // // public Date getUpdateAt() { // return updateAt; // } // // public void setUpdateAt(Date updateAt) { // this.updateAt = updateAt; // } // // public String getCreateBy() { // return createBy; // } // // public void setCreateBy(String createBy) { // this.createBy = createBy == null ? null : createBy.trim(); // } // // public String getUpdateBy() { // return updateBy; // } // // public void setUpdateBy(String updateBy) { // this.updateBy = updateBy == null ? null : updateBy.trim(); // } // // public String getHosts() { // return hosts; // } // // public void setHosts(String hosts) { // this.hosts = hosts; // } // // } // Path: src/main/java/com/appleframework/deploy/dao/TaskMapper.java import org.springframework.stereotype.Repository; import com.appleframework.deploy.entity.Task; package com.appleframework.deploy.dao; @Repository public interface TaskMapper { int deleteByPrimaryKey(Integer id);
int insert(Task record);
xushaomin/apple-deploy
src/main/java/com/appleframework/deploy/service/impl/RecordServiceImpl.java
// Path: src/main/java/com/appleframework/deploy/dao/RecordMapper.java // @Repository // public interface RecordMapper { // int deleteByPrimaryKey(Long id); // // int insert(RecordWithBLOBs record); // // int insertSelective(RecordWithBLOBs record); // // RecordWithBLOBs selectByPrimaryKey(Long id); // // int updateByPrimaryKeySelective(RecordWithBLOBs record); // // int updateByPrimaryKeyWithBLOBs(RecordWithBLOBs record); // // int updateByPrimaryKey(Record record); // } // // Path: src/main/java/com/appleframework/deploy/entity/RecordWithBLOBs.java // public class RecordWithBLOBs extends Record implements Serializable { // private String command; // // private String memo; // // private static final long serialVersionUID = 1L; // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command == null ? null : command.trim(); // } // // public String getMemo() { // return memo; // } // // public void setMemo(String memo) { // this.memo = memo == null ? null : memo.trim(); // } // } // // Path: src/main/java/com/appleframework/deploy/service/RecordService.java // public interface RecordService { // // public Long save(RecordWithBLOBs record) throws AppleException; // // public Long update(RecordWithBLOBs record) throws AppleException; // // public Long delete(Long id) throws AppleException; // // public RecordWithBLOBs get(Long id); // // }
import java.util.Date; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.appleframework.deploy.dao.RecordMapper; import com.appleframework.deploy.entity.RecordWithBLOBs; import com.appleframework.deploy.service.RecordService; import com.appleframework.exception.AppleException;
package com.appleframework.deploy.service.impl; @Service("recordService") public class RecordServiceImpl implements RecordService { @Resource
// Path: src/main/java/com/appleframework/deploy/dao/RecordMapper.java // @Repository // public interface RecordMapper { // int deleteByPrimaryKey(Long id); // // int insert(RecordWithBLOBs record); // // int insertSelective(RecordWithBLOBs record); // // RecordWithBLOBs selectByPrimaryKey(Long id); // // int updateByPrimaryKeySelective(RecordWithBLOBs record); // // int updateByPrimaryKeyWithBLOBs(RecordWithBLOBs record); // // int updateByPrimaryKey(Record record); // } // // Path: src/main/java/com/appleframework/deploy/entity/RecordWithBLOBs.java // public class RecordWithBLOBs extends Record implements Serializable { // private String command; // // private String memo; // // private static final long serialVersionUID = 1L; // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command == null ? null : command.trim(); // } // // public String getMemo() { // return memo; // } // // public void setMemo(String memo) { // this.memo = memo == null ? null : memo.trim(); // } // } // // Path: src/main/java/com/appleframework/deploy/service/RecordService.java // public interface RecordService { // // public Long save(RecordWithBLOBs record) throws AppleException; // // public Long update(RecordWithBLOBs record) throws AppleException; // // public Long delete(Long id) throws AppleException; // // public RecordWithBLOBs get(Long id); // // } // Path: src/main/java/com/appleframework/deploy/service/impl/RecordServiceImpl.java import java.util.Date; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.appleframework.deploy.dao.RecordMapper; import com.appleframework.deploy.entity.RecordWithBLOBs; import com.appleframework.deploy.service.RecordService; import com.appleframework.exception.AppleException; package com.appleframework.deploy.service.impl; @Service("recordService") public class RecordServiceImpl implements RecordService { @Resource
private RecordMapper recordMapper;
xushaomin/apple-deploy
src/main/java/com/appleframework/deploy/service/impl/RecordServiceImpl.java
// Path: src/main/java/com/appleframework/deploy/dao/RecordMapper.java // @Repository // public interface RecordMapper { // int deleteByPrimaryKey(Long id); // // int insert(RecordWithBLOBs record); // // int insertSelective(RecordWithBLOBs record); // // RecordWithBLOBs selectByPrimaryKey(Long id); // // int updateByPrimaryKeySelective(RecordWithBLOBs record); // // int updateByPrimaryKeyWithBLOBs(RecordWithBLOBs record); // // int updateByPrimaryKey(Record record); // } // // Path: src/main/java/com/appleframework/deploy/entity/RecordWithBLOBs.java // public class RecordWithBLOBs extends Record implements Serializable { // private String command; // // private String memo; // // private static final long serialVersionUID = 1L; // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command == null ? null : command.trim(); // } // // public String getMemo() { // return memo; // } // // public void setMemo(String memo) { // this.memo = memo == null ? null : memo.trim(); // } // } // // Path: src/main/java/com/appleframework/deploy/service/RecordService.java // public interface RecordService { // // public Long save(RecordWithBLOBs record) throws AppleException; // // public Long update(RecordWithBLOBs record) throws AppleException; // // public Long delete(Long id) throws AppleException; // // public RecordWithBLOBs get(Long id); // // }
import java.util.Date; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.appleframework.deploy.dao.RecordMapper; import com.appleframework.deploy.entity.RecordWithBLOBs; import com.appleframework.deploy.service.RecordService; import com.appleframework.exception.AppleException;
package com.appleframework.deploy.service.impl; @Service("recordService") public class RecordServiceImpl implements RecordService { @Resource private RecordMapper recordMapper; @Override
// Path: src/main/java/com/appleframework/deploy/dao/RecordMapper.java // @Repository // public interface RecordMapper { // int deleteByPrimaryKey(Long id); // // int insert(RecordWithBLOBs record); // // int insertSelective(RecordWithBLOBs record); // // RecordWithBLOBs selectByPrimaryKey(Long id); // // int updateByPrimaryKeySelective(RecordWithBLOBs record); // // int updateByPrimaryKeyWithBLOBs(RecordWithBLOBs record); // // int updateByPrimaryKey(Record record); // } // // Path: src/main/java/com/appleframework/deploy/entity/RecordWithBLOBs.java // public class RecordWithBLOBs extends Record implements Serializable { // private String command; // // private String memo; // // private static final long serialVersionUID = 1L; // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command == null ? null : command.trim(); // } // // public String getMemo() { // return memo; // } // // public void setMemo(String memo) { // this.memo = memo == null ? null : memo.trim(); // } // } // // Path: src/main/java/com/appleframework/deploy/service/RecordService.java // public interface RecordService { // // public Long save(RecordWithBLOBs record) throws AppleException; // // public Long update(RecordWithBLOBs record) throws AppleException; // // public Long delete(Long id) throws AppleException; // // public RecordWithBLOBs get(Long id); // // } // Path: src/main/java/com/appleframework/deploy/service/impl/RecordServiceImpl.java import java.util.Date; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.appleframework.deploy.dao.RecordMapper; import com.appleframework.deploy.entity.RecordWithBLOBs; import com.appleframework.deploy.service.RecordService; import com.appleframework.exception.AppleException; package com.appleframework.deploy.service.impl; @Service("recordService") public class RecordServiceImpl implements RecordService { @Resource private RecordMapper recordMapper; @Override
public Long save(RecordWithBLOBs record) throws AppleException {
xushaomin/apple-deploy
src/main/java/com/appleframework/deploy/task/DeployTask.java
// Path: src/main/java/com/appleframework/deploy/entity/ProjectWithBLOBs.java // public class ProjectWithBLOBs extends Project implements Serializable { // // private String hosts; // // private String preDeploy; // // private String postDeploy; // // private String afterDeploy; // // private static final long serialVersionUID = 1L; // // public String getHosts() { // return hosts; // } // // public void setHosts(String hosts) { // this.hosts = hosts == null ? null : hosts.trim(); // } // // public String getPreDeploy() { // return preDeploy; // } // // public void setPreDeploy(String preDeploy) { // this.preDeploy = preDeploy == null ? null : preDeploy.trim(); // } // // public String getPostDeploy() { // return postDeploy; // } // // public void setPostDeploy(String postDeploy) { // this.postDeploy = postDeploy == null ? null : postDeploy.trim(); // } // // public String getAfterDeploy() { // return afterDeploy; // } // // public void setAfterDeploy(String afterDeploy) { // this.afterDeploy = afterDeploy == null ? null : afterDeploy.trim(); // } // // } // // Path: src/main/java/com/appleframework/deploy/service/ProjectService.java // public interface ProjectService { // // public Integer save(ProjectWithBLOBs record) throws AppleException; // // public Integer update(ProjectWithBLOBs record) throws AppleException; // // public Integer delete(Integer id) throws AppleException; // // public ProjectWithBLOBs get(Integer id); // // public List<Project> findAll(); // // public boolean isExistByName(String name); // // public boolean isUniqueByName(String oldName, String newName); // // public int countByName(String name); // // public Project getByName(String name); // // public Pagination findPage(Pagination page, ProjectSo so); // // }
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import javax.annotation.Resource; import org.springframework.stereotype.Component; import com.appleframework.deploy.entity.ProjectWithBLOBs; import com.appleframework.deploy.service.ProjectService; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session;
package com.appleframework.deploy.task; @Component public class DeployTask { @Resource
// Path: src/main/java/com/appleframework/deploy/entity/ProjectWithBLOBs.java // public class ProjectWithBLOBs extends Project implements Serializable { // // private String hosts; // // private String preDeploy; // // private String postDeploy; // // private String afterDeploy; // // private static final long serialVersionUID = 1L; // // public String getHosts() { // return hosts; // } // // public void setHosts(String hosts) { // this.hosts = hosts == null ? null : hosts.trim(); // } // // public String getPreDeploy() { // return preDeploy; // } // // public void setPreDeploy(String preDeploy) { // this.preDeploy = preDeploy == null ? null : preDeploy.trim(); // } // // public String getPostDeploy() { // return postDeploy; // } // // public void setPostDeploy(String postDeploy) { // this.postDeploy = postDeploy == null ? null : postDeploy.trim(); // } // // public String getAfterDeploy() { // return afterDeploy; // } // // public void setAfterDeploy(String afterDeploy) { // this.afterDeploy = afterDeploy == null ? null : afterDeploy.trim(); // } // // } // // Path: src/main/java/com/appleframework/deploy/service/ProjectService.java // public interface ProjectService { // // public Integer save(ProjectWithBLOBs record) throws AppleException; // // public Integer update(ProjectWithBLOBs record) throws AppleException; // // public Integer delete(Integer id) throws AppleException; // // public ProjectWithBLOBs get(Integer id); // // public List<Project> findAll(); // // public boolean isExistByName(String name); // // public boolean isUniqueByName(String oldName, String newName); // // public int countByName(String name); // // public Project getByName(String name); // // public Pagination findPage(Pagination page, ProjectSo so); // // } // Path: src/main/java/com/appleframework/deploy/task/DeployTask.java import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import javax.annotation.Resource; import org.springframework.stereotype.Component; import com.appleframework.deploy.entity.ProjectWithBLOBs; import com.appleframework.deploy.service.ProjectService; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; package com.appleframework.deploy.task; @Component public class DeployTask { @Resource
private ProjectService projectService;
xushaomin/apple-deploy
src/main/java/com/appleframework/deploy/task/DeployTask.java
// Path: src/main/java/com/appleframework/deploy/entity/ProjectWithBLOBs.java // public class ProjectWithBLOBs extends Project implements Serializable { // // private String hosts; // // private String preDeploy; // // private String postDeploy; // // private String afterDeploy; // // private static final long serialVersionUID = 1L; // // public String getHosts() { // return hosts; // } // // public void setHosts(String hosts) { // this.hosts = hosts == null ? null : hosts.trim(); // } // // public String getPreDeploy() { // return preDeploy; // } // // public void setPreDeploy(String preDeploy) { // this.preDeploy = preDeploy == null ? null : preDeploy.trim(); // } // // public String getPostDeploy() { // return postDeploy; // } // // public void setPostDeploy(String postDeploy) { // this.postDeploy = postDeploy == null ? null : postDeploy.trim(); // } // // public String getAfterDeploy() { // return afterDeploy; // } // // public void setAfterDeploy(String afterDeploy) { // this.afterDeploy = afterDeploy == null ? null : afterDeploy.trim(); // } // // } // // Path: src/main/java/com/appleframework/deploy/service/ProjectService.java // public interface ProjectService { // // public Integer save(ProjectWithBLOBs record) throws AppleException; // // public Integer update(ProjectWithBLOBs record) throws AppleException; // // public Integer delete(Integer id) throws AppleException; // // public ProjectWithBLOBs get(Integer id); // // public List<Project> findAll(); // // public boolean isExistByName(String name); // // public boolean isUniqueByName(String oldName, String newName); // // public int countByName(String name); // // public Project getByName(String name); // // public Pagination findPage(Pagination page, ProjectSo so); // // }
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import javax.annotation.Resource; import org.springframework.stereotype.Component; import com.appleframework.deploy.entity.ProjectWithBLOBs; import com.appleframework.deploy.service.ProjectService; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session;
package com.appleframework.deploy.task; @Component public class DeployTask { @Resource private ProjectService projectService; //@Scheduled(cron = "0/30 * * * * ?") public void deploy() {
// Path: src/main/java/com/appleframework/deploy/entity/ProjectWithBLOBs.java // public class ProjectWithBLOBs extends Project implements Serializable { // // private String hosts; // // private String preDeploy; // // private String postDeploy; // // private String afterDeploy; // // private static final long serialVersionUID = 1L; // // public String getHosts() { // return hosts; // } // // public void setHosts(String hosts) { // this.hosts = hosts == null ? null : hosts.trim(); // } // // public String getPreDeploy() { // return preDeploy; // } // // public void setPreDeploy(String preDeploy) { // this.preDeploy = preDeploy == null ? null : preDeploy.trim(); // } // // public String getPostDeploy() { // return postDeploy; // } // // public void setPostDeploy(String postDeploy) { // this.postDeploy = postDeploy == null ? null : postDeploy.trim(); // } // // public String getAfterDeploy() { // return afterDeploy; // } // // public void setAfterDeploy(String afterDeploy) { // this.afterDeploy = afterDeploy == null ? null : afterDeploy.trim(); // } // // } // // Path: src/main/java/com/appleframework/deploy/service/ProjectService.java // public interface ProjectService { // // public Integer save(ProjectWithBLOBs record) throws AppleException; // // public Integer update(ProjectWithBLOBs record) throws AppleException; // // public Integer delete(Integer id) throws AppleException; // // public ProjectWithBLOBs get(Integer id); // // public List<Project> findAll(); // // public boolean isExistByName(String name); // // public boolean isUniqueByName(String oldName, String newName); // // public int countByName(String name); // // public Project getByName(String name); // // public Pagination findPage(Pagination page, ProjectSo so); // // } // Path: src/main/java/com/appleframework/deploy/task/DeployTask.java import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import javax.annotation.Resource; import org.springframework.stereotype.Component; import com.appleframework.deploy.entity.ProjectWithBLOBs; import com.appleframework.deploy.service.ProjectService; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; package com.appleframework.deploy.task; @Component public class DeployTask { @Resource private ProjectService projectService; //@Scheduled(cron = "0/30 * * * * ?") public void deploy() {
ProjectWithBLOBs project = projectService.get(1);
xushaomin/apple-deploy
src/main/java/com/appleframework/deploy/dao/extend/TaskExtendMapper.java
// Path: src/main/java/com/appleframework/deploy/entity/Project.java // public class Project implements Serializable { // // private Integer id; // // private String name; // // private Integer type; // // private Integer env; // // private Integer plus; // // private Integer status; // // private String version; // // private String nexusUrl; // // private String nexusGroup; // // private String nexusArtifact; // // private String releaseUser; // // private String releaseTo; // // private Boolean isAudit; // // private Date createAt; // // private Date updateAt; // // private String createBy; // // private String updateBy; // // private static final long serialVersionUID = 1L; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name == null ? null : name.trim(); // } // // public Integer getType() { // return type; // } // // public void setType(Integer type) { // this.type = type; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version == null ? null : version.trim(); // } // // public String getNexusUrl() { // return nexusUrl; // } // // public void setNexusUrl(String nexusUrl) { // this.nexusUrl = nexusUrl == null ? null : nexusUrl.trim(); // } // // public String getNexusGroup() { // return nexusGroup; // } // // public void setNexusGroup(String nexusGroup) { // this.nexusGroup = nexusGroup == null ? null : nexusGroup.trim(); // } // // public String getNexusArtifact() { // return nexusArtifact; // } // // public void setNexusArtifact(String nexusArtifact) { // this.nexusArtifact = nexusArtifact == null ? null : nexusArtifact.trim(); // } // // public String getReleaseUser() { // return releaseUser; // } // // public void setReleaseUser(String releaseUser) { // this.releaseUser = releaseUser == null ? null : releaseUser.trim(); // } // // public String getReleaseTo() { // return releaseTo; // } // // public void setReleaseTo(String releaseTo) { // this.releaseTo = releaseTo == null ? null : releaseTo.trim(); // } // // public Boolean getIsAudit() { // return isAudit; // } // // public void setIsAudit(Boolean isAudit) { // this.isAudit = isAudit; // } // // public Date getCreateAt() { // return createAt; // } // // public void setCreateAt(Date createAt) { // this.createAt = createAt; // } // // public Date getUpdateAt() { // return updateAt; // } // // public void setUpdateAt(Date updateAt) { // this.updateAt = updateAt; // } // // public String getCreateBy() { // return createBy; // } // // public void setCreateBy(String createBy) { // this.createBy = createBy == null ? null : createBy.trim(); // } // // public String getUpdateBy() { // return updateBy; // } // // public void setUpdateBy(String updateBy) { // this.updateBy = updateBy == null ? null : updateBy.trim(); // } // // public Integer getEnv() { // return env; // } // // public void setEnv(Integer env) { // this.env = env; // } // // public Integer getPlus() { // return plus; // } // // public void setPlus(Integer plus) { // this.plus = plus; // } // // } // // Path: src/main/java/com/appleframework/deploy/model/TaskSo.java // public class TaskSo implements Serializable { // // private static final long serialVersionUID = -2819301403023915774L; // // private String title; // private Integer projectId; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public Integer getProjectId() { // return projectId; // } // // public void setProjectId(Integer projectId) { // this.projectId = projectId; // } // // }
import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import com.appleframework.deploy.entity.Project; import com.appleframework.deploy.model.TaskSo; import com.appleframework.model.page.Pagination;
package com.appleframework.deploy.dao.extend; @Repository public interface TaskExtendMapper {
// Path: src/main/java/com/appleframework/deploy/entity/Project.java // public class Project implements Serializable { // // private Integer id; // // private String name; // // private Integer type; // // private Integer env; // // private Integer plus; // // private Integer status; // // private String version; // // private String nexusUrl; // // private String nexusGroup; // // private String nexusArtifact; // // private String releaseUser; // // private String releaseTo; // // private Boolean isAudit; // // private Date createAt; // // private Date updateAt; // // private String createBy; // // private String updateBy; // // private static final long serialVersionUID = 1L; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name == null ? null : name.trim(); // } // // public Integer getType() { // return type; // } // // public void setType(Integer type) { // this.type = type; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version == null ? null : version.trim(); // } // // public String getNexusUrl() { // return nexusUrl; // } // // public void setNexusUrl(String nexusUrl) { // this.nexusUrl = nexusUrl == null ? null : nexusUrl.trim(); // } // // public String getNexusGroup() { // return nexusGroup; // } // // public void setNexusGroup(String nexusGroup) { // this.nexusGroup = nexusGroup == null ? null : nexusGroup.trim(); // } // // public String getNexusArtifact() { // return nexusArtifact; // } // // public void setNexusArtifact(String nexusArtifact) { // this.nexusArtifact = nexusArtifact == null ? null : nexusArtifact.trim(); // } // // public String getReleaseUser() { // return releaseUser; // } // // public void setReleaseUser(String releaseUser) { // this.releaseUser = releaseUser == null ? null : releaseUser.trim(); // } // // public String getReleaseTo() { // return releaseTo; // } // // public void setReleaseTo(String releaseTo) { // this.releaseTo = releaseTo == null ? null : releaseTo.trim(); // } // // public Boolean getIsAudit() { // return isAudit; // } // // public void setIsAudit(Boolean isAudit) { // this.isAudit = isAudit; // } // // public Date getCreateAt() { // return createAt; // } // // public void setCreateAt(Date createAt) { // this.createAt = createAt; // } // // public Date getUpdateAt() { // return updateAt; // } // // public void setUpdateAt(Date updateAt) { // this.updateAt = updateAt; // } // // public String getCreateBy() { // return createBy; // } // // public void setCreateBy(String createBy) { // this.createBy = createBy == null ? null : createBy.trim(); // } // // public String getUpdateBy() { // return updateBy; // } // // public void setUpdateBy(String updateBy) { // this.updateBy = updateBy == null ? null : updateBy.trim(); // } // // public Integer getEnv() { // return env; // } // // public void setEnv(Integer env) { // this.env = env; // } // // public Integer getPlus() { // return plus; // } // // public void setPlus(Integer plus) { // this.plus = plus; // } // // } // // Path: src/main/java/com/appleframework/deploy/model/TaskSo.java // public class TaskSo implements Serializable { // // private static final long serialVersionUID = -2819301403023915774L; // // private String title; // private Integer projectId; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public Integer getProjectId() { // return projectId; // } // // public void setProjectId(Integer projectId) { // this.projectId = projectId; // } // // } // Path: src/main/java/com/appleframework/deploy/dao/extend/TaskExtendMapper.java import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import com.appleframework.deploy.entity.Project; import com.appleframework.deploy.model.TaskSo; import com.appleframework.model.page.Pagination; package com.appleframework.deploy.dao.extend; @Repository public interface TaskExtendMapper {
List<Project> selectByPage(@Param("page") Pagination page, @Param("so") TaskSo so);
xushaomin/apple-deploy
src/main/java/com/appleframework/deploy/dao/extend/TaskExtendMapper.java
// Path: src/main/java/com/appleframework/deploy/entity/Project.java // public class Project implements Serializable { // // private Integer id; // // private String name; // // private Integer type; // // private Integer env; // // private Integer plus; // // private Integer status; // // private String version; // // private String nexusUrl; // // private String nexusGroup; // // private String nexusArtifact; // // private String releaseUser; // // private String releaseTo; // // private Boolean isAudit; // // private Date createAt; // // private Date updateAt; // // private String createBy; // // private String updateBy; // // private static final long serialVersionUID = 1L; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name == null ? null : name.trim(); // } // // public Integer getType() { // return type; // } // // public void setType(Integer type) { // this.type = type; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version == null ? null : version.trim(); // } // // public String getNexusUrl() { // return nexusUrl; // } // // public void setNexusUrl(String nexusUrl) { // this.nexusUrl = nexusUrl == null ? null : nexusUrl.trim(); // } // // public String getNexusGroup() { // return nexusGroup; // } // // public void setNexusGroup(String nexusGroup) { // this.nexusGroup = nexusGroup == null ? null : nexusGroup.trim(); // } // // public String getNexusArtifact() { // return nexusArtifact; // } // // public void setNexusArtifact(String nexusArtifact) { // this.nexusArtifact = nexusArtifact == null ? null : nexusArtifact.trim(); // } // // public String getReleaseUser() { // return releaseUser; // } // // public void setReleaseUser(String releaseUser) { // this.releaseUser = releaseUser == null ? null : releaseUser.trim(); // } // // public String getReleaseTo() { // return releaseTo; // } // // public void setReleaseTo(String releaseTo) { // this.releaseTo = releaseTo == null ? null : releaseTo.trim(); // } // // public Boolean getIsAudit() { // return isAudit; // } // // public void setIsAudit(Boolean isAudit) { // this.isAudit = isAudit; // } // // public Date getCreateAt() { // return createAt; // } // // public void setCreateAt(Date createAt) { // this.createAt = createAt; // } // // public Date getUpdateAt() { // return updateAt; // } // // public void setUpdateAt(Date updateAt) { // this.updateAt = updateAt; // } // // public String getCreateBy() { // return createBy; // } // // public void setCreateBy(String createBy) { // this.createBy = createBy == null ? null : createBy.trim(); // } // // public String getUpdateBy() { // return updateBy; // } // // public void setUpdateBy(String updateBy) { // this.updateBy = updateBy == null ? null : updateBy.trim(); // } // // public Integer getEnv() { // return env; // } // // public void setEnv(Integer env) { // this.env = env; // } // // public Integer getPlus() { // return plus; // } // // public void setPlus(Integer plus) { // this.plus = plus; // } // // } // // Path: src/main/java/com/appleframework/deploy/model/TaskSo.java // public class TaskSo implements Serializable { // // private static final long serialVersionUID = -2819301403023915774L; // // private String title; // private Integer projectId; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public Integer getProjectId() { // return projectId; // } // // public void setProjectId(Integer projectId) { // this.projectId = projectId; // } // // }
import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import com.appleframework.deploy.entity.Project; import com.appleframework.deploy.model.TaskSo; import com.appleframework.model.page.Pagination;
package com.appleframework.deploy.dao.extend; @Repository public interface TaskExtendMapper {
// Path: src/main/java/com/appleframework/deploy/entity/Project.java // public class Project implements Serializable { // // private Integer id; // // private String name; // // private Integer type; // // private Integer env; // // private Integer plus; // // private Integer status; // // private String version; // // private String nexusUrl; // // private String nexusGroup; // // private String nexusArtifact; // // private String releaseUser; // // private String releaseTo; // // private Boolean isAudit; // // private Date createAt; // // private Date updateAt; // // private String createBy; // // private String updateBy; // // private static final long serialVersionUID = 1L; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name == null ? null : name.trim(); // } // // public Integer getType() { // return type; // } // // public void setType(Integer type) { // this.type = type; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version == null ? null : version.trim(); // } // // public String getNexusUrl() { // return nexusUrl; // } // // public void setNexusUrl(String nexusUrl) { // this.nexusUrl = nexusUrl == null ? null : nexusUrl.trim(); // } // // public String getNexusGroup() { // return nexusGroup; // } // // public void setNexusGroup(String nexusGroup) { // this.nexusGroup = nexusGroup == null ? null : nexusGroup.trim(); // } // // public String getNexusArtifact() { // return nexusArtifact; // } // // public void setNexusArtifact(String nexusArtifact) { // this.nexusArtifact = nexusArtifact == null ? null : nexusArtifact.trim(); // } // // public String getReleaseUser() { // return releaseUser; // } // // public void setReleaseUser(String releaseUser) { // this.releaseUser = releaseUser == null ? null : releaseUser.trim(); // } // // public String getReleaseTo() { // return releaseTo; // } // // public void setReleaseTo(String releaseTo) { // this.releaseTo = releaseTo == null ? null : releaseTo.trim(); // } // // public Boolean getIsAudit() { // return isAudit; // } // // public void setIsAudit(Boolean isAudit) { // this.isAudit = isAudit; // } // // public Date getCreateAt() { // return createAt; // } // // public void setCreateAt(Date createAt) { // this.createAt = createAt; // } // // public Date getUpdateAt() { // return updateAt; // } // // public void setUpdateAt(Date updateAt) { // this.updateAt = updateAt; // } // // public String getCreateBy() { // return createBy; // } // // public void setCreateBy(String createBy) { // this.createBy = createBy == null ? null : createBy.trim(); // } // // public String getUpdateBy() { // return updateBy; // } // // public void setUpdateBy(String updateBy) { // this.updateBy = updateBy == null ? null : updateBy.trim(); // } // // public Integer getEnv() { // return env; // } // // public void setEnv(Integer env) { // this.env = env; // } // // public Integer getPlus() { // return plus; // } // // public void setPlus(Integer plus) { // this.plus = plus; // } // // } // // Path: src/main/java/com/appleframework/deploy/model/TaskSo.java // public class TaskSo implements Serializable { // // private static final long serialVersionUID = -2819301403023915774L; // // private String title; // private Integer projectId; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public Integer getProjectId() { // return projectId; // } // // public void setProjectId(Integer projectId) { // this.projectId = projectId; // } // // } // Path: src/main/java/com/appleframework/deploy/dao/extend/TaskExtendMapper.java import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import com.appleframework.deploy.entity.Project; import com.appleframework.deploy.model.TaskSo; import com.appleframework.model.page.Pagination; package com.appleframework.deploy.dao.extend; @Repository public interface TaskExtendMapper {
List<Project> selectByPage(@Param("page") Pagination page, @Param("so") TaskSo so);
xushaomin/apple-deploy
src/main/java/com/appleframework/deploy/dao/extend/ProjectExtendMapper.java
// Path: src/main/java/com/appleframework/deploy/entity/Project.java // public class Project implements Serializable { // // private Integer id; // // private String name; // // private Integer type; // // private Integer env; // // private Integer plus; // // private Integer status; // // private String version; // // private String nexusUrl; // // private String nexusGroup; // // private String nexusArtifact; // // private String releaseUser; // // private String releaseTo; // // private Boolean isAudit; // // private Date createAt; // // private Date updateAt; // // private String createBy; // // private String updateBy; // // private static final long serialVersionUID = 1L; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name == null ? null : name.trim(); // } // // public Integer getType() { // return type; // } // // public void setType(Integer type) { // this.type = type; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version == null ? null : version.trim(); // } // // public String getNexusUrl() { // return nexusUrl; // } // // public void setNexusUrl(String nexusUrl) { // this.nexusUrl = nexusUrl == null ? null : nexusUrl.trim(); // } // // public String getNexusGroup() { // return nexusGroup; // } // // public void setNexusGroup(String nexusGroup) { // this.nexusGroup = nexusGroup == null ? null : nexusGroup.trim(); // } // // public String getNexusArtifact() { // return nexusArtifact; // } // // public void setNexusArtifact(String nexusArtifact) { // this.nexusArtifact = nexusArtifact == null ? null : nexusArtifact.trim(); // } // // public String getReleaseUser() { // return releaseUser; // } // // public void setReleaseUser(String releaseUser) { // this.releaseUser = releaseUser == null ? null : releaseUser.trim(); // } // // public String getReleaseTo() { // return releaseTo; // } // // public void setReleaseTo(String releaseTo) { // this.releaseTo = releaseTo == null ? null : releaseTo.trim(); // } // // public Boolean getIsAudit() { // return isAudit; // } // // public void setIsAudit(Boolean isAudit) { // this.isAudit = isAudit; // } // // public Date getCreateAt() { // return createAt; // } // // public void setCreateAt(Date createAt) { // this.createAt = createAt; // } // // public Date getUpdateAt() { // return updateAt; // } // // public void setUpdateAt(Date updateAt) { // this.updateAt = updateAt; // } // // public String getCreateBy() { // return createBy; // } // // public void setCreateBy(String createBy) { // this.createBy = createBy == null ? null : createBy.trim(); // } // // public String getUpdateBy() { // return updateBy; // } // // public void setUpdateBy(String updateBy) { // this.updateBy = updateBy == null ? null : updateBy.trim(); // } // // public Integer getEnv() { // return env; // } // // public void setEnv(Integer env) { // this.env = env; // } // // public Integer getPlus() { // return plus; // } // // public void setPlus(Integer plus) { // this.plus = plus; // } // // } // // Path: src/main/java/com/appleframework/deploy/model/ProjectSo.java // public class ProjectSo implements Serializable { // // private static final long serialVersionUID = -2819301403023915774L; // // private String name; // private Integer env; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getEnv() { // return env; // } // // public void setEnv(Integer env) { // this.env = env; // } // // }
import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import com.appleframework.deploy.entity.Project; import com.appleframework.deploy.model.ProjectSo; import com.appleframework.model.page.Pagination;
package com.appleframework.deploy.dao.extend; @Repository public interface ProjectExtendMapper {
// Path: src/main/java/com/appleframework/deploy/entity/Project.java // public class Project implements Serializable { // // private Integer id; // // private String name; // // private Integer type; // // private Integer env; // // private Integer plus; // // private Integer status; // // private String version; // // private String nexusUrl; // // private String nexusGroup; // // private String nexusArtifact; // // private String releaseUser; // // private String releaseTo; // // private Boolean isAudit; // // private Date createAt; // // private Date updateAt; // // private String createBy; // // private String updateBy; // // private static final long serialVersionUID = 1L; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name == null ? null : name.trim(); // } // // public Integer getType() { // return type; // } // // public void setType(Integer type) { // this.type = type; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version == null ? null : version.trim(); // } // // public String getNexusUrl() { // return nexusUrl; // } // // public void setNexusUrl(String nexusUrl) { // this.nexusUrl = nexusUrl == null ? null : nexusUrl.trim(); // } // // public String getNexusGroup() { // return nexusGroup; // } // // public void setNexusGroup(String nexusGroup) { // this.nexusGroup = nexusGroup == null ? null : nexusGroup.trim(); // } // // public String getNexusArtifact() { // return nexusArtifact; // } // // public void setNexusArtifact(String nexusArtifact) { // this.nexusArtifact = nexusArtifact == null ? null : nexusArtifact.trim(); // } // // public String getReleaseUser() { // return releaseUser; // } // // public void setReleaseUser(String releaseUser) { // this.releaseUser = releaseUser == null ? null : releaseUser.trim(); // } // // public String getReleaseTo() { // return releaseTo; // } // // public void setReleaseTo(String releaseTo) { // this.releaseTo = releaseTo == null ? null : releaseTo.trim(); // } // // public Boolean getIsAudit() { // return isAudit; // } // // public void setIsAudit(Boolean isAudit) { // this.isAudit = isAudit; // } // // public Date getCreateAt() { // return createAt; // } // // public void setCreateAt(Date createAt) { // this.createAt = createAt; // } // // public Date getUpdateAt() { // return updateAt; // } // // public void setUpdateAt(Date updateAt) { // this.updateAt = updateAt; // } // // public String getCreateBy() { // return createBy; // } // // public void setCreateBy(String createBy) { // this.createBy = createBy == null ? null : createBy.trim(); // } // // public String getUpdateBy() { // return updateBy; // } // // public void setUpdateBy(String updateBy) { // this.updateBy = updateBy == null ? null : updateBy.trim(); // } // // public Integer getEnv() { // return env; // } // // public void setEnv(Integer env) { // this.env = env; // } // // public Integer getPlus() { // return plus; // } // // public void setPlus(Integer plus) { // this.plus = plus; // } // // } // // Path: src/main/java/com/appleframework/deploy/model/ProjectSo.java // public class ProjectSo implements Serializable { // // private static final long serialVersionUID = -2819301403023915774L; // // private String name; // private Integer env; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getEnv() { // return env; // } // // public void setEnv(Integer env) { // this.env = env; // } // // } // Path: src/main/java/com/appleframework/deploy/dao/extend/ProjectExtendMapper.java import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import com.appleframework.deploy.entity.Project; import com.appleframework.deploy.model.ProjectSo; import com.appleframework.model.page.Pagination; package com.appleframework.deploy.dao.extend; @Repository public interface ProjectExtendMapper {
List<Project> selectByPage(@Param("page") Pagination page, @Param("so") ProjectSo so);
xushaomin/apple-deploy
src/main/java/com/appleframework/deploy/dao/extend/ProjectExtendMapper.java
// Path: src/main/java/com/appleframework/deploy/entity/Project.java // public class Project implements Serializable { // // private Integer id; // // private String name; // // private Integer type; // // private Integer env; // // private Integer plus; // // private Integer status; // // private String version; // // private String nexusUrl; // // private String nexusGroup; // // private String nexusArtifact; // // private String releaseUser; // // private String releaseTo; // // private Boolean isAudit; // // private Date createAt; // // private Date updateAt; // // private String createBy; // // private String updateBy; // // private static final long serialVersionUID = 1L; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name == null ? null : name.trim(); // } // // public Integer getType() { // return type; // } // // public void setType(Integer type) { // this.type = type; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version == null ? null : version.trim(); // } // // public String getNexusUrl() { // return nexusUrl; // } // // public void setNexusUrl(String nexusUrl) { // this.nexusUrl = nexusUrl == null ? null : nexusUrl.trim(); // } // // public String getNexusGroup() { // return nexusGroup; // } // // public void setNexusGroup(String nexusGroup) { // this.nexusGroup = nexusGroup == null ? null : nexusGroup.trim(); // } // // public String getNexusArtifact() { // return nexusArtifact; // } // // public void setNexusArtifact(String nexusArtifact) { // this.nexusArtifact = nexusArtifact == null ? null : nexusArtifact.trim(); // } // // public String getReleaseUser() { // return releaseUser; // } // // public void setReleaseUser(String releaseUser) { // this.releaseUser = releaseUser == null ? null : releaseUser.trim(); // } // // public String getReleaseTo() { // return releaseTo; // } // // public void setReleaseTo(String releaseTo) { // this.releaseTo = releaseTo == null ? null : releaseTo.trim(); // } // // public Boolean getIsAudit() { // return isAudit; // } // // public void setIsAudit(Boolean isAudit) { // this.isAudit = isAudit; // } // // public Date getCreateAt() { // return createAt; // } // // public void setCreateAt(Date createAt) { // this.createAt = createAt; // } // // public Date getUpdateAt() { // return updateAt; // } // // public void setUpdateAt(Date updateAt) { // this.updateAt = updateAt; // } // // public String getCreateBy() { // return createBy; // } // // public void setCreateBy(String createBy) { // this.createBy = createBy == null ? null : createBy.trim(); // } // // public String getUpdateBy() { // return updateBy; // } // // public void setUpdateBy(String updateBy) { // this.updateBy = updateBy == null ? null : updateBy.trim(); // } // // public Integer getEnv() { // return env; // } // // public void setEnv(Integer env) { // this.env = env; // } // // public Integer getPlus() { // return plus; // } // // public void setPlus(Integer plus) { // this.plus = plus; // } // // } // // Path: src/main/java/com/appleframework/deploy/model/ProjectSo.java // public class ProjectSo implements Serializable { // // private static final long serialVersionUID = -2819301403023915774L; // // private String name; // private Integer env; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getEnv() { // return env; // } // // public void setEnv(Integer env) { // this.env = env; // } // // }
import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import com.appleframework.deploy.entity.Project; import com.appleframework.deploy.model.ProjectSo; import com.appleframework.model.page.Pagination;
package com.appleframework.deploy.dao.extend; @Repository public interface ProjectExtendMapper {
// Path: src/main/java/com/appleframework/deploy/entity/Project.java // public class Project implements Serializable { // // private Integer id; // // private String name; // // private Integer type; // // private Integer env; // // private Integer plus; // // private Integer status; // // private String version; // // private String nexusUrl; // // private String nexusGroup; // // private String nexusArtifact; // // private String releaseUser; // // private String releaseTo; // // private Boolean isAudit; // // private Date createAt; // // private Date updateAt; // // private String createBy; // // private String updateBy; // // private static final long serialVersionUID = 1L; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name == null ? null : name.trim(); // } // // public Integer getType() { // return type; // } // // public void setType(Integer type) { // this.type = type; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version == null ? null : version.trim(); // } // // public String getNexusUrl() { // return nexusUrl; // } // // public void setNexusUrl(String nexusUrl) { // this.nexusUrl = nexusUrl == null ? null : nexusUrl.trim(); // } // // public String getNexusGroup() { // return nexusGroup; // } // // public void setNexusGroup(String nexusGroup) { // this.nexusGroup = nexusGroup == null ? null : nexusGroup.trim(); // } // // public String getNexusArtifact() { // return nexusArtifact; // } // // public void setNexusArtifact(String nexusArtifact) { // this.nexusArtifact = nexusArtifact == null ? null : nexusArtifact.trim(); // } // // public String getReleaseUser() { // return releaseUser; // } // // public void setReleaseUser(String releaseUser) { // this.releaseUser = releaseUser == null ? null : releaseUser.trim(); // } // // public String getReleaseTo() { // return releaseTo; // } // // public void setReleaseTo(String releaseTo) { // this.releaseTo = releaseTo == null ? null : releaseTo.trim(); // } // // public Boolean getIsAudit() { // return isAudit; // } // // public void setIsAudit(Boolean isAudit) { // this.isAudit = isAudit; // } // // public Date getCreateAt() { // return createAt; // } // // public void setCreateAt(Date createAt) { // this.createAt = createAt; // } // // public Date getUpdateAt() { // return updateAt; // } // // public void setUpdateAt(Date updateAt) { // this.updateAt = updateAt; // } // // public String getCreateBy() { // return createBy; // } // // public void setCreateBy(String createBy) { // this.createBy = createBy == null ? null : createBy.trim(); // } // // public String getUpdateBy() { // return updateBy; // } // // public void setUpdateBy(String updateBy) { // this.updateBy = updateBy == null ? null : updateBy.trim(); // } // // public Integer getEnv() { // return env; // } // // public void setEnv(Integer env) { // this.env = env; // } // // public Integer getPlus() { // return plus; // } // // public void setPlus(Integer plus) { // this.plus = plus; // } // // } // // Path: src/main/java/com/appleframework/deploy/model/ProjectSo.java // public class ProjectSo implements Serializable { // // private static final long serialVersionUID = -2819301403023915774L; // // private String name; // private Integer env; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getEnv() { // return env; // } // // public void setEnv(Integer env) { // this.env = env; // } // // } // Path: src/main/java/com/appleframework/deploy/dao/extend/ProjectExtendMapper.java import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import com.appleframework.deploy.entity.Project; import com.appleframework.deploy.model.ProjectSo; import com.appleframework.model.page.Pagination; package com.appleframework.deploy.dao.extend; @Repository public interface ProjectExtendMapper {
List<Project> selectByPage(@Param("page") Pagination page, @Param("so") ProjectSo so);
xushaomin/apple-deploy
src/main/java/com/appleframework/deploy/service/TaskService.java
// Path: src/main/java/com/appleframework/deploy/entity/Task.java // public class Task implements Serializable { // // private Integer id; // // private Integer projectId; // // private String projectName; // // private String hosts; // // private String title; // // private Integer action; // // private Integer status; // // private String version; // // private String exVersion; // // private Date createAt; // // private Date updateAt; // // private String createBy; // // private String updateBy; // // private static final long serialVersionUID = 1L; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getProjectId() { // return projectId; // } // // public void setProjectId(Integer projectId) { // this.projectId = projectId; // } // // public String getProjectName() { // return projectName; // } // // public void setProjectName(String projectName) { // this.projectName = projectName == null ? null : projectName.trim(); // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title == null ? null : title.trim(); // } // // public Integer getAction() { // return action; // } // // public void setAction(Integer action) { // this.action = action; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version == null ? null : version.trim(); // } // // public String getExVersion() { // return exVersion; // } // // public void setExVersion(String exVersion) { // this.exVersion = exVersion == null ? null : exVersion.trim(); // } // // public Date getCreateAt() { // return createAt; // } // // public void setCreateAt(Date createAt) { // this.createAt = createAt; // } // // public Date getUpdateAt() { // return updateAt; // } // // public void setUpdateAt(Date updateAt) { // this.updateAt = updateAt; // } // // public String getCreateBy() { // return createBy; // } // // public void setCreateBy(String createBy) { // this.createBy = createBy == null ? null : createBy.trim(); // } // // public String getUpdateBy() { // return updateBy; // } // // public void setUpdateBy(String updateBy) { // this.updateBy = updateBy == null ? null : updateBy.trim(); // } // // public String getHosts() { // return hosts; // } // // public void setHosts(String hosts) { // this.hosts = hosts; // } // // } // // Path: src/main/java/com/appleframework/deploy/model/TaskSo.java // public class TaskSo implements Serializable { // // private static final long serialVersionUID = -2819301403023915774L; // // private String title; // private Integer projectId; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public Integer getProjectId() { // return projectId; // } // // public void setProjectId(Integer projectId) { // this.projectId = projectId; // } // // }
import com.appleframework.deploy.entity.Task; import com.appleframework.deploy.model.TaskSo; import com.appleframework.exception.AppleException; import com.appleframework.model.page.Pagination;
package com.appleframework.deploy.service; public interface TaskService { public Integer save(Task record) throws AppleException; public Integer update(Task record) throws AppleException; public Integer delete(Integer id) throws AppleException; public Task get(Integer id);
// Path: src/main/java/com/appleframework/deploy/entity/Task.java // public class Task implements Serializable { // // private Integer id; // // private Integer projectId; // // private String projectName; // // private String hosts; // // private String title; // // private Integer action; // // private Integer status; // // private String version; // // private String exVersion; // // private Date createAt; // // private Date updateAt; // // private String createBy; // // private String updateBy; // // private static final long serialVersionUID = 1L; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getProjectId() { // return projectId; // } // // public void setProjectId(Integer projectId) { // this.projectId = projectId; // } // // public String getProjectName() { // return projectName; // } // // public void setProjectName(String projectName) { // this.projectName = projectName == null ? null : projectName.trim(); // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title == null ? null : title.trim(); // } // // public Integer getAction() { // return action; // } // // public void setAction(Integer action) { // this.action = action; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version == null ? null : version.trim(); // } // // public String getExVersion() { // return exVersion; // } // // public void setExVersion(String exVersion) { // this.exVersion = exVersion == null ? null : exVersion.trim(); // } // // public Date getCreateAt() { // return createAt; // } // // public void setCreateAt(Date createAt) { // this.createAt = createAt; // } // // public Date getUpdateAt() { // return updateAt; // } // // public void setUpdateAt(Date updateAt) { // this.updateAt = updateAt; // } // // public String getCreateBy() { // return createBy; // } // // public void setCreateBy(String createBy) { // this.createBy = createBy == null ? null : createBy.trim(); // } // // public String getUpdateBy() { // return updateBy; // } // // public void setUpdateBy(String updateBy) { // this.updateBy = updateBy == null ? null : updateBy.trim(); // } // // public String getHosts() { // return hosts; // } // // public void setHosts(String hosts) { // this.hosts = hosts; // } // // } // // Path: src/main/java/com/appleframework/deploy/model/TaskSo.java // public class TaskSo implements Serializable { // // private static final long serialVersionUID = -2819301403023915774L; // // private String title; // private Integer projectId; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public Integer getProjectId() { // return projectId; // } // // public void setProjectId(Integer projectId) { // this.projectId = projectId; // } // // } // Path: src/main/java/com/appleframework/deploy/service/TaskService.java import com.appleframework.deploy.entity.Task; import com.appleframework.deploy.model.TaskSo; import com.appleframework.exception.AppleException; import com.appleframework.model.page.Pagination; package com.appleframework.deploy.service; public interface TaskService { public Integer save(Task record) throws AppleException; public Integer update(Task record) throws AppleException; public Integer delete(Integer id) throws AppleException; public Task get(Integer id);
public Pagination findPage(Pagination page, TaskSo so);
xushaomin/apple-deploy
src/main/java/com/appleframework/deploy/dao/RecordMapper.java
// Path: src/main/java/com/appleframework/deploy/entity/Record.java // public class Record implements Serializable { // private Long id; // // private Integer taskId; // // private Integer status; // // private Integer action; // // private Integer duration; // // private Date createAt; // // private static final long serialVersionUID = 1L; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Integer getTaskId() { // return taskId; // } // // public void setTaskId(Integer taskId) { // this.taskId = taskId; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public Integer getAction() { // return action; // } // // public void setAction(Integer action) { // this.action = action; // } // // public Integer getDuration() { // return duration; // } // // public void setDuration(Integer duration) { // this.duration = duration; // } // // public Date getCreateAt() { // return createAt; // } // // public void setCreateAt(Date createAt) { // this.createAt = createAt; // } // } // // Path: src/main/java/com/appleframework/deploy/entity/RecordWithBLOBs.java // public class RecordWithBLOBs extends Record implements Serializable { // private String command; // // private String memo; // // private static final long serialVersionUID = 1L; // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command == null ? null : command.trim(); // } // // public String getMemo() { // return memo; // } // // public void setMemo(String memo) { // this.memo = memo == null ? null : memo.trim(); // } // }
import org.springframework.stereotype.Repository; import com.appleframework.deploy.entity.Record; import com.appleframework.deploy.entity.RecordWithBLOBs;
package com.appleframework.deploy.dao; @Repository public interface RecordMapper { int deleteByPrimaryKey(Long id);
// Path: src/main/java/com/appleframework/deploy/entity/Record.java // public class Record implements Serializable { // private Long id; // // private Integer taskId; // // private Integer status; // // private Integer action; // // private Integer duration; // // private Date createAt; // // private static final long serialVersionUID = 1L; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Integer getTaskId() { // return taskId; // } // // public void setTaskId(Integer taskId) { // this.taskId = taskId; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public Integer getAction() { // return action; // } // // public void setAction(Integer action) { // this.action = action; // } // // public Integer getDuration() { // return duration; // } // // public void setDuration(Integer duration) { // this.duration = duration; // } // // public Date getCreateAt() { // return createAt; // } // // public void setCreateAt(Date createAt) { // this.createAt = createAt; // } // } // // Path: src/main/java/com/appleframework/deploy/entity/RecordWithBLOBs.java // public class RecordWithBLOBs extends Record implements Serializable { // private String command; // // private String memo; // // private static final long serialVersionUID = 1L; // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command == null ? null : command.trim(); // } // // public String getMemo() { // return memo; // } // // public void setMemo(String memo) { // this.memo = memo == null ? null : memo.trim(); // } // } // Path: src/main/java/com/appleframework/deploy/dao/RecordMapper.java import org.springframework.stereotype.Repository; import com.appleframework.deploy.entity.Record; import com.appleframework.deploy.entity.RecordWithBLOBs; package com.appleframework.deploy.dao; @Repository public interface RecordMapper { int deleteByPrimaryKey(Long id);
int insert(RecordWithBLOBs record);
xushaomin/apple-deploy
src/main/java/com/appleframework/deploy/dao/RecordMapper.java
// Path: src/main/java/com/appleframework/deploy/entity/Record.java // public class Record implements Serializable { // private Long id; // // private Integer taskId; // // private Integer status; // // private Integer action; // // private Integer duration; // // private Date createAt; // // private static final long serialVersionUID = 1L; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Integer getTaskId() { // return taskId; // } // // public void setTaskId(Integer taskId) { // this.taskId = taskId; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public Integer getAction() { // return action; // } // // public void setAction(Integer action) { // this.action = action; // } // // public Integer getDuration() { // return duration; // } // // public void setDuration(Integer duration) { // this.duration = duration; // } // // public Date getCreateAt() { // return createAt; // } // // public void setCreateAt(Date createAt) { // this.createAt = createAt; // } // } // // Path: src/main/java/com/appleframework/deploy/entity/RecordWithBLOBs.java // public class RecordWithBLOBs extends Record implements Serializable { // private String command; // // private String memo; // // private static final long serialVersionUID = 1L; // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command == null ? null : command.trim(); // } // // public String getMemo() { // return memo; // } // // public void setMemo(String memo) { // this.memo = memo == null ? null : memo.trim(); // } // }
import org.springframework.stereotype.Repository; import com.appleframework.deploy.entity.Record; import com.appleframework.deploy.entity.RecordWithBLOBs;
package com.appleframework.deploy.dao; @Repository public interface RecordMapper { int deleteByPrimaryKey(Long id); int insert(RecordWithBLOBs record); int insertSelective(RecordWithBLOBs record); RecordWithBLOBs selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(RecordWithBLOBs record); int updateByPrimaryKeyWithBLOBs(RecordWithBLOBs record);
// Path: src/main/java/com/appleframework/deploy/entity/Record.java // public class Record implements Serializable { // private Long id; // // private Integer taskId; // // private Integer status; // // private Integer action; // // private Integer duration; // // private Date createAt; // // private static final long serialVersionUID = 1L; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Integer getTaskId() { // return taskId; // } // // public void setTaskId(Integer taskId) { // this.taskId = taskId; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public Integer getAction() { // return action; // } // // public void setAction(Integer action) { // this.action = action; // } // // public Integer getDuration() { // return duration; // } // // public void setDuration(Integer duration) { // this.duration = duration; // } // // public Date getCreateAt() { // return createAt; // } // // public void setCreateAt(Date createAt) { // this.createAt = createAt; // } // } // // Path: src/main/java/com/appleframework/deploy/entity/RecordWithBLOBs.java // public class RecordWithBLOBs extends Record implements Serializable { // private String command; // // private String memo; // // private static final long serialVersionUID = 1L; // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command == null ? null : command.trim(); // } // // public String getMemo() { // return memo; // } // // public void setMemo(String memo) { // this.memo = memo == null ? null : memo.trim(); // } // } // Path: src/main/java/com/appleframework/deploy/dao/RecordMapper.java import org.springframework.stereotype.Repository; import com.appleframework.deploy.entity.Record; import com.appleframework.deploy.entity.RecordWithBLOBs; package com.appleframework.deploy.dao; @Repository public interface RecordMapper { int deleteByPrimaryKey(Long id); int insert(RecordWithBLOBs record); int insertSelective(RecordWithBLOBs record); RecordWithBLOBs selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(RecordWithBLOBs record); int updateByPrimaryKeyWithBLOBs(RecordWithBLOBs record);
int updateByPrimaryKey(Record record);
Mpmart08/MusicPlayer
src/app/musicplayer/model/Artist.java
// Path: src/app/musicplayer/util/Resources.java // public final class Resources { // // public static final String FXML = "/app/musicplayer/view/"; // public static final String IMG = "/app/musicplayer/util/img/"; // public static final String CSS = "/app/musicplayer/util/css/"; // public static String JAR; // public static final String APIBASE = "http://ws.audioscrobbler.com/2.0/?"; // public static final String APIKEY = "57ee3318536b23ee81d6b27e36997cde"; // // private Resources() {} // }
import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import app.musicplayer.util.Resources; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.image.Image;
package app.musicplayer.model; /** * Model class for an Artist * */ public final class Artist implements Comparable<Artist> { private String title; private ArrayList<Album> albums; private Image artistImage; private SimpleObjectProperty<Image> artistImageProperty; /** * Constructor for the Artist class. * Creates an artist object and obtains the artist artwork. * * @param title Artist name * @param albums List of artist albums */ public Artist(String title, ArrayList<Album> albums) { this.title = title; this.albums = albums; this.artistImageProperty = new SimpleObjectProperty<>(getArtistImage()); } /** * Gets the artist title. * @return artist title */ public String getTitle() { return this.title; } /** * Gets array list of artist albums * @return artist albums */ public ArrayList<Album> getAlbums() { return new ArrayList<>(this.albums); } public ObjectProperty<Image> artistImageProperty() { return this.artistImageProperty; } /** * Gets images for artists * @return artist image */ public Image getArtistImage() { if (artistImage == null) { try {
// Path: src/app/musicplayer/util/Resources.java // public final class Resources { // // public static final String FXML = "/app/musicplayer/view/"; // public static final String IMG = "/app/musicplayer/util/img/"; // public static final String CSS = "/app/musicplayer/util/css/"; // public static String JAR; // public static final String APIBASE = "http://ws.audioscrobbler.com/2.0/?"; // public static final String APIKEY = "57ee3318536b23ee81d6b27e36997cde"; // // private Resources() {} // } // Path: src/app/musicplayer/model/Artist.java import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import app.musicplayer.util.Resources; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.image.Image; package app.musicplayer.model; /** * Model class for an Artist * */ public final class Artist implements Comparable<Artist> { private String title; private ArrayList<Album> albums; private Image artistImage; private SimpleObjectProperty<Image> artistImageProperty; /** * Constructor for the Artist class. * Creates an artist object and obtains the artist artwork. * * @param title Artist name * @param albums List of artist albums */ public Artist(String title, ArrayList<Album> albums) { this.title = title; this.albums = albums; this.artistImageProperty = new SimpleObjectProperty<>(getArtistImage()); } /** * Gets the artist title. * @return artist title */ public String getTitle() { return this.title; } /** * Gets array list of artist albums * @return artist albums */ public ArrayList<Album> getAlbums() { return new ArrayList<>(this.albums); } public ObjectProperty<Image> artistImageProperty() { return this.artistImageProperty; } /** * Gets images for artists * @return artist image */ public Image getArtistImage() { if (artistImage == null) { try {
File file = new File(Resources.JAR + "/img/" + this.title + ".jpg");
Mpmart08/MusicPlayer
src/app/musicplayer/model/Song.java
// Path: src/app/musicplayer/util/Resources.java // public final class Resources { // // public static final String FXML = "/app/musicplayer/view/"; // public static final String IMG = "/app/musicplayer/util/img/"; // public static final String CSS = "/app/musicplayer/util/css/"; // public static String JAR; // public static final String APIBASE = "http://ws.audioscrobbler.com/2.0/?"; // public static final String APIKEY = "57ee3318536b23ee81d6b27e36997cde"; // // private Resources() {} // }
import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.time.LocalDateTime; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import app.musicplayer.util.Resources; import javafx.beans.property.BooleanProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.scene.image.Image;
public boolean getPlaying() { return this.playing.get(); } public void setPlaying(boolean playing) { this.playing.set(playing); } public BooleanProperty selectedProperty() { return this.selected; } public boolean getSelected() { return this.selected.get(); } public void setSelected(boolean selected) { this.selected.set(selected); } public void played() { this.playCount.set(this.playCount.get() + 1); this.playDate = LocalDateTime.now(); Thread thread = new Thread(() -> { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// Path: src/app/musicplayer/util/Resources.java // public final class Resources { // // public static final String FXML = "/app/musicplayer/view/"; // public static final String IMG = "/app/musicplayer/util/img/"; // public static final String CSS = "/app/musicplayer/util/css/"; // public static String JAR; // public static final String APIBASE = "http://ws.audioscrobbler.com/2.0/?"; // public static final String APIKEY = "57ee3318536b23ee81d6b27e36997cde"; // // private Resources() {} // } // Path: src/app/musicplayer/model/Song.java import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.time.LocalDateTime; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import app.musicplayer.util.Resources; import javafx.beans.property.BooleanProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.scene.image.Image; public boolean getPlaying() { return this.playing.get(); } public void setPlaying(boolean playing) { this.playing.set(playing); } public BooleanProperty selectedProperty() { return this.selected; } public boolean getSelected() { return this.selected.get(); } public void setSelected(boolean selected) { this.selected.set(selected); } public void played() { this.playCount.set(this.playCount.get() + 1); this.playDate = LocalDateTime.now(); Thread thread = new Thread(() -> { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(Resources.JAR + "library.xml");
Mpmart08/MusicPlayer
src/app/musicplayer/model/Album.java
// Path: src/app/musicplayer/util/Resources.java // public final class Resources { // // public static final String FXML = "/app/musicplayer/view/"; // public static final String IMG = "/app/musicplayer/util/img/"; // public static final String CSS = "/app/musicplayer/util/css/"; // public static String JAR; // public static final String APIBASE = "http://ws.audioscrobbler.com/2.0/?"; // public static final String APIKEY = "57ee3318536b23ee81d6b27e36997cde"; // // private Resources() {} // }
import java.awt.Color; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.tag.Tag; import org.jaudiotagger.tag.images.Artwork; import org.jaudiotagger.tag.images.ArtworkFactory; import app.musicplayer.util.Resources; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.image.Image;
* @return album title */ public String getTitle() { return this.title; } public String getArtist() { return this.artist; } public ArrayList<Song> getSongs() { return new ArrayList<>(this.songs); } public ObjectProperty<Image> artworkProperty() { return this.artworkProperty; } public Image getArtwork() { if (this.artwork == null) { try { String location = this.songs.get(0).getLocation(); AudioFile audioFile = AudioFileIO.read(new File(location)); Tag tag = audioFile.getTag(); byte[] bytes = tag.getFirstArtwork().getBinaryData(); ByteArrayInputStream in = new ByteArrayInputStream(bytes); this.artwork = new Image(in, 300, 300, true, true); if (this.artwork.isError()) {
// Path: src/app/musicplayer/util/Resources.java // public final class Resources { // // public static final String FXML = "/app/musicplayer/view/"; // public static final String IMG = "/app/musicplayer/util/img/"; // public static final String CSS = "/app/musicplayer/util/css/"; // public static String JAR; // public static final String APIBASE = "http://ws.audioscrobbler.com/2.0/?"; // public static final String APIKEY = "57ee3318536b23ee81d6b27e36997cde"; // // private Resources() {} // } // Path: src/app/musicplayer/model/Album.java import java.awt.Color; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.tag.Tag; import org.jaudiotagger.tag.images.Artwork; import org.jaudiotagger.tag.images.ArtworkFactory; import app.musicplayer.util.Resources; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.image.Image; * @return album title */ public String getTitle() { return this.title; } public String getArtist() { return this.artist; } public ArrayList<Song> getSongs() { return new ArrayList<>(this.songs); } public ObjectProperty<Image> artworkProperty() { return this.artworkProperty; } public Image getArtwork() { if (this.artwork == null) { try { String location = this.songs.get(0).getLocation(); AudioFile audioFile = AudioFileIO.read(new File(location)); Tag tag = audioFile.getTag(); byte[] bytes = tag.getFirstArtwork().getBinaryData(); ByteArrayInputStream in = new ByteArrayInputStream(bytes); this.artwork = new Image(in, 300, 300, true, true); if (this.artwork.isError()) {
this.artwork = new Image(Resources.IMG + "albumsIcon.png");
Mpmart08/MusicPlayer
src/app/musicplayer/model/Playlist.java
// Path: src/app/musicplayer/util/Resources.java // public final class Resources { // // public static final String FXML = "/app/musicplayer/view/"; // public static final String IMG = "/app/musicplayer/util/img/"; // public static final String CSS = "/app/musicplayer/util/css/"; // public static String JAR; // public static final String APIBASE = "http://ws.audioscrobbler.com/2.0/?"; // public static final String APIKEY = "57ee3318536b23ee81d6b27e36997cde"; // // private Resources() {} // }
import java.io.File; import java.util.ArrayList; import java.util.Iterator; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import app.musicplayer.util.Resources; import javafx.collections.FXCollections; import javafx.collections.ObservableList;
this.id = id; this.title = title; this.songs = null; this.placeholder = placeholder; } public int getId() { return this.id; } public String getTitle() { return this.title; } public String getPlaceholder() { return this.placeholder; } public ObservableList<Song> getSongs() { return FXCollections.observableArrayList(this.songs); } public void addSong(Song song) { if (!songs.contains(song)) { songs.add(song); try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// Path: src/app/musicplayer/util/Resources.java // public final class Resources { // // public static final String FXML = "/app/musicplayer/view/"; // public static final String IMG = "/app/musicplayer/util/img/"; // public static final String CSS = "/app/musicplayer/util/css/"; // public static String JAR; // public static final String APIBASE = "http://ws.audioscrobbler.com/2.0/?"; // public static final String APIKEY = "57ee3318536b23ee81d6b27e36997cde"; // // private Resources() {} // } // Path: src/app/musicplayer/model/Playlist.java import java.io.File; import java.util.ArrayList; import java.util.Iterator; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import app.musicplayer.util.Resources; import javafx.collections.FXCollections; import javafx.collections.ObservableList; this.id = id; this.title = title; this.songs = null; this.placeholder = placeholder; } public int getId() { return this.id; } public String getTitle() { return this.title; } public String getPlaceholder() { return this.placeholder; } public ObservableList<Song> getSongs() { return FXCollections.observableArrayList(this.songs); } public void addSong(Song song) { if (!songs.contains(song)) { songs.add(song); try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(Resources.JAR + "library.xml");
Turbo87/flight-club
core/src/main/java/org/flightclub/CameraMan.java
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // }
import org.flightclub.compat.Color;
/** This code is covered by the GNU General Public License detailed at http://www.gnu.org/copyleft/gpl.html Flight Club docs located at http://www.danb.dircon.co.uk/hg/hg.htm Dan Burton , Nov 2001 */ package org.flightclub; /* todo - seperate into two classes - generic 3d framework camera functionality - XCGame extension of above class */ public class CameraMan { final XCGame app; public final Vector3d lightRay; public float zoom = 1; private float distance = 0; private float[][] matrix; private final int screenWidth; private final int screenHeight; private final float theScale; private Vector3d eye; private Vector3d focus; private static final int BACKGROUND_R = 255; private static final int BACKGROUND_G = 255; private static final int BACKGROUND_B = 255;
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // Path: core/src/main/java/org/flightclub/CameraMan.java import org.flightclub.compat.Color; /** This code is covered by the GNU General Public License detailed at http://www.gnu.org/copyleft/gpl.html Flight Club docs located at http://www.danb.dircon.co.uk/hg/hg.htm Dan Burton , Nov 2001 */ package org.flightclub; /* todo - seperate into two classes - generic 3d framework camera functionality - XCGame extension of above class */ public class CameraMan { final XCGame app; public final Vector3d lightRay; public float zoom = 1; private float distance = 0; private float[][] matrix; private final int screenWidth; private final int screenHeight; private final float theScale; private Vector3d eye; private Vector3d focus; private static final int BACKGROUND_R = 255; private static final int BACKGROUND_G = 255; private static final int BACKGROUND_B = 255;
private static final Color BACKGROUND = new Color(BACKGROUND_R, BACKGROUND_G, BACKGROUND_B);
Turbo87/flight-club
core/src/main/java/org/flightclub/XCGame.java
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // // Path: core/src/main/java/org/flightclub/compat/Font.java // public class Font { // private java.awt.Font f; // // /** // * The plain style constant. // */ // public static final int PLAIN = 0; // // /** // * The bold style constant. This can be combined with the other style // * constants (except PLAIN) for mixed styles. // */ // public static final int BOLD = 1; // // /** // * The italicized style constant. This can be combined with the other // * style constants (except PLAIN) for mixed styles. // */ // public static final int ITALIC = 2; // // public Font(String name, int style, int size) { // this(new java.awt.Font(name, style, size)); // } // // public Font(java.awt.Font f) { // this.f = f; // } // // public java.awt.Font getFont() { // return f; // } // } // // Path: core/src/main/java/org/flightclub/compat/Graphics.java // public interface Graphics { // void setColor(Color color); // void setFont(Font font); // // void drawLine(int x1, int y1, int x2, int y2); // void drawString(String str, int x, int y); // // void fillCircle(int x, int y, int diameter); // void fillPolygon(int[] xPoints, int[] yPoints, int nPoints); // }
import org.flightclub.compat.Color; import org.flightclub.compat.Font; import org.flightclub.compat.Graphics; import java.awt.event.KeyEvent; import java.util.Vector;
cameraMan.move(CameraMan.CAMERA_MOVEMENT_DELTA, 0); return; case KeyEvent.VK_M: cameraMan.move(0, CameraMan.CAMERA_MOVEMENT_DELTA); return; case KeyEvent.VK_N: cameraMan.move(0, -CameraMan.CAMERA_MOVEMENT_DELTA); return; case KeyEvent.VK_1: cameraMan.setMode(CameraMan.Mode.SELF); return; case KeyEvent.VK_2: cameraMan.setMode(CameraMan.Mode.GAGGLE); return; case KeyEvent.VK_3: cameraMan.setMode(CameraMan.Mode.PLAN); return; case KeyEvent.VK_4: cameraMan.setMode(CameraMan.Mode.TILE); return; default: } } @Override public void keyReleased(KeyEvent e) { }
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // // Path: core/src/main/java/org/flightclub/compat/Font.java // public class Font { // private java.awt.Font f; // // /** // * The plain style constant. // */ // public static final int PLAIN = 0; // // /** // * The bold style constant. This can be combined with the other style // * constants (except PLAIN) for mixed styles. // */ // public static final int BOLD = 1; // // /** // * The italicized style constant. This can be combined with the other // * style constants (except PLAIN) for mixed styles. // */ // public static final int ITALIC = 2; // // public Font(String name, int style, int size) { // this(new java.awt.Font(name, style, size)); // } // // public Font(java.awt.Font f) { // this.f = f; // } // // public java.awt.Font getFont() { // return f; // } // } // // Path: core/src/main/java/org/flightclub/compat/Graphics.java // public interface Graphics { // void setColor(Color color); // void setFont(Font font); // // void drawLine(int x1, int y1, int x2, int y2); // void drawString(String str, int x, int y); // // void fillCircle(int x, int y, int diameter); // void fillPolygon(int[] xPoints, int[] yPoints, int nPoints); // } // Path: core/src/main/java/org/flightclub/XCGame.java import org.flightclub.compat.Color; import org.flightclub.compat.Font; import org.flightclub.compat.Graphics; import java.awt.event.KeyEvent; import java.util.Vector; cameraMan.move(CameraMan.CAMERA_MOVEMENT_DELTA, 0); return; case KeyEvent.VK_M: cameraMan.move(0, CameraMan.CAMERA_MOVEMENT_DELTA); return; case KeyEvent.VK_N: cameraMan.move(0, -CameraMan.CAMERA_MOVEMENT_DELTA); return; case KeyEvent.VK_1: cameraMan.setMode(CameraMan.Mode.SELF); return; case KeyEvent.VK_2: cameraMan.setMode(CameraMan.Mode.GAGGLE); return; case KeyEvent.VK_3: cameraMan.setMode(CameraMan.Mode.PLAN); return; case KeyEvent.VK_4: cameraMan.setMode(CameraMan.Mode.TILE); return; default: } } @Override public void keyReleased(KeyEvent e) { }
public void draw(Graphics g, int width, int height) {
Turbo87/flight-club
core/src/main/java/org/flightclub/XCGame.java
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // // Path: core/src/main/java/org/flightclub/compat/Font.java // public class Font { // private java.awt.Font f; // // /** // * The plain style constant. // */ // public static final int PLAIN = 0; // // /** // * The bold style constant. This can be combined with the other style // * constants (except PLAIN) for mixed styles. // */ // public static final int BOLD = 1; // // /** // * The italicized style constant. This can be combined with the other // * style constants (except PLAIN) for mixed styles. // */ // public static final int ITALIC = 2; // // public Font(String name, int style, int size) { // this(new java.awt.Font(name, style, size)); // } // // public Font(java.awt.Font f) { // this.f = f; // } // // public java.awt.Font getFont() { // return f; // } // } // // Path: core/src/main/java/org/flightclub/compat/Graphics.java // public interface Graphics { // void setColor(Color color); // void setFont(Font font); // // void drawLine(int x1, int y1, int x2, int y2); // void drawString(String str, int x, int y); // // void fillCircle(int x, int y, int diameter); // void fillPolygon(int[] xPoints, int[] yPoints, int nPoints); // }
import org.flightclub.compat.Color; import org.flightclub.compat.Font; import org.flightclub.compat.Graphics; import java.awt.event.KeyEvent; import java.util.Vector;
return; case KeyEvent.VK_3: cameraMan.setMode(CameraMan.Mode.PLAN); return; case KeyEvent.VK_4: cameraMan.setMode(CameraMan.Mode.TILE); return; default: } } @Override public void keyReleased(KeyEvent e) { } public void draw(Graphics g, int width, int height) { //TODO optimize - build vector of objs in FOV, need only draw these cameraMan.setMatrix(); obj3dManager.sortObjects(); for (ObjectLayer layer : obj3dManager.layers) { for (Object3d object : layer) { object.film(cameraMan); object.draw(g); } } //Text if (textMessage != null) {
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // // Path: core/src/main/java/org/flightclub/compat/Font.java // public class Font { // private java.awt.Font f; // // /** // * The plain style constant. // */ // public static final int PLAIN = 0; // // /** // * The bold style constant. This can be combined with the other style // * constants (except PLAIN) for mixed styles. // */ // public static final int BOLD = 1; // // /** // * The italicized style constant. This can be combined with the other // * style constants (except PLAIN) for mixed styles. // */ // public static final int ITALIC = 2; // // public Font(String name, int style, int size) { // this(new java.awt.Font(name, style, size)); // } // // public Font(java.awt.Font f) { // this.f = f; // } // // public java.awt.Font getFont() { // return f; // } // } // // Path: core/src/main/java/org/flightclub/compat/Graphics.java // public interface Graphics { // void setColor(Color color); // void setFont(Font font); // // void drawLine(int x1, int y1, int x2, int y2); // void drawString(String str, int x, int y); // // void fillCircle(int x, int y, int diameter); // void fillPolygon(int[] xPoints, int[] yPoints, int nPoints); // } // Path: core/src/main/java/org/flightclub/XCGame.java import org.flightclub.compat.Color; import org.flightclub.compat.Font; import org.flightclub.compat.Graphics; import java.awt.event.KeyEvent; import java.util.Vector; return; case KeyEvent.VK_3: cameraMan.setMode(CameraMan.Mode.PLAN); return; case KeyEvent.VK_4: cameraMan.setMode(CameraMan.Mode.TILE); return; default: } } @Override public void keyReleased(KeyEvent e) { } public void draw(Graphics g, int width, int height) { //TODO optimize - build vector of objs in FOV, need only draw these cameraMan.setMatrix(); obj3dManager.sortObjects(); for (ObjectLayer layer : obj3dManager.layers) { for (Object3d object : layer) { object.film(cameraMan); object.draw(g); } } //Text if (textMessage != null) {
Font font = new Font("SansSerif", Font.PLAIN, 10);
Turbo87/flight-club
core/src/main/java/org/flightclub/XCGame.java
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // // Path: core/src/main/java/org/flightclub/compat/Font.java // public class Font { // private java.awt.Font f; // // /** // * The plain style constant. // */ // public static final int PLAIN = 0; // // /** // * The bold style constant. This can be combined with the other style // * constants (except PLAIN) for mixed styles. // */ // public static final int BOLD = 1; // // /** // * The italicized style constant. This can be combined with the other // * style constants (except PLAIN) for mixed styles. // */ // public static final int ITALIC = 2; // // public Font(String name, int style, int size) { // this(new java.awt.Font(name, style, size)); // } // // public Font(java.awt.Font f) { // this.f = f; // } // // public java.awt.Font getFont() { // return f; // } // } // // Path: core/src/main/java/org/flightclub/compat/Graphics.java // public interface Graphics { // void setColor(Color color); // void setFont(Font font); // // void drawLine(int x1, int y1, int x2, int y2); // void drawString(String str, int x, int y); // // void fillCircle(int x, int y, int diameter); // void fillPolygon(int[] xPoints, int[] yPoints, int nPoints); // }
import org.flightclub.compat.Color; import org.flightclub.compat.Font; import org.flightclub.compat.Graphics; import java.awt.event.KeyEvent; import java.util.Vector;
cameraMan.setMode(CameraMan.Mode.PLAN); return; case KeyEvent.VK_4: cameraMan.setMode(CameraMan.Mode.TILE); return; default: } } @Override public void keyReleased(KeyEvent e) { } public void draw(Graphics g, int width, int height) { //TODO optimize - build vector of objs in FOV, need only draw these cameraMan.setMatrix(); obj3dManager.sortObjects(); for (ObjectLayer layer : obj3dManager.layers) { for (Object3d object : layer) { object.film(cameraMan); object.draw(g); } } //Text if (textMessage != null) { Font font = new Font("SansSerif", Font.PLAIN, 10); g.setFont(font);
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // // Path: core/src/main/java/org/flightclub/compat/Font.java // public class Font { // private java.awt.Font f; // // /** // * The plain style constant. // */ // public static final int PLAIN = 0; // // /** // * The bold style constant. This can be combined with the other style // * constants (except PLAIN) for mixed styles. // */ // public static final int BOLD = 1; // // /** // * The italicized style constant. This can be combined with the other // * style constants (except PLAIN) for mixed styles. // */ // public static final int ITALIC = 2; // // public Font(String name, int style, int size) { // this(new java.awt.Font(name, style, size)); // } // // public Font(java.awt.Font f) { // this.f = f; // } // // public java.awt.Font getFont() { // return f; // } // } // // Path: core/src/main/java/org/flightclub/compat/Graphics.java // public interface Graphics { // void setColor(Color color); // void setFont(Font font); // // void drawLine(int x1, int y1, int x2, int y2); // void drawString(String str, int x, int y); // // void fillCircle(int x, int y, int diameter); // void fillPolygon(int[] xPoints, int[] yPoints, int nPoints); // } // Path: core/src/main/java/org/flightclub/XCGame.java import org.flightclub.compat.Color; import org.flightclub.compat.Font; import org.flightclub.compat.Graphics; import java.awt.event.KeyEvent; import java.util.Vector; cameraMan.setMode(CameraMan.Mode.PLAN); return; case KeyEvent.VK_4: cameraMan.setMode(CameraMan.Mode.TILE); return; default: } } @Override public void keyReleased(KeyEvent e) { } public void draw(Graphics g, int width, int height) { //TODO optimize - build vector of objs in FOV, need only draw these cameraMan.setMatrix(); obj3dManager.sortObjects(); for (ObjectLayer layer : obj3dManager.layers) { for (Object3d object : layer) { object.film(cameraMan); object.draw(g); } } //Text if (textMessage != null) { Font font = new Font("SansSerif", Font.PLAIN, 10); g.setFont(font);
g.setColor(Color.LIGHT_GRAY);
Turbo87/flight-club
core/src/main/java/org/flightclub/Object3dWithShadow.java
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // // Path: core/src/main/java/org/flightclub/compat/Graphics.java // public interface Graphics { // void setColor(Color color); // void setFont(Font font); // // void drawLine(int x1, int y1, int x2, int y2); // void drawString(String str, int x, int y); // // void fillCircle(int x, int y, int diameter); // void fillPolygon(int[] xPoints, int[] yPoints, int nPoints); // }
import org.flightclub.compat.Color; import org.flightclub.compat.Graphics; import java.util.Vector;
/** This code is covered by the GNU General Public License detailed at http://www.gnu.org/copyleft/gpl.html Flight Club docs located at http://www.danb.dircon.co.uk/hg/hg.htm Dan Burton , Nov 2001 */ package org.flightclub; /** * Three new methods added to object3d... * * 1. addWireWithShadow - the wire that casts the shadow * 2. updateShadow - make the shaow track the object * 3. drawShadow - call this when drawing the landscape segement * that it falls on * * 2001-10-24: change one shadow to a list of shadows (use for new glider shape) * 2002-02-24: offset shadow to one side, and darker */ public class Object3dWithShadow extends Object3d { static final int MAX_SHADOWS = 2; static final int SHADOW_COLOR = 180; final int[] shadowCasters = new int[MAX_SHADOWS]; final Surface[] shadows = new Surface[MAX_SHADOWS]; int numShadows = 0; Object3dWithShadow(XCGame theApp) { super(theApp); initShadow(); } Object3dWithShadow(XCGame theApp, boolean register) { super(theApp, register); initShadow(); }
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // // Path: core/src/main/java/org/flightclub/compat/Graphics.java // public interface Graphics { // void setColor(Color color); // void setFont(Font font); // // void drawLine(int x1, int y1, int x2, int y2); // void drawString(String str, int x, int y); // // void fillCircle(int x, int y, int diameter); // void fillPolygon(int[] xPoints, int[] yPoints, int nPoints); // } // Path: core/src/main/java/org/flightclub/Object3dWithShadow.java import org.flightclub.compat.Color; import org.flightclub.compat.Graphics; import java.util.Vector; /** This code is covered by the GNU General Public License detailed at http://www.gnu.org/copyleft/gpl.html Flight Club docs located at http://www.danb.dircon.co.uk/hg/hg.htm Dan Burton , Nov 2001 */ package org.flightclub; /** * Three new methods added to object3d... * * 1. addWireWithShadow - the wire that casts the shadow * 2. updateShadow - make the shaow track the object * 3. drawShadow - call this when drawing the landscape segement * that it falls on * * 2001-10-24: change one shadow to a list of shadows (use for new glider shape) * 2002-02-24: offset shadow to one side, and darker */ public class Object3dWithShadow extends Object3d { static final int MAX_SHADOWS = 2; static final int SHADOW_COLOR = 180; final int[] shadowCasters = new int[MAX_SHADOWS]; final Surface[] shadows = new Surface[MAX_SHADOWS]; int numShadows = 0; Object3dWithShadow(XCGame theApp) { super(theApp); initShadow(); } Object3dWithShadow(XCGame theApp, boolean register) { super(theApp, register); initShadow(); }
public int addWireWithShadow(Vector<Vector3d> wirePoints, Color c, boolean isSolid, boolean hasNormal) {
Turbo87/flight-club
core/src/main/java/org/flightclub/Object3dWithShadow.java
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // // Path: core/src/main/java/org/flightclub/compat/Graphics.java // public interface Graphics { // void setColor(Color color); // void setFont(Font font); // // void drawLine(int x1, int y1, int x2, int y2); // void drawString(String str, int x, int y); // // void fillCircle(int x, int y, int diameter); // void fillPolygon(int[] xPoints, int[] yPoints, int nPoints); // }
import org.flightclub.compat.Color; import org.flightclub.compat.Graphics; import java.util.Vector;
private void initShadow() { for (int i = 0; i < MAX_SHADOWS; i++) { shadowCasters[i] = -1; } } public void updateShadow() { /* keep shadow under object. the owner/creator of this object should call this method each time they move the object */ for (int i = 0; i < MAX_SHADOWS; i++) { if (shadowCasters[i] == -1) return; Surface surface = (Surface) wires.elementAt(shadowCasters[i]); for (int j = surface.numPoints - 1; j >= 0; j--) { Vector3d p = points.elementAt(surface.points[j]); Vector3d q = points.elementAt(shadows[i].points[surface.numPoints - 1 - j]);//?? q.set(p); //float doff = p.z/2; //q.x -= doff; //q.y += 0;; if (app.landscape != null) q.z = app.landscape.getHeight(q.x, q.y); else q.z = 0; } } }
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // // Path: core/src/main/java/org/flightclub/compat/Graphics.java // public interface Graphics { // void setColor(Color color); // void setFont(Font font); // // void drawLine(int x1, int y1, int x2, int y2); // void drawString(String str, int x, int y); // // void fillCircle(int x, int y, int diameter); // void fillPolygon(int[] xPoints, int[] yPoints, int nPoints); // } // Path: core/src/main/java/org/flightclub/Object3dWithShadow.java import org.flightclub.compat.Color; import org.flightclub.compat.Graphics; import java.util.Vector; private void initShadow() { for (int i = 0; i < MAX_SHADOWS; i++) { shadowCasters[i] = -1; } } public void updateShadow() { /* keep shadow under object. the owner/creator of this object should call this method each time they move the object */ for (int i = 0; i < MAX_SHADOWS; i++) { if (shadowCasters[i] == -1) return; Surface surface = (Surface) wires.elementAt(shadowCasters[i]); for (int j = surface.numPoints - 1; j >= 0; j--) { Vector3d p = points.elementAt(surface.points[j]); Vector3d q = points.elementAt(shadows[i].points[surface.numPoints - 1 - j]);//?? q.set(p); //float doff = p.z/2; //q.x -= doff; //q.y += 0;; if (app.landscape != null) q.z = app.landscape.getHeight(q.x, q.y); else q.z = 0; } } }
public void drawShadow(Graphics g) {
Turbo87/flight-club
core/src/main/java/org/flightclub/PolyLine.java
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // // Path: core/src/main/java/org/flightclub/compat/Graphics.java // public interface Graphics { // void setColor(Color color); // void setFont(Font font); // // void drawLine(int x1, int y1, int x2, int y2); // void drawString(String str, int x, int y); // // void fillCircle(int x, int y, int diameter); // void fillPolygon(int[] xPoints, int[] yPoints, int nPoints); // }
import org.flightclub.compat.Color; import org.flightclub.compat.Graphics;
/** This code is covered by the GNU General Public License detailed at http://www.gnu.org/copyleft/gpl.html Flight Club docs located at http://www.danb.dircon.co.uk/hg/hg.htm Dan Burton , Nov 2001 */ package org.flightclub; public class PolyLine { final int numPoints; final int[] points; int nextIndex = 0; final Object3d object3d; // true color
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // // Path: core/src/main/java/org/flightclub/compat/Graphics.java // public interface Graphics { // void setColor(Color color); // void setFont(Font font); // // void drawLine(int x1, int y1, int x2, int y2); // void drawString(String str, int x, int y); // // void fillCircle(int x, int y, int diameter); // void fillPolygon(int[] xPoints, int[] yPoints, int nPoints); // } // Path: core/src/main/java/org/flightclub/PolyLine.java import org.flightclub.compat.Color; import org.flightclub.compat.Graphics; /** This code is covered by the GNU General Public License detailed at http://www.gnu.org/copyleft/gpl.html Flight Club docs located at http://www.danb.dircon.co.uk/hg/hg.htm Dan Burton , Nov 2001 */ package org.flightclub; public class PolyLine { final int numPoints; final int[] points; int nextIndex = 0; final Object3d object3d; // true color
Color c;
Turbo87/flight-club
core/src/main/java/org/flightclub/PolyLine.java
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // // Path: core/src/main/java/org/flightclub/compat/Graphics.java // public interface Graphics { // void setColor(Color color); // void setFont(Font font); // // void drawLine(int x1, int y1, int x2, int y2); // void drawString(String str, int x, int y); // // void fillCircle(int x, int y, int diameter); // void fillPolygon(int[] xPoints, int[] yPoints, int nPoints); // }
import org.flightclub.compat.Color; import org.flightclub.compat.Graphics;
void setNormal() { if (numPoints < 3) return; Vector3d[] ps = new Vector3d[3]; for (int i = 0; i < 3; i++) ps[i] = object3d.points.elementAt(points[i]); Vector3d e1 = ps[0].minus(ps[1]); Vector3d e2 = ps[2].minus(ps[1]); normal = new Vector3d(e1).cross(e2).makeUnit(); calcLight(); } void calcLight() { int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); float light = object3d.app.cameraMan.surfaceLight(normal); r *= light; g *= light; b *= light; c_ = new Color(r, g, b); }
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // // Path: core/src/main/java/org/flightclub/compat/Graphics.java // public interface Graphics { // void setColor(Color color); // void setFont(Font font); // // void drawLine(int x1, int y1, int x2, int y2); // void drawString(String str, int x, int y); // // void fillCircle(int x, int y, int diameter); // void fillPolygon(int[] xPoints, int[] yPoints, int nPoints); // } // Path: core/src/main/java/org/flightclub/PolyLine.java import org.flightclub.compat.Color; import org.flightclub.compat.Graphics; void setNormal() { if (numPoints < 3) return; Vector3d[] ps = new Vector3d[3]; for (int i = 0; i < 3; i++) ps[i] = object3d.points.elementAt(points[i]); Vector3d e1 = ps[0].minus(ps[1]); Vector3d e2 = ps[2].minus(ps[1]); normal = new Vector3d(e1).cross(e2).makeUnit(); calcLight(); } void calcLight() { int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); float light = object3d.app.cameraMan.surfaceLight(normal); r *= light; g *= light; b *= light; c_ = new Color(r, g, b); }
public void draw(Graphics g) {
Turbo87/flight-club
core/src/main/java/org/flightclub/Cloud.java
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // }
import org.flightclub.compat.Color; import java.util.Vector;
/** This code is covered by the GNU General Public License detailed at http://www.gnu.org/copyleft/gpl.html Flight Club docs located at http://www.danb.dircon.co.uk/hg/hg.htm Dan Burton , Nov 2001 */ package org.flightclub; public class Cloud implements CameraSubject, Clock.Observer { final XCGame app; final Object3dWithShadow object3d; Vector3d p = new Vector3d(); float radius; final float maxRadius; final boolean solid = true;
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // Path: core/src/main/java/org/flightclub/Cloud.java import org.flightclub.compat.Color; import java.util.Vector; /** This code is covered by the GNU General Public License detailed at http://www.gnu.org/copyleft/gpl.html Flight Club docs located at http://www.danb.dircon.co.uk/hg/hg.htm Dan Burton , Nov 2001 */ package org.flightclub; public class Cloud implements CameraSubject, Clock.Observer { final XCGame app; final Object3dWithShadow object3d; Vector3d p = new Vector3d(); float radius; final float maxRadius; final boolean solid = true;
final Color color;
Turbo87/flight-club
core/src/main/java/org/flightclub/Tail.java
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // }
import org.flightclub.compat.Color; import java.util.Vector;
/** This code is covered by the GNU General Public License detailed at http://www.gnu.org/copyleft/gpl.html Flight Club docs located at http://www.danb.dircon.co.uk/hg/hg.htm Dan Burton , Nov 2001 */ package org.flightclub; /** * a tail of length n may be attached to a flying dot */ public class Tail extends Object3d { final int length;
// Path: core/src/main/java/org/flightclub/compat/Color.java // public class Color { // private final java.awt.Color c; // // // /** // * The color white. In the default sRGB space. // */ // public final static Color WHITE = new Color(255, 255, 255); // // /** // * The color light gray. In the default sRGB space. // */ // public final static Color LIGHT_GRAY = new Color(192, 192, 192); // // /** // * The color gray. In the default sRGB space. // */ // public final static Color GRAY = new Color(128, 128, 128); // // /** // * The color dark gray. In the default sRGB space. // */ // public final static Color DARK_GRAY = new Color(64, 64, 64); // // /** // * The color black. In the default sRGB space. // */ // public final static Color BLACK = new Color(0, 0, 0); // // /** // * The color red. In the default sRGB space. // */ // public final static Color RED = new Color(255, 0, 0); // // /** // * The color pink. In the default sRGB space. // */ // public final static Color PINK = new Color(255, 175, 175); // // /** // * The color orange. In the default sRGB space. // */ // public final static Color ORANGE = new Color(255, 200, 0); // // /** // * The color yellow. In the default sRGB space. // */ // public final static Color YELLOW = new Color(255, 255, 0); // // /** // * The color green. In the default sRGB space. // */ // public final static Color GREEN = new Color(0, 255, 0); // // /** // * The color magenta. In the default sRGB space. // */ // public final static Color MAGENTA = new Color(255, 0, 255); // // /** // * The color cyan. In the default sRGB space. // */ // public final static Color CYAN = new Color(0, 255, 255); // // /** // * The color blue. In the default sRGB space. // */ // public final static Color BLUE = new Color(0, 0, 255); // // public Color(int r, int g, int b) { // this.c = new java.awt.Color(r, g, b); // } // // public java.awt.Color getColor() { // return c; // } // // public int getRed() { // return c.getRed(); // } // // public int getGreen() { // return c.getGreen(); // } // // public int getBlue() { // return c.getBlue(); // } // } // Path: core/src/main/java/org/flightclub/Tail.java import org.flightclub.compat.Color; import java.util.Vector; /** This code is covered by the GNU General Public License detailed at http://www.gnu.org/copyleft/gpl.html Flight Club docs located at http://www.danb.dircon.co.uk/hg/hg.htm Dan Burton , Nov 2001 */ package org.flightclub; /** * a tail of length n may be attached to a flying dot */ public class Tail extends Object3d { final int length;
final Color color;