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
ibcn-cloudlet/firefly
be.iminds.iot.things.rule.engine.provider/src/be/iminds/iot/things/rule/factory/SimpleCondition.java
// Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.rule.api/src/be/iminds/iot/things/rule/api/Change.java // public class Change { // // public Change(UUID thingId, String stateVariable, Object value){ // this.thingId = thingId; // this.stateVariable = stateVariable; // this.value = value; // } // // public UUID thingId; // public String stateVariable; // public Object value; // // } // // Path: be.iminds.iot.things.rule.api/src/be/iminds/iot/things/rule/api/Condition.java // public interface Condition extends Serializable { // // public UUID getId(); // // public String getType(); // // public void setThing(Thing thing); // // public boolean trigger(Change change); // // }
import aQute.lib.converter.Converter; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.rule.api.Change; import be.iminds.iot.things.rule.api.Condition; import java.util.UUID;
/******************************************************************************* * Copyright (c) 2015, Tim Verbelen * Internet Based Communication Networks and Services research group (IBCN), * Department of Information Technology (INTEC), Ghent University - iMinds. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Ghent University - iMinds, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package be.iminds.iot.things.rule.factory; public class SimpleCondition implements Condition { public enum Operator {BECOMES,IS,IS_NOT,IS_GREATER,IS_LESS,CHANGES}; private final UUID id; private final String type; private final String variable; private Operator operator; private Object value; private Object currentValue; public SimpleCondition( UUID id, String type, String variable, Operator operator, Object value) { this.id = id; this.type = type; this.variable = variable; this.operator = operator; this.value = value; } @Override public UUID getId() { return id; } @Override public String getType() { return type; } @Override
// Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.rule.api/src/be/iminds/iot/things/rule/api/Change.java // public class Change { // // public Change(UUID thingId, String stateVariable, Object value){ // this.thingId = thingId; // this.stateVariable = stateVariable; // this.value = value; // } // // public UUID thingId; // public String stateVariable; // public Object value; // // } // // Path: be.iminds.iot.things.rule.api/src/be/iminds/iot/things/rule/api/Condition.java // public interface Condition extends Serializable { // // public UUID getId(); // // public String getType(); // // public void setThing(Thing thing); // // public boolean trigger(Change change); // // } // Path: be.iminds.iot.things.rule.engine.provider/src/be/iminds/iot/things/rule/factory/SimpleCondition.java import aQute.lib.converter.Converter; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.rule.api.Change; import be.iminds.iot.things.rule.api.Condition; import java.util.UUID; /******************************************************************************* * Copyright (c) 2015, Tim Verbelen * Internet Based Communication Networks and Services research group (IBCN), * Department of Information Technology (INTEC), Ghent University - iMinds. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Ghent University - iMinds, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package be.iminds.iot.things.rule.factory; public class SimpleCondition implements Condition { public enum Operator {BECOMES,IS,IS_NOT,IS_GREATER,IS_LESS,CHANGES}; private final UUID id; private final String type; private final String variable; private Operator operator; private Object value; private Object currentValue; public SimpleCondition( UUID id, String type, String variable, Operator operator, Object value) { this.id = id; this.type = type; this.variable = variable; this.operator = operator; this.value = value; } @Override public UUID getId() { return id; } @Override public String getType() { return type; } @Override
public void setThing(Thing thing) {
ibcn-cloudlet/firefly
be.iminds.iot.things.rule.engine.provider/src/be/iminds/iot/things/rule/factory/SimpleCondition.java
// Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.rule.api/src/be/iminds/iot/things/rule/api/Change.java // public class Change { // // public Change(UUID thingId, String stateVariable, Object value){ // this.thingId = thingId; // this.stateVariable = stateVariable; // this.value = value; // } // // public UUID thingId; // public String stateVariable; // public Object value; // // } // // Path: be.iminds.iot.things.rule.api/src/be/iminds/iot/things/rule/api/Condition.java // public interface Condition extends Serializable { // // public UUID getId(); // // public String getType(); // // public void setThing(Thing thing); // // public boolean trigger(Change change); // // }
import aQute.lib.converter.Converter; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.rule.api.Change; import be.iminds.iot.things.rule.api.Condition; import java.util.UUID;
public SimpleCondition( UUID id, String type, String variable, Operator operator, Object value) { this.id = id; this.type = type; this.variable = variable; this.operator = operator; this.value = value; } @Override public UUID getId() { return id; } @Override public String getType() { return type; } @Override public void setThing(Thing thing) { // ignore } @Override
// Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.rule.api/src/be/iminds/iot/things/rule/api/Change.java // public class Change { // // public Change(UUID thingId, String stateVariable, Object value){ // this.thingId = thingId; // this.stateVariable = stateVariable; // this.value = value; // } // // public UUID thingId; // public String stateVariable; // public Object value; // // } // // Path: be.iminds.iot.things.rule.api/src/be/iminds/iot/things/rule/api/Condition.java // public interface Condition extends Serializable { // // public UUID getId(); // // public String getType(); // // public void setThing(Thing thing); // // public boolean trigger(Change change); // // } // Path: be.iminds.iot.things.rule.engine.provider/src/be/iminds/iot/things/rule/factory/SimpleCondition.java import aQute.lib.converter.Converter; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.rule.api.Change; import be.iminds.iot.things.rule.api.Condition; import java.util.UUID; public SimpleCondition( UUID id, String type, String variable, Operator operator, Object value) { this.id = id; this.type = type; this.variable = variable; this.operator = operator; this.value = value; } @Override public UUID getId() { return id; } @Override public String getType() { return type; } @Override public void setThing(Thing thing) { // ignore } @Override
public boolean trigger(Change change) {
ibcn-cloudlet/firefly
be.iminds.iot.things.rule.engine.provider/src/be/iminds/iot/things/rule/endpoint/SimpleConditionDTO.java
// Path: be.iminds.iot.things.rule.engine.provider/src/be/iminds/iot/things/rule/factory/SimpleCondition.java // public enum Operator {BECOMES,IS,IS_NOT,IS_GREATER,IS_LESS,CHANGES};
import be.iminds.iot.things.rule.factory.SimpleCondition.Operator; import java.util.UUID;
/******************************************************************************* * Copyright (c) 2015, Tim Verbelen * Internet Based Communication Networks and Services research group (IBCN), * Department of Information Technology (INTEC), Ghent University - iMinds. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Ghent University - iMinds, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package be.iminds.iot.things.rule.endpoint; public class SimpleConditionDTO { public UUID thingId; public String type; public String variable;
// Path: be.iminds.iot.things.rule.engine.provider/src/be/iminds/iot/things/rule/factory/SimpleCondition.java // public enum Operator {BECOMES,IS,IS_NOT,IS_GREATER,IS_LESS,CHANGES}; // Path: be.iminds.iot.things.rule.engine.provider/src/be/iminds/iot/things/rule/endpoint/SimpleConditionDTO.java import be.iminds.iot.things.rule.factory.SimpleCondition.Operator; import java.util.UUID; /******************************************************************************* * Copyright (c) 2015, Tim Verbelen * Internet Based Communication Networks and Services research group (IBCN), * Department of Information Technology (INTEC), Ghent University - iMinds. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Ghent University - iMinds, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package be.iminds.iot.things.rule.endpoint; public class SimpleConditionDTO { public UUID thingId; public String type; public String variable;
public Operator operator;
ibcn-cloudlet/firefly
be.iminds.iot.things.api/src/be/iminds/iot/things/api/camera/CameraListener.java
// Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/camera/Camera.java // public static enum Format { // YUV, RGB, GRAYSCALE, MJPEG; // }
import be.iminds.iot.things.api.camera.Camera.Format; import java.util.UUID;
/******************************************************************************* * Copyright (c) 2015, Tim Verbelen * Internet Based Communication Networks and Services research group (IBCN), * Department of Information Technology (INTEC), Ghent University - iMinds. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Ghent University - iMinds, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package be.iminds.iot.things.api.camera; /** * Register a CameraListener with CAMERA_ID property set to listen for new frames from that camera. * * @author tverbele * */ public interface CameraListener { public final static String CAMERA_ID = "be.iminds.iot.thing.camera.id"; public final static String CAMERA_FORMAT = "be.iminds.iot.thing.camera.format";
// Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/camera/Camera.java // public static enum Format { // YUV, RGB, GRAYSCALE, MJPEG; // } // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/camera/CameraListener.java import be.iminds.iot.things.api.camera.Camera.Format; import java.util.UUID; /******************************************************************************* * Copyright (c) 2015, Tim Verbelen * Internet Based Communication Networks and Services research group (IBCN), * Department of Information Technology (INTEC), Ghent University - iMinds. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Ghent University - iMinds, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package be.iminds.iot.things.api.camera; /** * Register a CameraListener with CAMERA_ID property set to listen for new frames from that camera. * * @author tverbele * */ public interface CameraListener { public final static String CAMERA_ID = "be.iminds.iot.thing.camera.id"; public final static String CAMERA_FORMAT = "be.iminds.iot.thing.camera.format";
public void nextFrame(UUID id, Format format, byte[] data);
ibcn-cloudlet/firefly
be.iminds.iot.things.repository.provider/src/be/iminds/iot/things/repository/provider/ThingsRepositoryRestEndpoint.java
// Path: be.iminds.iot.things.repository.api/src/be/iminds/iot/things/repository/api/ThingsRepository.java // public interface ThingsRepository { // // public ThingDTO getThing(UUID id); // // public Collection<ThingDTO> getThings(); // // public void putThing(ThingDTO thing); // // } // // Path: be.iminds.iot.things.repository.api/src/be/iminds/iot/things/repository/api/ThingDTO.java // public class ThingDTO { // // // These are provided by the system (hardware) // public UUID id; /* unique thing id - based on device+service combination */ // public String device; /* device name */ // public String service; /* service name */ // public UUID gateway; /* id of the gateway that provides this thing */ // // // These are (optionally) provided by the user // public String name; /* user defined name of the thing */ // public String location; /* user defined location the thing is located */ // // // Type represents the functionality (interface) of this thing // public String type; /* type of the device */ // // public Map<String, Object> state; /* last known state variables */ // // }
import java.util.UUID; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import osgi.enroute.rest.api.REST; import osgi.enroute.rest.api.RequireRestImplementation; import be.iminds.iot.things.repository.api.ThingsRepository; import be.iminds.iot.things.repository.api.ThingDTO; import java.util.Collection;
/******************************************************************************* * Copyright (c) 2015, Tim Verbelen * Internet Based Communication Networks and Services research group (IBCN), * Department of Information Technology (INTEC), Ghent University - iMinds. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Ghent University - iMinds, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package be.iminds.iot.things.repository.provider; @RequireRestImplementation @Component() public class ThingsRepositoryRestEndpoint implements REST{
// Path: be.iminds.iot.things.repository.api/src/be/iminds/iot/things/repository/api/ThingsRepository.java // public interface ThingsRepository { // // public ThingDTO getThing(UUID id); // // public Collection<ThingDTO> getThings(); // // public void putThing(ThingDTO thing); // // } // // Path: be.iminds.iot.things.repository.api/src/be/iminds/iot/things/repository/api/ThingDTO.java // public class ThingDTO { // // // These are provided by the system (hardware) // public UUID id; /* unique thing id - based on device+service combination */ // public String device; /* device name */ // public String service; /* service name */ // public UUID gateway; /* id of the gateway that provides this thing */ // // // These are (optionally) provided by the user // public String name; /* user defined name of the thing */ // public String location; /* user defined location the thing is located */ // // // Type represents the functionality (interface) of this thing // public String type; /* type of the device */ // // public Map<String, Object> state; /* last known state variables */ // // } // Path: be.iminds.iot.things.repository.provider/src/be/iminds/iot/things/repository/provider/ThingsRepositoryRestEndpoint.java import java.util.UUID; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import osgi.enroute.rest.api.REST; import osgi.enroute.rest.api.RequireRestImplementation; import be.iminds.iot.things.repository.api.ThingsRepository; import be.iminds.iot.things.repository.api.ThingDTO; import java.util.Collection; /******************************************************************************* * Copyright (c) 2015, Tim Verbelen * Internet Based Communication Networks and Services research group (IBCN), * Department of Information Technology (INTEC), Ghent University - iMinds. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Ghent University - iMinds, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package be.iminds.iot.things.repository.provider; @RequireRestImplementation @Component() public class ThingsRepositoryRestEndpoint implements REST{
private ThingsRepository repository;
ibcn-cloudlet/firefly
be.iminds.iot.things.repository.provider/src/be/iminds/iot/things/repository/provider/ThingsRepositoryRestEndpoint.java
// Path: be.iminds.iot.things.repository.api/src/be/iminds/iot/things/repository/api/ThingsRepository.java // public interface ThingsRepository { // // public ThingDTO getThing(UUID id); // // public Collection<ThingDTO> getThings(); // // public void putThing(ThingDTO thing); // // } // // Path: be.iminds.iot.things.repository.api/src/be/iminds/iot/things/repository/api/ThingDTO.java // public class ThingDTO { // // // These are provided by the system (hardware) // public UUID id; /* unique thing id - based on device+service combination */ // public String device; /* device name */ // public String service; /* service name */ // public UUID gateway; /* id of the gateway that provides this thing */ // // // These are (optionally) provided by the user // public String name; /* user defined name of the thing */ // public String location; /* user defined location the thing is located */ // // // Type represents the functionality (interface) of this thing // public String type; /* type of the device */ // // public Map<String, Object> state; /* last known state variables */ // // }
import java.util.UUID; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import osgi.enroute.rest.api.REST; import osgi.enroute.rest.api.RequireRestImplementation; import be.iminds.iot.things.repository.api.ThingsRepository; import be.iminds.iot.things.repository.api.ThingDTO; import java.util.Collection;
/******************************************************************************* * Copyright (c) 2015, Tim Verbelen * Internet Based Communication Networks and Services research group (IBCN), * Department of Information Technology (INTEC), Ghent University - iMinds. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Ghent University - iMinds, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package be.iminds.iot.things.repository.provider; @RequireRestImplementation @Component() public class ThingsRepositoryRestEndpoint implements REST{ private ThingsRepository repository;
// Path: be.iminds.iot.things.repository.api/src/be/iminds/iot/things/repository/api/ThingsRepository.java // public interface ThingsRepository { // // public ThingDTO getThing(UUID id); // // public Collection<ThingDTO> getThings(); // // public void putThing(ThingDTO thing); // // } // // Path: be.iminds.iot.things.repository.api/src/be/iminds/iot/things/repository/api/ThingDTO.java // public class ThingDTO { // // // These are provided by the system (hardware) // public UUID id; /* unique thing id - based on device+service combination */ // public String device; /* device name */ // public String service; /* service name */ // public UUID gateway; /* id of the gateway that provides this thing */ // // // These are (optionally) provided by the user // public String name; /* user defined name of the thing */ // public String location; /* user defined location the thing is located */ // // // Type represents the functionality (interface) of this thing // public String type; /* type of the device */ // // public Map<String, Object> state; /* last known state variables */ // // } // Path: be.iminds.iot.things.repository.provider/src/be/iminds/iot/things/repository/provider/ThingsRepositoryRestEndpoint.java import java.util.UUID; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import osgi.enroute.rest.api.REST; import osgi.enroute.rest.api.RequireRestImplementation; import be.iminds.iot.things.repository.api.ThingsRepository; import be.iminds.iot.things.repository.api.ThingDTO; import java.util.Collection; /******************************************************************************* * Copyright (c) 2015, Tim Verbelen * Internet Based Communication Networks and Services research group (IBCN), * Department of Information Technology (INTEC), Ghent University - iMinds. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Ghent University - iMinds, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package be.iminds.iot.things.repository.provider; @RequireRestImplementation @Component() public class ThingsRepositoryRestEndpoint implements REST{ private ThingsRepository repository;
public ThingDTO getThing(UUID id) {
ibcn-cloudlet/firefly
be.iminds.iot.things.dyamand.adapter/src/be/iminds/iot/things/dyamand/adapter/DyamandAdapter.java
// Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/ChangeEvent.java // public class ChangeEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public String stateVariable; /* state variable that changed */ // public Object stateValue; /* new value of the state variable */ // public long timestamp; /* timestamp the event was generated */ // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/OfflineEvent.java // public class OfflineEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public long timestamp; /* timestamp the event was generated */ // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/OnlineEvent.java // public class OnlineEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public String service; /* service of the thing */ // public String device; /* device name of the thing */ // public String type; /* thing type */ // public long timestamp; /* timestamp the event was generated */ // // }
import java.util.ArrayList; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.UUID; import org.dyamand.event.Event; import org.dyamand.event.EventListener; import org.dyamand.event.ServicePOJOOfflineEvent; import org.dyamand.event.ServicePOJOOnlineEvent; import org.dyamand.event.StateChangedEvent; import org.dyamand.service.ServicePOJO; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.event.EventAdmin; import org.osgi.service.event.EventProperties; import osgi.enroute.dto.api.DTOs; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.api.event.ChangeEvent; import be.iminds.iot.things.api.event.OfflineEvent; import be.iminds.iot.things.api.event.OnlineEvent;
this.servicePojoOnline(servicePOJO); } else if (event instanceof ServicePOJOOfflineEvent) { final ServicePOJO servicePOJO = ((ServicePOJOOfflineEvent) event) .getServicePOJO(); this.servicePojoOffline(servicePOJO); } else if (event instanceof StateChangedEvent) { final org.dyamand.service.StateChange stateChange = ((StateChangedEvent) event) .getStateChange(); this.processStateChange(stateChange); } } private void servicePojoOnline(final ServicePOJO servicePOJO) { if(this.services.get(servicePOJO)!=null){ System.err.println("ServicePOJO "+servicePOJO+" already online?!"); return; } // translate sensor to IoT types synchronized(adapters){ for(ServiceAdapter adapter : adapters){ try { // ADAPT! final Object so = adapter.getServiceObject(servicePOJO); final String device = servicePOJO.getService().getOriginalDevice().getName().toString(); final String service = servicePOJO.getService().getName().toString(); final UUID thingId = UUID.nameUUIDFromBytes((device+service).getBytes()); final Dictionary<String, Object> properties = new Hashtable<String, Object>();
// Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/ChangeEvent.java // public class ChangeEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public String stateVariable; /* state variable that changed */ // public Object stateValue; /* new value of the state variable */ // public long timestamp; /* timestamp the event was generated */ // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/OfflineEvent.java // public class OfflineEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public long timestamp; /* timestamp the event was generated */ // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/OnlineEvent.java // public class OnlineEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public String service; /* service of the thing */ // public String device; /* device name of the thing */ // public String type; /* thing type */ // public long timestamp; /* timestamp the event was generated */ // // } // Path: be.iminds.iot.things.dyamand.adapter/src/be/iminds/iot/things/dyamand/adapter/DyamandAdapter.java import java.util.ArrayList; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.UUID; import org.dyamand.event.Event; import org.dyamand.event.EventListener; import org.dyamand.event.ServicePOJOOfflineEvent; import org.dyamand.event.ServicePOJOOnlineEvent; import org.dyamand.event.StateChangedEvent; import org.dyamand.service.ServicePOJO; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.event.EventAdmin; import org.osgi.service.event.EventProperties; import osgi.enroute.dto.api.DTOs; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.api.event.ChangeEvent; import be.iminds.iot.things.api.event.OfflineEvent; import be.iminds.iot.things.api.event.OnlineEvent; this.servicePojoOnline(servicePOJO); } else if (event instanceof ServicePOJOOfflineEvent) { final ServicePOJO servicePOJO = ((ServicePOJOOfflineEvent) event) .getServicePOJO(); this.servicePojoOffline(servicePOJO); } else if (event instanceof StateChangedEvent) { final org.dyamand.service.StateChange stateChange = ((StateChangedEvent) event) .getStateChange(); this.processStateChange(stateChange); } } private void servicePojoOnline(final ServicePOJO servicePOJO) { if(this.services.get(servicePOJO)!=null){ System.err.println("ServicePOJO "+servicePOJO+" already online?!"); return; } // translate sensor to IoT types synchronized(adapters){ for(ServiceAdapter adapter : adapters){ try { // ADAPT! final Object so = adapter.getServiceObject(servicePOJO); final String device = servicePOJO.getService().getOriginalDevice().getName().toString(); final String service = servicePOJO.getService().getName().toString(); final UUID thingId = UUID.nameUUIDFromBytes((device+service).getBytes()); final Dictionary<String, Object> properties = new Hashtable<String, Object>();
properties.put(Thing.ID, thingId.toString());
ibcn-cloudlet/firefly
be.iminds.iot.things.dyamand.adapter/src/be/iminds/iot/things/dyamand/adapter/DyamandAdapter.java
// Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/ChangeEvent.java // public class ChangeEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public String stateVariable; /* state variable that changed */ // public Object stateValue; /* new value of the state variable */ // public long timestamp; /* timestamp the event was generated */ // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/OfflineEvent.java // public class OfflineEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public long timestamp; /* timestamp the event was generated */ // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/OnlineEvent.java // public class OnlineEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public String service; /* service of the thing */ // public String device; /* device name of the thing */ // public String type; /* thing type */ // public long timestamp; /* timestamp the event was generated */ // // }
import java.util.ArrayList; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.UUID; import org.dyamand.event.Event; import org.dyamand.event.EventListener; import org.dyamand.event.ServicePOJOOfflineEvent; import org.dyamand.event.ServicePOJOOnlineEvent; import org.dyamand.event.StateChangedEvent; import org.dyamand.service.ServicePOJO; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.event.EventAdmin; import org.osgi.service.event.EventProperties; import osgi.enroute.dto.api.DTOs; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.api.event.ChangeEvent; import be.iminds.iot.things.api.event.OfflineEvent; import be.iminds.iot.things.api.event.OnlineEvent;
private void processStateChange( final org.dyamand.service.StateChange stateChange) { final String device = stateChange.getService().getOriginalDevice().getName().toString(); final String service = stateChange.getService().getName().toString(); final UUID thingId = UUID.nameUUIDFromBytes((device+service).getBytes()); final String stateVariable = stateChange.getStateVariable().toString(); final Object value = stateChange.getValue(); synchronized(adapters){ for (final ServiceAdapter adapter : this.adapters) { try { final StateVariable translated = adapter .translateStateVariable(stateVariable, value); this.notifiyStateChange(thingId, translated.getName(), translated.getValue()); } catch (final Exception e) { } } } } private void notifyOnline( final UUID thingId, final String device, final String service, final String type){ try {
// Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/ChangeEvent.java // public class ChangeEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public String stateVariable; /* state variable that changed */ // public Object stateValue; /* new value of the state variable */ // public long timestamp; /* timestamp the event was generated */ // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/OfflineEvent.java // public class OfflineEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public long timestamp; /* timestamp the event was generated */ // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/OnlineEvent.java // public class OnlineEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public String service; /* service of the thing */ // public String device; /* device name of the thing */ // public String type; /* thing type */ // public long timestamp; /* timestamp the event was generated */ // // } // Path: be.iminds.iot.things.dyamand.adapter/src/be/iminds/iot/things/dyamand/adapter/DyamandAdapter.java import java.util.ArrayList; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.UUID; import org.dyamand.event.Event; import org.dyamand.event.EventListener; import org.dyamand.event.ServicePOJOOfflineEvent; import org.dyamand.event.ServicePOJOOnlineEvent; import org.dyamand.event.StateChangedEvent; import org.dyamand.service.ServicePOJO; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.event.EventAdmin; import org.osgi.service.event.EventProperties; import osgi.enroute.dto.api.DTOs; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.api.event.ChangeEvent; import be.iminds.iot.things.api.event.OfflineEvent; import be.iminds.iot.things.api.event.OnlineEvent; private void processStateChange( final org.dyamand.service.StateChange stateChange) { final String device = stateChange.getService().getOriginalDevice().getName().toString(); final String service = stateChange.getService().getName().toString(); final UUID thingId = UUID.nameUUIDFromBytes((device+service).getBytes()); final String stateVariable = stateChange.getStateVariable().toString(); final Object value = stateChange.getValue(); synchronized(adapters){ for (final ServiceAdapter adapter : this.adapters) { try { final StateVariable translated = adapter .translateStateVariable(stateVariable, value); this.notifiyStateChange(thingId, translated.getName(), translated.getValue()); } catch (final Exception e) { } } } } private void notifyOnline( final UUID thingId, final String device, final String service, final String type){ try {
OnlineEvent e = new OnlineEvent();
ibcn-cloudlet/firefly
be.iminds.iot.things.dyamand.adapter/src/be/iminds/iot/things/dyamand/adapter/DyamandAdapter.java
// Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/ChangeEvent.java // public class ChangeEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public String stateVariable; /* state variable that changed */ // public Object stateValue; /* new value of the state variable */ // public long timestamp; /* timestamp the event was generated */ // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/OfflineEvent.java // public class OfflineEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public long timestamp; /* timestamp the event was generated */ // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/OnlineEvent.java // public class OnlineEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public String service; /* service of the thing */ // public String device; /* device name of the thing */ // public String type; /* thing type */ // public long timestamp; /* timestamp the event was generated */ // // }
import java.util.ArrayList; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.UUID; import org.dyamand.event.Event; import org.dyamand.event.EventListener; import org.dyamand.event.ServicePOJOOfflineEvent; import org.dyamand.event.ServicePOJOOnlineEvent; import org.dyamand.event.StateChangedEvent; import org.dyamand.service.ServicePOJO; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.event.EventAdmin; import org.osgi.service.event.EventProperties; import osgi.enroute.dto.api.DTOs; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.api.event.ChangeEvent; import be.iminds.iot.things.api.event.OfflineEvent; import be.iminds.iot.things.api.event.OnlineEvent;
} catch (final Exception e) { } } } } private void notifyOnline( final UUID thingId, final String device, final String service, final String type){ try { OnlineEvent e = new OnlineEvent(); e.thingId = thingId; e.gatewayId = gatewayId; e.service = service; e.device = device; e.type = type; e.timestamp = System.currentTimeMillis(); final String topic = "be/iminds/iot/thing/online/"+thingId; ea.sendEvent(new org.osgi.service.event.Event(topic, dtos.asMap(e))); } catch(Exception e){ System.err.println("Error sending online event "+e); } } private void notifyOffline( final UUID thingId){ try {
// Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/ChangeEvent.java // public class ChangeEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public String stateVariable; /* state variable that changed */ // public Object stateValue; /* new value of the state variable */ // public long timestamp; /* timestamp the event was generated */ // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/OfflineEvent.java // public class OfflineEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public long timestamp; /* timestamp the event was generated */ // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/OnlineEvent.java // public class OnlineEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public String service; /* service of the thing */ // public String device; /* device name of the thing */ // public String type; /* thing type */ // public long timestamp; /* timestamp the event was generated */ // // } // Path: be.iminds.iot.things.dyamand.adapter/src/be/iminds/iot/things/dyamand/adapter/DyamandAdapter.java import java.util.ArrayList; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.UUID; import org.dyamand.event.Event; import org.dyamand.event.EventListener; import org.dyamand.event.ServicePOJOOfflineEvent; import org.dyamand.event.ServicePOJOOnlineEvent; import org.dyamand.event.StateChangedEvent; import org.dyamand.service.ServicePOJO; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.event.EventAdmin; import org.osgi.service.event.EventProperties; import osgi.enroute.dto.api.DTOs; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.api.event.ChangeEvent; import be.iminds.iot.things.api.event.OfflineEvent; import be.iminds.iot.things.api.event.OnlineEvent; } catch (final Exception e) { } } } } private void notifyOnline( final UUID thingId, final String device, final String service, final String type){ try { OnlineEvent e = new OnlineEvent(); e.thingId = thingId; e.gatewayId = gatewayId; e.service = service; e.device = device; e.type = type; e.timestamp = System.currentTimeMillis(); final String topic = "be/iminds/iot/thing/online/"+thingId; ea.sendEvent(new org.osgi.service.event.Event(topic, dtos.asMap(e))); } catch(Exception e){ System.err.println("Error sending online event "+e); } } private void notifyOffline( final UUID thingId){ try {
OfflineEvent e = new OfflineEvent();
ibcn-cloudlet/firefly
be.iminds.iot.things.dyamand.adapter/src/be/iminds/iot/things/dyamand/adapter/DyamandAdapter.java
// Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/ChangeEvent.java // public class ChangeEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public String stateVariable; /* state variable that changed */ // public Object stateValue; /* new value of the state variable */ // public long timestamp; /* timestamp the event was generated */ // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/OfflineEvent.java // public class OfflineEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public long timestamp; /* timestamp the event was generated */ // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/OnlineEvent.java // public class OnlineEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public String service; /* service of the thing */ // public String device; /* device name of the thing */ // public String type; /* thing type */ // public long timestamp; /* timestamp the event was generated */ // // }
import java.util.ArrayList; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.UUID; import org.dyamand.event.Event; import org.dyamand.event.EventListener; import org.dyamand.event.ServicePOJOOfflineEvent; import org.dyamand.event.ServicePOJOOnlineEvent; import org.dyamand.event.StateChangedEvent; import org.dyamand.service.ServicePOJO; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.event.EventAdmin; import org.osgi.service.event.EventProperties; import osgi.enroute.dto.api.DTOs; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.api.event.ChangeEvent; import be.iminds.iot.things.api.event.OfflineEvent; import be.iminds.iot.things.api.event.OnlineEvent;
e.type = type; e.timestamp = System.currentTimeMillis(); final String topic = "be/iminds/iot/thing/online/"+thingId; ea.sendEvent(new org.osgi.service.event.Event(topic, dtos.asMap(e))); } catch(Exception e){ System.err.println("Error sending online event "+e); } } private void notifyOffline( final UUID thingId){ try { OfflineEvent e = new OfflineEvent(); e.thingId = thingId; e.gatewayId = gatewayId; e.timestamp = System.currentTimeMillis(); final String topic = "be/iminds/iot/thing/offline/"+thingId; ea.sendEvent(new org.osgi.service.event.Event(topic, dtos.asMap(e))); } catch(Exception e){ System.err.println("Error sending offline event "+e); } } private void notifiyStateChange( final UUID thingId, final String stateVariable, final Object stateValue){ try {
// Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/ChangeEvent.java // public class ChangeEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public String stateVariable; /* state variable that changed */ // public Object stateValue; /* new value of the state variable */ // public long timestamp; /* timestamp the event was generated */ // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/OfflineEvent.java // public class OfflineEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public long timestamp; /* timestamp the event was generated */ // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/event/OnlineEvent.java // public class OnlineEvent { // // public UUID thingId; /* id of the thing */ // public UUID gatewayId; /* gateway that published the event */ // public String service; /* service of the thing */ // public String device; /* device name of the thing */ // public String type; /* thing type */ // public long timestamp; /* timestamp the event was generated */ // // } // Path: be.iminds.iot.things.dyamand.adapter/src/be/iminds/iot/things/dyamand/adapter/DyamandAdapter.java import java.util.ArrayList; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.UUID; import org.dyamand.event.Event; import org.dyamand.event.EventListener; import org.dyamand.event.ServicePOJOOfflineEvent; import org.dyamand.event.ServicePOJOOnlineEvent; import org.dyamand.event.StateChangedEvent; import org.dyamand.service.ServicePOJO; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.event.EventAdmin; import org.osgi.service.event.EventProperties; import osgi.enroute.dto.api.DTOs; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.api.event.ChangeEvent; import be.iminds.iot.things.api.event.OfflineEvent; import be.iminds.iot.things.api.event.OnlineEvent; e.type = type; e.timestamp = System.currentTimeMillis(); final String topic = "be/iminds/iot/thing/online/"+thingId; ea.sendEvent(new org.osgi.service.event.Event(topic, dtos.asMap(e))); } catch(Exception e){ System.err.println("Error sending online event "+e); } } private void notifyOffline( final UUID thingId){ try { OfflineEvent e = new OfflineEvent(); e.thingId = thingId; e.gatewayId = gatewayId; e.timestamp = System.currentTimeMillis(); final String topic = "be/iminds/iot/thing/offline/"+thingId; ea.sendEvent(new org.osgi.service.event.Event(topic, dtos.asMap(e))); } catch(Exception e){ System.err.println("Error sending offline event "+e); } } private void notifiyStateChange( final UUID thingId, final String stateVariable, final Object stateValue){ try {
ChangeEvent e = new ChangeEvent();
ibcn-cloudlet/firefly
be.iminds.iot.firefly.dashboard.application/src/be/iminds/iot/firefly/dashboard/actions/LampActions.java
// Path: be.iminds.iot.firefly.dashboard.application/src/be/iminds/iot/firefly/dashboard/Actions.java // public interface Actions { // // public String getType(); // // public void action(UUID id, String ... params); // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/lamp/Lamp.java // public interface Lamp extends Thing { // // public final static String STATE = "state"; // public final static String LEVEL = "level"; // public final static String COLOR = "color"; // // // public static enum State { // OFF, ON; // } // // public State getState(); // // public void on(); // // public void off(); // // public void toggle(); // // public int getLevel(); // // public void setLevel(final int level); // // public void incrementLevel(final int increment); // // public void decrementLevel(final int decrement); // // public Color getColor(); // // public void setColor(Color c); // // }
import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import be.iminds.iot.firefly.dashboard.Actions; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.api.lamp.Lamp; import java.awt.Color;
/******************************************************************************* * Copyright (c) 2015, Tim Verbelen * Internet Based Communication Networks and Services research group (IBCN), * Department of Information Technology (INTEC), Ghent University - iMinds. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Ghent University - iMinds, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package be.iminds.iot.firefly.dashboard.actions; @Component(property={"aiolos.proxy=false"}) public class LampActions implements Actions {
// Path: be.iminds.iot.firefly.dashboard.application/src/be/iminds/iot/firefly/dashboard/Actions.java // public interface Actions { // // public String getType(); // // public void action(UUID id, String ... params); // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/lamp/Lamp.java // public interface Lamp extends Thing { // // public final static String STATE = "state"; // public final static String LEVEL = "level"; // public final static String COLOR = "color"; // // // public static enum State { // OFF, ON; // } // // public State getState(); // // public void on(); // // public void off(); // // public void toggle(); // // public int getLevel(); // // public void setLevel(final int level); // // public void incrementLevel(final int increment); // // public void decrementLevel(final int decrement); // // public Color getColor(); // // public void setColor(Color c); // // } // Path: be.iminds.iot.firefly.dashboard.application/src/be/iminds/iot/firefly/dashboard/actions/LampActions.java import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import be.iminds.iot.firefly.dashboard.Actions; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.api.lamp.Lamp; import java.awt.Color; /******************************************************************************* * Copyright (c) 2015, Tim Verbelen * Internet Based Communication Networks and Services research group (IBCN), * Department of Information Technology (INTEC), Ghent University - iMinds. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Ghent University - iMinds, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package be.iminds.iot.firefly.dashboard.actions; @Component(property={"aiolos.proxy=false"}) public class LampActions implements Actions {
private Map<UUID, Lamp> lamps = Collections.synchronizedMap(new HashMap<UUID, Lamp>());
ibcn-cloudlet/firefly
be.iminds.iot.firefly.dashboard.application/src/be/iminds/iot/firefly/dashboard/actions/LampActions.java
// Path: be.iminds.iot.firefly.dashboard.application/src/be/iminds/iot/firefly/dashboard/Actions.java // public interface Actions { // // public String getType(); // // public void action(UUID id, String ... params); // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/lamp/Lamp.java // public interface Lamp extends Thing { // // public final static String STATE = "state"; // public final static String LEVEL = "level"; // public final static String COLOR = "color"; // // // public static enum State { // OFF, ON; // } // // public State getState(); // // public void on(); // // public void off(); // // public void toggle(); // // public int getLevel(); // // public void setLevel(final int level); // // public void incrementLevel(final int increment); // // public void decrementLevel(final int decrement); // // public Color getColor(); // // public void setColor(Color c); // // }
import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import be.iminds.iot.firefly.dashboard.Actions; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.api.lamp.Lamp; import java.awt.Color;
/******************************************************************************* * Copyright (c) 2015, Tim Verbelen * Internet Based Communication Networks and Services research group (IBCN), * Department of Information Technology (INTEC), Ghent University - iMinds. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Ghent University - iMinds, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package be.iminds.iot.firefly.dashboard.actions; @Component(property={"aiolos.proxy=false"}) public class LampActions implements Actions { private Map<UUID, Lamp> lamps = Collections.synchronizedMap(new HashMap<UUID, Lamp>()); @Override public String getType() { return "lamp"; } @Override public void action(UUID id, String... params) { Lamp lamp = lamps.get(id); if(lamp!=null){ if(params.length==0){ // default action - switch on/off lamp.toggle(); } else { switch(params[0]){ case "level": lamp.setLevel(Integer.parseInt(params[1])); break; case "color": Color c = Color.decode(params[1]); lamp.setColor(c); break; } } } } @Reference(cardinality=ReferenceCardinality.MULTIPLE, policy=ReferencePolicy.DYNAMIC) public void addLamp(Lamp l, Map<String, Object> properties){
// Path: be.iminds.iot.firefly.dashboard.application/src/be/iminds/iot/firefly/dashboard/Actions.java // public interface Actions { // // public String getType(); // // public void action(UUID id, String ... params); // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/lamp/Lamp.java // public interface Lamp extends Thing { // // public final static String STATE = "state"; // public final static String LEVEL = "level"; // public final static String COLOR = "color"; // // // public static enum State { // OFF, ON; // } // // public State getState(); // // public void on(); // // public void off(); // // public void toggle(); // // public int getLevel(); // // public void setLevel(final int level); // // public void incrementLevel(final int increment); // // public void decrementLevel(final int decrement); // // public Color getColor(); // // public void setColor(Color c); // // } // Path: be.iminds.iot.firefly.dashboard.application/src/be/iminds/iot/firefly/dashboard/actions/LampActions.java import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import be.iminds.iot.firefly.dashboard.Actions; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.api.lamp.Lamp; import java.awt.Color; /******************************************************************************* * Copyright (c) 2015, Tim Verbelen * Internet Based Communication Networks and Services research group (IBCN), * Department of Information Technology (INTEC), Ghent University - iMinds. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Ghent University - iMinds, nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package be.iminds.iot.firefly.dashboard.actions; @Component(property={"aiolos.proxy=false"}) public class LampActions implements Actions { private Map<UUID, Lamp> lamps = Collections.synchronizedMap(new HashMap<UUID, Lamp>()); @Override public String getType() { return "lamp"; } @Override public void action(UUID id, String... params) { Lamp lamp = lamps.get(id); if(lamp!=null){ if(params.length==0){ // default action - switch on/off lamp.toggle(); } else { switch(params[0]){ case "level": lamp.setLevel(Integer.parseInt(params[1])); break; case "color": Color c = Color.decode(params[1]); lamp.setColor(c); break; } } } } @Reference(cardinality=ReferenceCardinality.MULTIPLE, policy=ReferencePolicy.DYNAMIC) public void addLamp(Lamp l, Map<String, Object> properties){
UUID id = UUID.fromString((String)properties.get(Thing.ID));
ibcn-cloudlet/firefly
be.iminds.iot.firefly.dashboard.application/src/be/iminds/iot/firefly/dashboard/actions/CameraActions.java
// Path: be.iminds.iot.firefly.dashboard.application/src/be/iminds/iot/firefly/dashboard/Actions.java // public interface Actions { // // public String getType(); // // public void action(UUID id, String ... params); // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/camera/Camera.java // public interface Camera extends Thing { // // public final static String STATE = "state"; // // public static enum State { // OFF, RECORDING; // } // // public static enum Format { // YUV, RGB, GRAYSCALE, MJPEG; // } // // /** // * Get the state of the camera // * // * @return state of the camera // */ // public State getState(); // // /** // * Return boolean if the camera is on // */ // public boolean isOn(); // // /** // * Get the width of the frames the camera is fetching // * // * @return frame width or -1 if not initialized // */ // public int getWidth(); // // /** // * Get the height of the frames the camera is fetching // * // * @return frame height or -1 if not initialized // */ // public int getHeight(); // // /** // * Get the current capturing format // * // * @return frame format // */ // public Format getFormat(); // // /** // * Return the framerate (frames per second) that is aimed for when having a CameraListener // * // * @return framerate // */ // public float getFramerate(); // // /** // * Set framerate // * // * @param f framerate to set // */ // public void setFramerate(float f); // // /** // * Return the latest camera frame when the camera is turned on // * @return byte array in the camera's current format // */ // public byte[] getFrame(); // // /** // * Turn the camera on // */ // public void start(); // // /** // * Turn the camera on with preferred width,height capture ratio // * // * @param width // * @param height // */ // public void start(int width, int height, Format format); // // /** // * Stop capturing // */ // public void stop(); // // /** // * Toggle // */ // public void toggle(); // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/camera/Camera.java // public static enum Format { // YUV, RGB, GRAYSCALE, MJPEG; // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/camera/CameraListener.java // public interface CameraListener { // // public final static String CAMERA_ID = "be.iminds.iot.thing.camera.id"; // public final static String CAMERA_FORMAT = "be.iminds.iot.thing.camera.format"; // // public void nextFrame(UUID id, Format format, byte[] data); // // }
import java.io.IOException; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.UUID; import javax.servlet.AsyncContext; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.http.whiteboard.HttpWhiteboardConstants; import osgi.enroute.http.capabilities.RequireHttpImplementation; import aQute.lib.collections.MultiMap; import be.iminds.iot.firefly.dashboard.Actions; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.api.camera.Camera; import be.iminds.iot.things.api.camera.Camera.Format; import be.iminds.iot.things.api.camera.CameraListener;
response.setContentType("multipart/x-mixed-replace;boundary=next"); // check if there is already a stream for this client String client = request.getRemoteHost()+":"+request.getRemotePort(); CameraStream stream = streamsByClient.get(client); if(stream==null){ stream = new CameraStream(id, client); synchronized(streamsByCameraId){ streamsByCameraId.add(id, stream); streamsByClient.put(client, stream); } } stream.updateRequest(request); // if not yet a stream for this id, register CameraListener service if(!listenerRegistrations.containsKey(id)){ Dictionary<String, Object> properties = new Hashtable<>(); properties.put("aiolos.unique", true); properties.put("be.iminds.iot.thing.camera.id", id.toString()); ServiceRegistration r = context.registerService(CameraListener.class, this, properties); listenerRegistrations.put(id, r); } } @Reference(cardinality=ReferenceCardinality.MULTIPLE, policy=ReferencePolicy.DYNAMIC) public void addCamera(Camera c, Map<String, Object> properties){
// Path: be.iminds.iot.firefly.dashboard.application/src/be/iminds/iot/firefly/dashboard/Actions.java // public interface Actions { // // public String getType(); // // public void action(UUID id, String ... params); // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/camera/Camera.java // public interface Camera extends Thing { // // public final static String STATE = "state"; // // public static enum State { // OFF, RECORDING; // } // // public static enum Format { // YUV, RGB, GRAYSCALE, MJPEG; // } // // /** // * Get the state of the camera // * // * @return state of the camera // */ // public State getState(); // // /** // * Return boolean if the camera is on // */ // public boolean isOn(); // // /** // * Get the width of the frames the camera is fetching // * // * @return frame width or -1 if not initialized // */ // public int getWidth(); // // /** // * Get the height of the frames the camera is fetching // * // * @return frame height or -1 if not initialized // */ // public int getHeight(); // // /** // * Get the current capturing format // * // * @return frame format // */ // public Format getFormat(); // // /** // * Return the framerate (frames per second) that is aimed for when having a CameraListener // * // * @return framerate // */ // public float getFramerate(); // // /** // * Set framerate // * // * @param f framerate to set // */ // public void setFramerate(float f); // // /** // * Return the latest camera frame when the camera is turned on // * @return byte array in the camera's current format // */ // public byte[] getFrame(); // // /** // * Turn the camera on // */ // public void start(); // // /** // * Turn the camera on with preferred width,height capture ratio // * // * @param width // * @param height // */ // public void start(int width, int height, Format format); // // /** // * Stop capturing // */ // public void stop(); // // /** // * Toggle // */ // public void toggle(); // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/camera/Camera.java // public static enum Format { // YUV, RGB, GRAYSCALE, MJPEG; // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/camera/CameraListener.java // public interface CameraListener { // // public final static String CAMERA_ID = "be.iminds.iot.thing.camera.id"; // public final static String CAMERA_FORMAT = "be.iminds.iot.thing.camera.format"; // // public void nextFrame(UUID id, Format format, byte[] data); // // } // Path: be.iminds.iot.firefly.dashboard.application/src/be/iminds/iot/firefly/dashboard/actions/CameraActions.java import java.io.IOException; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.UUID; import javax.servlet.AsyncContext; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.http.whiteboard.HttpWhiteboardConstants; import osgi.enroute.http.capabilities.RequireHttpImplementation; import aQute.lib.collections.MultiMap; import be.iminds.iot.firefly.dashboard.Actions; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.api.camera.Camera; import be.iminds.iot.things.api.camera.Camera.Format; import be.iminds.iot.things.api.camera.CameraListener; response.setContentType("multipart/x-mixed-replace;boundary=next"); // check if there is already a stream for this client String client = request.getRemoteHost()+":"+request.getRemotePort(); CameraStream stream = streamsByClient.get(client); if(stream==null){ stream = new CameraStream(id, client); synchronized(streamsByCameraId){ streamsByCameraId.add(id, stream); streamsByClient.put(client, stream); } } stream.updateRequest(request); // if not yet a stream for this id, register CameraListener service if(!listenerRegistrations.containsKey(id)){ Dictionary<String, Object> properties = new Hashtable<>(); properties.put("aiolos.unique", true); properties.put("be.iminds.iot.thing.camera.id", id.toString()); ServiceRegistration r = context.registerService(CameraListener.class, this, properties); listenerRegistrations.put(id, r); } } @Reference(cardinality=ReferenceCardinality.MULTIPLE, policy=ReferencePolicy.DYNAMIC) public void addCamera(Camera c, Map<String, Object> properties){
UUID id = UUID.fromString((String)properties.get(Thing.ID));
ibcn-cloudlet/firefly
be.iminds.iot.firefly.dashboard.application/src/be/iminds/iot/firefly/dashboard/actions/CameraActions.java
// Path: be.iminds.iot.firefly.dashboard.application/src/be/iminds/iot/firefly/dashboard/Actions.java // public interface Actions { // // public String getType(); // // public void action(UUID id, String ... params); // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/camera/Camera.java // public interface Camera extends Thing { // // public final static String STATE = "state"; // // public static enum State { // OFF, RECORDING; // } // // public static enum Format { // YUV, RGB, GRAYSCALE, MJPEG; // } // // /** // * Get the state of the camera // * // * @return state of the camera // */ // public State getState(); // // /** // * Return boolean if the camera is on // */ // public boolean isOn(); // // /** // * Get the width of the frames the camera is fetching // * // * @return frame width or -1 if not initialized // */ // public int getWidth(); // // /** // * Get the height of the frames the camera is fetching // * // * @return frame height or -1 if not initialized // */ // public int getHeight(); // // /** // * Get the current capturing format // * // * @return frame format // */ // public Format getFormat(); // // /** // * Return the framerate (frames per second) that is aimed for when having a CameraListener // * // * @return framerate // */ // public float getFramerate(); // // /** // * Set framerate // * // * @param f framerate to set // */ // public void setFramerate(float f); // // /** // * Return the latest camera frame when the camera is turned on // * @return byte array in the camera's current format // */ // public byte[] getFrame(); // // /** // * Turn the camera on // */ // public void start(); // // /** // * Turn the camera on with preferred width,height capture ratio // * // * @param width // * @param height // */ // public void start(int width, int height, Format format); // // /** // * Stop capturing // */ // public void stop(); // // /** // * Toggle // */ // public void toggle(); // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/camera/Camera.java // public static enum Format { // YUV, RGB, GRAYSCALE, MJPEG; // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/camera/CameraListener.java // public interface CameraListener { // // public final static String CAMERA_ID = "be.iminds.iot.thing.camera.id"; // public final static String CAMERA_FORMAT = "be.iminds.iot.thing.camera.format"; // // public void nextFrame(UUID id, Format format, byte[] data); // // }
import java.io.IOException; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.UUID; import javax.servlet.AsyncContext; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.http.whiteboard.HttpWhiteboardConstants; import osgi.enroute.http.capabilities.RequireHttpImplementation; import aQute.lib.collections.MultiMap; import be.iminds.iot.firefly.dashboard.Actions; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.api.camera.Camera; import be.iminds.iot.things.api.camera.Camera.Format; import be.iminds.iot.things.api.camera.CameraListener;
} } stream.updateRequest(request); // if not yet a stream for this id, register CameraListener service if(!listenerRegistrations.containsKey(id)){ Dictionary<String, Object> properties = new Hashtable<>(); properties.put("aiolos.unique", true); properties.put("be.iminds.iot.thing.camera.id", id.toString()); ServiceRegistration r = context.registerService(CameraListener.class, this, properties); listenerRegistrations.put(id, r); } } @Reference(cardinality=ReferenceCardinality.MULTIPLE, policy=ReferencePolicy.DYNAMIC) public void addCamera(Camera c, Map<String, Object> properties){ UUID id = UUID.fromString((String)properties.get(Thing.ID)); cameras.put(id, c); } public void removeCamera(Camera c, Map<String, Object> properties){ UUID id = UUID.fromString((String)properties.get(Thing.ID)); cameras.remove(id); } @Override
// Path: be.iminds.iot.firefly.dashboard.application/src/be/iminds/iot/firefly/dashboard/Actions.java // public interface Actions { // // public String getType(); // // public void action(UUID id, String ... params); // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/Thing.java // public interface Thing { // // public final static String ID = "thing.id"; // public final static String DEVICE = "thing.device"; // public final static String SERVICE = "thing.service"; // public final static String GATEWAY = "thing.gateway"; // public final static String TYPE = "thing.type"; // // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/camera/Camera.java // public interface Camera extends Thing { // // public final static String STATE = "state"; // // public static enum State { // OFF, RECORDING; // } // // public static enum Format { // YUV, RGB, GRAYSCALE, MJPEG; // } // // /** // * Get the state of the camera // * // * @return state of the camera // */ // public State getState(); // // /** // * Return boolean if the camera is on // */ // public boolean isOn(); // // /** // * Get the width of the frames the camera is fetching // * // * @return frame width or -1 if not initialized // */ // public int getWidth(); // // /** // * Get the height of the frames the camera is fetching // * // * @return frame height or -1 if not initialized // */ // public int getHeight(); // // /** // * Get the current capturing format // * // * @return frame format // */ // public Format getFormat(); // // /** // * Return the framerate (frames per second) that is aimed for when having a CameraListener // * // * @return framerate // */ // public float getFramerate(); // // /** // * Set framerate // * // * @param f framerate to set // */ // public void setFramerate(float f); // // /** // * Return the latest camera frame when the camera is turned on // * @return byte array in the camera's current format // */ // public byte[] getFrame(); // // /** // * Turn the camera on // */ // public void start(); // // /** // * Turn the camera on with preferred width,height capture ratio // * // * @param width // * @param height // */ // public void start(int width, int height, Format format); // // /** // * Stop capturing // */ // public void stop(); // // /** // * Toggle // */ // public void toggle(); // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/camera/Camera.java // public static enum Format { // YUV, RGB, GRAYSCALE, MJPEG; // } // // Path: be.iminds.iot.things.api/src/be/iminds/iot/things/api/camera/CameraListener.java // public interface CameraListener { // // public final static String CAMERA_ID = "be.iminds.iot.thing.camera.id"; // public final static String CAMERA_FORMAT = "be.iminds.iot.thing.camera.format"; // // public void nextFrame(UUID id, Format format, byte[] data); // // } // Path: be.iminds.iot.firefly.dashboard.application/src/be/iminds/iot/firefly/dashboard/actions/CameraActions.java import java.io.IOException; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.UUID; import javax.servlet.AsyncContext; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.http.whiteboard.HttpWhiteboardConstants; import osgi.enroute.http.capabilities.RequireHttpImplementation; import aQute.lib.collections.MultiMap; import be.iminds.iot.firefly.dashboard.Actions; import be.iminds.iot.things.api.Thing; import be.iminds.iot.things.api.camera.Camera; import be.iminds.iot.things.api.camera.Camera.Format; import be.iminds.iot.things.api.camera.CameraListener; } } stream.updateRequest(request); // if not yet a stream for this id, register CameraListener service if(!listenerRegistrations.containsKey(id)){ Dictionary<String, Object> properties = new Hashtable<>(); properties.put("aiolos.unique", true); properties.put("be.iminds.iot.thing.camera.id", id.toString()); ServiceRegistration r = context.registerService(CameraListener.class, this, properties); listenerRegistrations.put(id, r); } } @Reference(cardinality=ReferenceCardinality.MULTIPLE, policy=ReferencePolicy.DYNAMIC) public void addCamera(Camera c, Map<String, Object> properties){ UUID id = UUID.fromString((String)properties.get(Thing.ID)); cameras.put(id, c); } public void removeCamera(Camera c, Map<String, Object> properties){ UUID id = UUID.fromString((String)properties.get(Thing.ID)); cameras.remove(id); } @Override
public void nextFrame(UUID id, Format format, byte[] data) {
leifj/saml-md-aggregator
src/main/java/net/nordu/mdx/store/git/GitRepositoryMetadataStore.java
// Path: src/main/java/net/nordu/mdx/scanner/MetadataChange.java // public class MetadataChange implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6750830823194935907L; // // private String id; // private String reason; // private Date timeStamp; // private MetadataChangeType type; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public Date getTimeStamp() { // return timeStamp; // } // // public void setTimeStamp(Date timeStamp) { // this.timeStamp = timeStamp; // } // // public MetadataChangeType getType() { // return type; // } // // public void setType(MetadataChangeType type) { // this.type = type; // } // // public String toString() { // return "EntityDescriptor["+id+"] changed: "+timeStamp+", "+type+(reason == null ? "" : ": "+reason); // } // // public MetadataChange(String id, MetadataChangeType type, String reason, Date timeStamp) { // this.id = id; // this.type = type; // this.reason = reason; // this.timeStamp = timeStamp; // } // // public MetadataChange(String id, MetadataChangeType type, String reason) { // this(id,type,reason,new Date()); // } // // public MetadataChange(String id, MetadataChangeType type) { // this(id,type,null,new Date()); // } // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeType.java // public enum MetadataChangeType { // ADD, // REMOVE, // MODIFY, // CHATTR // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContext.java // public interface MetadataStoreContext extends Serializable { // // public MetadataIndex getIndex(); // public MetadataChangeNotifier getChangeNotifier(); // // } // // Path: src/main/java/net/nordu/mdx/store/fs/URLMetadataStoreContext.java // public class URLMetadataStoreContext extends MetadataStoreContextBase { // // /** // * // */ // private static final long serialVersionUID = 5358038794721104393L; // // private URL url; // // public URL getUrl() { // return url; // } // // public void setUrl(URL url) { // this.url = url; // } // // }
import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimerTask; import net.nordu.mdx.scanner.MetadataChange; import net.nordu.mdx.scanner.MetadataChangeType; import net.nordu.mdx.store.MetadataStore; import net.nordu.mdx.store.MetadataStoreContext; import net.nordu.mdx.store.fs.URLMetadataStoreContext; import org.eclipse.jgit.lib.Commit; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.MutableObjectId; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.oasis.saml.metadata.EntityDescriptorDocument; import org.oasis.saml.metadata.EntityDescriptorType;
package net.nordu.mdx.store.git; public class GitRepositoryMetadataStore implements MetadataStore { /** * Git branch to use (refs/heads/branchname). */ private String refName; /** * Object ID of the last HEAD. */ private ObjectId lastRef; /** * Git repository. */ private Repository repository; /** * Maps blobs to entity identifiers. */ private final Map<String, RepositoryEntry> blobMap;
// Path: src/main/java/net/nordu/mdx/scanner/MetadataChange.java // public class MetadataChange implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6750830823194935907L; // // private String id; // private String reason; // private Date timeStamp; // private MetadataChangeType type; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public Date getTimeStamp() { // return timeStamp; // } // // public void setTimeStamp(Date timeStamp) { // this.timeStamp = timeStamp; // } // // public MetadataChangeType getType() { // return type; // } // // public void setType(MetadataChangeType type) { // this.type = type; // } // // public String toString() { // return "EntityDescriptor["+id+"] changed: "+timeStamp+", "+type+(reason == null ? "" : ": "+reason); // } // // public MetadataChange(String id, MetadataChangeType type, String reason, Date timeStamp) { // this.id = id; // this.type = type; // this.reason = reason; // this.timeStamp = timeStamp; // } // // public MetadataChange(String id, MetadataChangeType type, String reason) { // this(id,type,reason,new Date()); // } // // public MetadataChange(String id, MetadataChangeType type) { // this(id,type,null,new Date()); // } // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeType.java // public enum MetadataChangeType { // ADD, // REMOVE, // MODIFY, // CHATTR // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContext.java // public interface MetadataStoreContext extends Serializable { // // public MetadataIndex getIndex(); // public MetadataChangeNotifier getChangeNotifier(); // // } // // Path: src/main/java/net/nordu/mdx/store/fs/URLMetadataStoreContext.java // public class URLMetadataStoreContext extends MetadataStoreContextBase { // // /** // * // */ // private static final long serialVersionUID = 5358038794721104393L; // // private URL url; // // public URL getUrl() { // return url; // } // // public void setUrl(URL url) { // this.url = url; // } // // } // Path: src/main/java/net/nordu/mdx/store/git/GitRepositoryMetadataStore.java import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimerTask; import net.nordu.mdx.scanner.MetadataChange; import net.nordu.mdx.scanner.MetadataChangeType; import net.nordu.mdx.store.MetadataStore; import net.nordu.mdx.store.MetadataStoreContext; import net.nordu.mdx.store.fs.URLMetadataStoreContext; import org.eclipse.jgit.lib.Commit; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.MutableObjectId; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.oasis.saml.metadata.EntityDescriptorDocument; import org.oasis.saml.metadata.EntityDescriptorType; package net.nordu.mdx.store.git; public class GitRepositoryMetadataStore implements MetadataStore { /** * Git branch to use (refs/heads/branchname). */ private String refName; /** * Object ID of the last HEAD. */ private ObjectId lastRef; /** * Git repository. */ private Repository repository; /** * Maps blobs to entity identifiers. */ private final Map<String, RepositoryEntry> blobMap;
private URLMetadataStoreContext context;
leifj/saml-md-aggregator
src/main/java/net/nordu/mdx/store/git/GitRepositoryMetadataStore.java
// Path: src/main/java/net/nordu/mdx/scanner/MetadataChange.java // public class MetadataChange implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6750830823194935907L; // // private String id; // private String reason; // private Date timeStamp; // private MetadataChangeType type; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public Date getTimeStamp() { // return timeStamp; // } // // public void setTimeStamp(Date timeStamp) { // this.timeStamp = timeStamp; // } // // public MetadataChangeType getType() { // return type; // } // // public void setType(MetadataChangeType type) { // this.type = type; // } // // public String toString() { // return "EntityDescriptor["+id+"] changed: "+timeStamp+", "+type+(reason == null ? "" : ": "+reason); // } // // public MetadataChange(String id, MetadataChangeType type, String reason, Date timeStamp) { // this.id = id; // this.type = type; // this.reason = reason; // this.timeStamp = timeStamp; // } // // public MetadataChange(String id, MetadataChangeType type, String reason) { // this(id,type,reason,new Date()); // } // // public MetadataChange(String id, MetadataChangeType type) { // this(id,type,null,new Date()); // } // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeType.java // public enum MetadataChangeType { // ADD, // REMOVE, // MODIFY, // CHATTR // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContext.java // public interface MetadataStoreContext extends Serializable { // // public MetadataIndex getIndex(); // public MetadataChangeNotifier getChangeNotifier(); // // } // // Path: src/main/java/net/nordu/mdx/store/fs/URLMetadataStoreContext.java // public class URLMetadataStoreContext extends MetadataStoreContextBase { // // /** // * // */ // private static final long serialVersionUID = 5358038794721104393L; // // private URL url; // // public URL getUrl() { // return url; // } // // public void setUrl(URL url) { // this.url = url; // } // // }
import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimerTask; import net.nordu.mdx.scanner.MetadataChange; import net.nordu.mdx.scanner.MetadataChangeType; import net.nordu.mdx.store.MetadataStore; import net.nordu.mdx.store.MetadataStoreContext; import net.nordu.mdx.store.fs.URLMetadataStoreContext; import org.eclipse.jgit.lib.Commit; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.MutableObjectId; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.oasis.saml.metadata.EntityDescriptorDocument; import org.oasis.saml.metadata.EntityDescriptorType;
package net.nordu.mdx.store.git; public class GitRepositoryMetadataStore implements MetadataStore { /** * Git branch to use (refs/heads/branchname). */ private String refName; /** * Object ID of the last HEAD. */ private ObjectId lastRef; /** * Git repository. */ private Repository repository; /** * Maps blobs to entity identifiers. */ private final Map<String, RepositoryEntry> blobMap; private URLMetadataStoreContext context; @Override
// Path: src/main/java/net/nordu/mdx/scanner/MetadataChange.java // public class MetadataChange implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6750830823194935907L; // // private String id; // private String reason; // private Date timeStamp; // private MetadataChangeType type; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public Date getTimeStamp() { // return timeStamp; // } // // public void setTimeStamp(Date timeStamp) { // this.timeStamp = timeStamp; // } // // public MetadataChangeType getType() { // return type; // } // // public void setType(MetadataChangeType type) { // this.type = type; // } // // public String toString() { // return "EntityDescriptor["+id+"] changed: "+timeStamp+", "+type+(reason == null ? "" : ": "+reason); // } // // public MetadataChange(String id, MetadataChangeType type, String reason, Date timeStamp) { // this.id = id; // this.type = type; // this.reason = reason; // this.timeStamp = timeStamp; // } // // public MetadataChange(String id, MetadataChangeType type, String reason) { // this(id,type,reason,new Date()); // } // // public MetadataChange(String id, MetadataChangeType type) { // this(id,type,null,new Date()); // } // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeType.java // public enum MetadataChangeType { // ADD, // REMOVE, // MODIFY, // CHATTR // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContext.java // public interface MetadataStoreContext extends Serializable { // // public MetadataIndex getIndex(); // public MetadataChangeNotifier getChangeNotifier(); // // } // // Path: src/main/java/net/nordu/mdx/store/fs/URLMetadataStoreContext.java // public class URLMetadataStoreContext extends MetadataStoreContextBase { // // /** // * // */ // private static final long serialVersionUID = 5358038794721104393L; // // private URL url; // // public URL getUrl() { // return url; // } // // public void setUrl(URL url) { // this.url = url; // } // // } // Path: src/main/java/net/nordu/mdx/store/git/GitRepositoryMetadataStore.java import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimerTask; import net.nordu.mdx.scanner.MetadataChange; import net.nordu.mdx.scanner.MetadataChangeType; import net.nordu.mdx.store.MetadataStore; import net.nordu.mdx.store.MetadataStoreContext; import net.nordu.mdx.store.fs.URLMetadataStoreContext; import org.eclipse.jgit.lib.Commit; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.MutableObjectId; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.oasis.saml.metadata.EntityDescriptorDocument; import org.oasis.saml.metadata.EntityDescriptorType; package net.nordu.mdx.store.git; public class GitRepositoryMetadataStore implements MetadataStore { /** * Git branch to use (refs/heads/branchname). */ private String refName; /** * Object ID of the last HEAD. */ private ObjectId lastRef; /** * Git repository. */ private Repository repository; /** * Maps blobs to entity identifiers. */ private final Map<String, RepositoryEntry> blobMap; private URLMetadataStoreContext context; @Override
public void setContext(MetadataStoreContext c) throws Exception {
leifj/saml-md-aggregator
src/main/java/net/nordu/mdx/store/git/GitRepositoryMetadataStore.java
// Path: src/main/java/net/nordu/mdx/scanner/MetadataChange.java // public class MetadataChange implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6750830823194935907L; // // private String id; // private String reason; // private Date timeStamp; // private MetadataChangeType type; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public Date getTimeStamp() { // return timeStamp; // } // // public void setTimeStamp(Date timeStamp) { // this.timeStamp = timeStamp; // } // // public MetadataChangeType getType() { // return type; // } // // public void setType(MetadataChangeType type) { // this.type = type; // } // // public String toString() { // return "EntityDescriptor["+id+"] changed: "+timeStamp+", "+type+(reason == null ? "" : ": "+reason); // } // // public MetadataChange(String id, MetadataChangeType type, String reason, Date timeStamp) { // this.id = id; // this.type = type; // this.reason = reason; // this.timeStamp = timeStamp; // } // // public MetadataChange(String id, MetadataChangeType type, String reason) { // this(id,type,reason,new Date()); // } // // public MetadataChange(String id, MetadataChangeType type) { // this(id,type,null,new Date()); // } // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeType.java // public enum MetadataChangeType { // ADD, // REMOVE, // MODIFY, // CHATTR // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContext.java // public interface MetadataStoreContext extends Serializable { // // public MetadataIndex getIndex(); // public MetadataChangeNotifier getChangeNotifier(); // // } // // Path: src/main/java/net/nordu/mdx/store/fs/URLMetadataStoreContext.java // public class URLMetadataStoreContext extends MetadataStoreContextBase { // // /** // * // */ // private static final long serialVersionUID = 5358038794721104393L; // // private URL url; // // public URL getUrl() { // return url; // } // // public void setUrl(URL url) { // this.url = url; // } // // }
import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimerTask; import net.nordu.mdx.scanner.MetadataChange; import net.nordu.mdx.scanner.MetadataChangeType; import net.nordu.mdx.store.MetadataStore; import net.nordu.mdx.store.MetadataStoreContext; import net.nordu.mdx.store.fs.URLMetadataStoreContext; import org.eclipse.jgit.lib.Commit; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.MutableObjectId; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.oasis.saml.metadata.EntityDescriptorDocument; import org.oasis.saml.metadata.EntityDescriptorType;
/** * Diff two trees, and emit metadata change notifications. * * @param oldTree * @param newTree * @param message * @param timeStamp * @throws IOException */ private void diffTrees(ObjectId oldTree, ObjectId newTree, String message, Date timeStamp) throws IOException { TreeWalk tw = new TreeWalk(repository); int cur = tw.addTree(newTree); int old = 0; boolean initialScan = oldTree == null; if (!initialScan) { old = tw.addTree(oldTree); } tw.setFilter(TreeFilter.ANY_DIFF); tw.setRecursive(true); while (tw.next()) { if (initialScan || !tw.idEqual(old, cur)) { String changedFile = tw.getNameString(); int pfix = changedFile.lastIndexOf(".xml"); if (pfix == -1) { continue; } String identifier = changedFile.substring(0, pfix);
// Path: src/main/java/net/nordu/mdx/scanner/MetadataChange.java // public class MetadataChange implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6750830823194935907L; // // private String id; // private String reason; // private Date timeStamp; // private MetadataChangeType type; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public Date getTimeStamp() { // return timeStamp; // } // // public void setTimeStamp(Date timeStamp) { // this.timeStamp = timeStamp; // } // // public MetadataChangeType getType() { // return type; // } // // public void setType(MetadataChangeType type) { // this.type = type; // } // // public String toString() { // return "EntityDescriptor["+id+"] changed: "+timeStamp+", "+type+(reason == null ? "" : ": "+reason); // } // // public MetadataChange(String id, MetadataChangeType type, String reason, Date timeStamp) { // this.id = id; // this.type = type; // this.reason = reason; // this.timeStamp = timeStamp; // } // // public MetadataChange(String id, MetadataChangeType type, String reason) { // this(id,type,reason,new Date()); // } // // public MetadataChange(String id, MetadataChangeType type) { // this(id,type,null,new Date()); // } // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeType.java // public enum MetadataChangeType { // ADD, // REMOVE, // MODIFY, // CHATTR // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContext.java // public interface MetadataStoreContext extends Serializable { // // public MetadataIndex getIndex(); // public MetadataChangeNotifier getChangeNotifier(); // // } // // Path: src/main/java/net/nordu/mdx/store/fs/URLMetadataStoreContext.java // public class URLMetadataStoreContext extends MetadataStoreContextBase { // // /** // * // */ // private static final long serialVersionUID = 5358038794721104393L; // // private URL url; // // public URL getUrl() { // return url; // } // // public void setUrl(URL url) { // this.url = url; // } // // } // Path: src/main/java/net/nordu/mdx/store/git/GitRepositoryMetadataStore.java import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimerTask; import net.nordu.mdx.scanner.MetadataChange; import net.nordu.mdx.scanner.MetadataChangeType; import net.nordu.mdx.store.MetadataStore; import net.nordu.mdx.store.MetadataStoreContext; import net.nordu.mdx.store.fs.URLMetadataStoreContext; import org.eclipse.jgit.lib.Commit; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.MutableObjectId; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.oasis.saml.metadata.EntityDescriptorDocument; import org.oasis.saml.metadata.EntityDescriptorType; /** * Diff two trees, and emit metadata change notifications. * * @param oldTree * @param newTree * @param message * @param timeStamp * @throws IOException */ private void diffTrees(ObjectId oldTree, ObjectId newTree, String message, Date timeStamp) throws IOException { TreeWalk tw = new TreeWalk(repository); int cur = tw.addTree(newTree); int old = 0; boolean initialScan = oldTree == null; if (!initialScan) { old = tw.addTree(oldTree); } tw.setFilter(TreeFilter.ANY_DIFF); tw.setRecursive(true); while (tw.next()) { if (initialScan || !tw.idEqual(old, cur)) { String changedFile = tw.getNameString(); int pfix = changedFile.lastIndexOf(".xml"); if (pfix == -1) { continue; } String identifier = changedFile.substring(0, pfix);
MetadataChangeType chT = null;
leifj/saml-md-aggregator
src/main/java/net/nordu/mdx/store/git/GitRepositoryMetadataStore.java
// Path: src/main/java/net/nordu/mdx/scanner/MetadataChange.java // public class MetadataChange implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6750830823194935907L; // // private String id; // private String reason; // private Date timeStamp; // private MetadataChangeType type; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public Date getTimeStamp() { // return timeStamp; // } // // public void setTimeStamp(Date timeStamp) { // this.timeStamp = timeStamp; // } // // public MetadataChangeType getType() { // return type; // } // // public void setType(MetadataChangeType type) { // this.type = type; // } // // public String toString() { // return "EntityDescriptor["+id+"] changed: "+timeStamp+", "+type+(reason == null ? "" : ": "+reason); // } // // public MetadataChange(String id, MetadataChangeType type, String reason, Date timeStamp) { // this.id = id; // this.type = type; // this.reason = reason; // this.timeStamp = timeStamp; // } // // public MetadataChange(String id, MetadataChangeType type, String reason) { // this(id,type,reason,new Date()); // } // // public MetadataChange(String id, MetadataChangeType type) { // this(id,type,null,new Date()); // } // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeType.java // public enum MetadataChangeType { // ADD, // REMOVE, // MODIFY, // CHATTR // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContext.java // public interface MetadataStoreContext extends Serializable { // // public MetadataIndex getIndex(); // public MetadataChangeNotifier getChangeNotifier(); // // } // // Path: src/main/java/net/nordu/mdx/store/fs/URLMetadataStoreContext.java // public class URLMetadataStoreContext extends MetadataStoreContextBase { // // /** // * // */ // private static final long serialVersionUID = 5358038794721104393L; // // private URL url; // // public URL getUrl() { // return url; // } // // public void setUrl(URL url) { // this.url = url; // } // // }
import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimerTask; import net.nordu.mdx.scanner.MetadataChange; import net.nordu.mdx.scanner.MetadataChangeType; import net.nordu.mdx.store.MetadataStore; import net.nordu.mdx.store.MetadataStoreContext; import net.nordu.mdx.store.fs.URLMetadataStoreContext; import org.eclipse.jgit.lib.Commit; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.MutableObjectId; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.oasis.saml.metadata.EntityDescriptorDocument; import org.oasis.saml.metadata.EntityDescriptorType;
String changedFile = tw.getNameString(); int pfix = changedFile.lastIndexOf(".xml"); if (pfix == -1) { continue; } String identifier = changedFile.substring(0, pfix); MetadataChangeType chT = null; if (FileMode.MISSING.equals(tw.getFileMode(cur))) { // debug("Entity deleted: '{}'", identifier); synchronized (blobMap) { blobMap.remove(identifier); } chT = MetadataChangeType.REMOVE; } else { MutableObjectId newEntry = new MutableObjectId(); tw.getObjectId(newEntry, cur); ObjectId blobId = newEntry.copy(); // debug("Entity updated or added: '{}', blob is '{}'", // identifier, blobId.getName()); synchronized (blobMap) { blobMap.put(identifier, new RepositoryEntry(blobId, timeStamp)); } if (initialScan || FileMode.MISSING.equals(tw.getFileMode(old))) { chT = MetadataChangeType.ADD; } else { chT = MetadataChangeType.MODIFY; } }
// Path: src/main/java/net/nordu/mdx/scanner/MetadataChange.java // public class MetadataChange implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6750830823194935907L; // // private String id; // private String reason; // private Date timeStamp; // private MetadataChangeType type; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public Date getTimeStamp() { // return timeStamp; // } // // public void setTimeStamp(Date timeStamp) { // this.timeStamp = timeStamp; // } // // public MetadataChangeType getType() { // return type; // } // // public void setType(MetadataChangeType type) { // this.type = type; // } // // public String toString() { // return "EntityDescriptor["+id+"] changed: "+timeStamp+", "+type+(reason == null ? "" : ": "+reason); // } // // public MetadataChange(String id, MetadataChangeType type, String reason, Date timeStamp) { // this.id = id; // this.type = type; // this.reason = reason; // this.timeStamp = timeStamp; // } // // public MetadataChange(String id, MetadataChangeType type, String reason) { // this(id,type,reason,new Date()); // } // // public MetadataChange(String id, MetadataChangeType type) { // this(id,type,null,new Date()); // } // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeType.java // public enum MetadataChangeType { // ADD, // REMOVE, // MODIFY, // CHATTR // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContext.java // public interface MetadataStoreContext extends Serializable { // // public MetadataIndex getIndex(); // public MetadataChangeNotifier getChangeNotifier(); // // } // // Path: src/main/java/net/nordu/mdx/store/fs/URLMetadataStoreContext.java // public class URLMetadataStoreContext extends MetadataStoreContextBase { // // /** // * // */ // private static final long serialVersionUID = 5358038794721104393L; // // private URL url; // // public URL getUrl() { // return url; // } // // public void setUrl(URL url) { // this.url = url; // } // // } // Path: src/main/java/net/nordu/mdx/store/git/GitRepositoryMetadataStore.java import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimerTask; import net.nordu.mdx.scanner.MetadataChange; import net.nordu.mdx.scanner.MetadataChangeType; import net.nordu.mdx.store.MetadataStore; import net.nordu.mdx.store.MetadataStoreContext; import net.nordu.mdx.store.fs.URLMetadataStoreContext; import org.eclipse.jgit.lib.Commit; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.MutableObjectId; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.oasis.saml.metadata.EntityDescriptorDocument; import org.oasis.saml.metadata.EntityDescriptorType; String changedFile = tw.getNameString(); int pfix = changedFile.lastIndexOf(".xml"); if (pfix == -1) { continue; } String identifier = changedFile.substring(0, pfix); MetadataChangeType chT = null; if (FileMode.MISSING.equals(tw.getFileMode(cur))) { // debug("Entity deleted: '{}'", identifier); synchronized (blobMap) { blobMap.remove(identifier); } chT = MetadataChangeType.REMOVE; } else { MutableObjectId newEntry = new MutableObjectId(); tw.getObjectId(newEntry, cur); ObjectId blobId = newEntry.copy(); // debug("Entity updated or added: '{}', blob is '{}'", // identifier, blobId.getName()); synchronized (blobMap) { blobMap.put(identifier, new RepositoryEntry(blobId, timeStamp)); } if (initialScan || FileMode.MISSING.equals(tw.getFileMode(old))) { chT = MetadataChangeType.ADD; } else { chT = MetadataChangeType.MODIFY; } }
MetadataChange metadataChange = new MetadataChange(identifier,
leifj/saml-md-aggregator
src/main/java/net/nordu/mdx/spring/PrettyPrintXmlBeansView.java
// Path: src/main/java/net/nordu/mdx/utils/XMLUtils.java // public class XMLUtils { // // public static byte[] o2b(XmlObject o) throws IOException { // ByteArrayOutputStream out = new ByteArrayOutputStream(); // writeObject(o,out); // return out.toByteArray(); // } // // public static void writeObject(XmlObject o, OutputStream out) throws IOException { // XmlOptions opts = new XmlOptions(); // // opts.setSaveOuter(); // opts.setSavePrettyPrint(); // opts.setSaveAggressiveNamespaces(); // o.save(out,opts); // } // // public static String o2s(XmlObject o) throws IOException { // return new String(o2b(o)); // } // // }
import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.nordu.mdx.utils.XMLUtils; import org.apache.xmlbeans.XmlObject; import org.springframework.web.servlet.View;
package net.nordu.mdx.spring; public class PrettyPrintXmlBeansView implements View { private String contentType; public void setContentType(String contentType) { this.contentType = contentType; } public String getContentType() { return contentType; } public PrettyPrintXmlBeansView() { } protected XmlObject findXmlObject(Map<String, ?> map) { for (Map.Entry<String, ?> e : map.entrySet()) { if (e.getValue() instanceof XmlObject) { return (XmlObject)e.getValue(); } } return null; } public void render(Map<String, ?> map, HttpServletRequest request, HttpServletResponse response) throws Exception { XmlObject o = findXmlObject(map); if (o != null)
// Path: src/main/java/net/nordu/mdx/utils/XMLUtils.java // public class XMLUtils { // // public static byte[] o2b(XmlObject o) throws IOException { // ByteArrayOutputStream out = new ByteArrayOutputStream(); // writeObject(o,out); // return out.toByteArray(); // } // // public static void writeObject(XmlObject o, OutputStream out) throws IOException { // XmlOptions opts = new XmlOptions(); // // opts.setSaveOuter(); // opts.setSavePrettyPrint(); // opts.setSaveAggressiveNamespaces(); // o.save(out,opts); // } // // public static String o2s(XmlObject o) throws IOException { // return new String(o2b(o)); // } // // } // Path: src/main/java/net/nordu/mdx/spring/PrettyPrintXmlBeansView.java import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.nordu.mdx.utils.XMLUtils; import org.apache.xmlbeans.XmlObject; import org.springframework.web.servlet.View; package net.nordu.mdx.spring; public class PrettyPrintXmlBeansView implements View { private String contentType; public void setContentType(String contentType) { this.contentType = contentType; } public String getContentType() { return contentType; } public PrettyPrintXmlBeansView() { } protected XmlObject findXmlObject(Map<String, ?> map) { for (Map.Entry<String, ?> e : map.entrySet()) { if (e.getValue() instanceof XmlObject) { return (XmlObject)e.getValue(); } } return null; } public void render(Map<String, ?> map, HttpServletRequest request, HttpServletResponse response) throws Exception { XmlObject o = findXmlObject(map); if (o != null)
XMLUtils.writeObject(o, response.getOutputStream());
leifj/saml-md-aggregator
src/main/java/net/nordu/mdx/scanner/MetadataIndexer.java
// Path: src/main/java/net/nordu/mdx/index/MetadataIndex.java // public interface MetadataIndex { // // public Iterable<String> find(String[] tags) throws Exception; // public void update(String id, EntityDescriptorType entity) throws Exception; // public void remove(String id); // public boolean exists(String id); // public Iterable<String> listIDs(); // public Calendar lastModified(String id); // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // }
import net.nordu.mdx.index.MetadataIndex; import net.nordu.mdx.store.MetadataStore; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired;
package net.nordu.mdx.scanner; public class MetadataIndexer { private static final Log log = LogFactory.getLog(MetadataIndexer.class); @Autowired
// Path: src/main/java/net/nordu/mdx/index/MetadataIndex.java // public interface MetadataIndex { // // public Iterable<String> find(String[] tags) throws Exception; // public void update(String id, EntityDescriptorType entity) throws Exception; // public void remove(String id); // public boolean exists(String id); // public Iterable<String> listIDs(); // public Calendar lastModified(String id); // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // } // Path: src/main/java/net/nordu/mdx/scanner/MetadataIndexer.java import net.nordu.mdx.index.MetadataIndex; import net.nordu.mdx.store.MetadataStore; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; package net.nordu.mdx.scanner; public class MetadataIndexer { private static final Log log = LogFactory.getLog(MetadataIndexer.class); @Autowired
private MetadataStore store;
leifj/saml-md-aggregator
src/main/java/net/nordu/mdx/scanner/MetadataIndexer.java
// Path: src/main/java/net/nordu/mdx/index/MetadataIndex.java // public interface MetadataIndex { // // public Iterable<String> find(String[] tags) throws Exception; // public void update(String id, EntityDescriptorType entity) throws Exception; // public void remove(String id); // public boolean exists(String id); // public Iterable<String> listIDs(); // public Calendar lastModified(String id); // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // }
import net.nordu.mdx.index.MetadataIndex; import net.nordu.mdx.store.MetadataStore; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired;
package net.nordu.mdx.scanner; public class MetadataIndexer { private static final Log log = LogFactory.getLog(MetadataIndexer.class); @Autowired private MetadataStore store; @Autowired
// Path: src/main/java/net/nordu/mdx/index/MetadataIndex.java // public interface MetadataIndex { // // public Iterable<String> find(String[] tags) throws Exception; // public void update(String id, EntityDescriptorType entity) throws Exception; // public void remove(String id); // public boolean exists(String id); // public Iterable<String> listIDs(); // public Calendar lastModified(String id); // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // } // Path: src/main/java/net/nordu/mdx/scanner/MetadataIndexer.java import net.nordu.mdx.index.MetadataIndex; import net.nordu.mdx.store.MetadataStore; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; package net.nordu.mdx.scanner; public class MetadataIndexer { private static final Log log = LogFactory.getLog(MetadataIndexer.class); @Autowired private MetadataStore store; @Autowired
private MetadataIndex index;
leifj/saml-md-aggregator
src/main/java/net/nordu/mdx/store/MetadataStoreContext.java
// Path: src/main/java/net/nordu/mdx/index/MetadataIndex.java // public interface MetadataIndex { // // public Iterable<String> find(String[] tags) throws Exception; // public void update(String id, EntityDescriptorType entity) throws Exception; // public void remove(String id); // public boolean exists(String id); // public Iterable<String> listIDs(); // public Calendar lastModified(String id); // // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeNotifier.java // public interface MetadataChangeNotifier { // // @Gateway(requestChannel="changes") // public void notifyChange(MetadataChange change); // // }
import java.io.Serializable; import net.nordu.mdx.index.MetadataIndex; import net.nordu.mdx.scanner.MetadataChangeNotifier;
package net.nordu.mdx.store; public interface MetadataStoreContext extends Serializable { public MetadataIndex getIndex();
// Path: src/main/java/net/nordu/mdx/index/MetadataIndex.java // public interface MetadataIndex { // // public Iterable<String> find(String[] tags) throws Exception; // public void update(String id, EntityDescriptorType entity) throws Exception; // public void remove(String id); // public boolean exists(String id); // public Iterable<String> listIDs(); // public Calendar lastModified(String id); // // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeNotifier.java // public interface MetadataChangeNotifier { // // @Gateway(requestChannel="changes") // public void notifyChange(MetadataChange change); // // } // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContext.java import java.io.Serializable; import net.nordu.mdx.index.MetadataIndex; import net.nordu.mdx.scanner.MetadataChangeNotifier; package net.nordu.mdx.store; public interface MetadataStoreContext extends Serializable { public MetadataIndex getIndex();
public MetadataChangeNotifier getChangeNotifier();
leifj/saml-md-aggregator
src/main/java/net/nordu/mdx/store/fs/FileSystemMetadataStore.java
// Path: src/main/java/net/nordu/mdx/scanner/MetadataChange.java // public class MetadataChange implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6750830823194935907L; // // private String id; // private String reason; // private Date timeStamp; // private MetadataChangeType type; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public Date getTimeStamp() { // return timeStamp; // } // // public void setTimeStamp(Date timeStamp) { // this.timeStamp = timeStamp; // } // // public MetadataChangeType getType() { // return type; // } // // public void setType(MetadataChangeType type) { // this.type = type; // } // // public String toString() { // return "EntityDescriptor["+id+"] changed: "+timeStamp+", "+type+(reason == null ? "" : ": "+reason); // } // // public MetadataChange(String id, MetadataChangeType type, String reason, Date timeStamp) { // this.id = id; // this.type = type; // this.reason = reason; // this.timeStamp = timeStamp; // } // // public MetadataChange(String id, MetadataChangeType type, String reason) { // this(id,type,reason,new Date()); // } // // public MetadataChange(String id, MetadataChangeType type) { // this(id,type,null,new Date()); // } // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeType.java // public enum MetadataChangeType { // ADD, // REMOVE, // MODIFY, // CHATTR // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContext.java // public interface MetadataStoreContext extends Serializable { // // public MetadataIndex getIndex(); // public MetadataChangeNotifier getChangeNotifier(); // // }
import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.TimerTask; import net.nordu.mdx.scanner.MetadataChange; import net.nordu.mdx.scanner.MetadataChangeType; import net.nordu.mdx.store.MetadataStore; import net.nordu.mdx.store.MetadataStoreContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.oasis.saml.metadata.EntityDescriptorDocument; import org.oasis.saml.metadata.EntityDescriptorType;
package net.nordu.mdx.store.fs; public class FileSystemMetadataStore implements MetadataStore { private URLMetadataStoreContext context; public String getDirectory() { return context.getUrl().getPath(); } public void setContext(URLMetadataStoreContext context) { this.context = context; } public URLMetadataStoreContext getContext() { return context; } private File getDir() { return new File(getDirectory()); }
// Path: src/main/java/net/nordu/mdx/scanner/MetadataChange.java // public class MetadataChange implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6750830823194935907L; // // private String id; // private String reason; // private Date timeStamp; // private MetadataChangeType type; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public Date getTimeStamp() { // return timeStamp; // } // // public void setTimeStamp(Date timeStamp) { // this.timeStamp = timeStamp; // } // // public MetadataChangeType getType() { // return type; // } // // public void setType(MetadataChangeType type) { // this.type = type; // } // // public String toString() { // return "EntityDescriptor["+id+"] changed: "+timeStamp+", "+type+(reason == null ? "" : ": "+reason); // } // // public MetadataChange(String id, MetadataChangeType type, String reason, Date timeStamp) { // this.id = id; // this.type = type; // this.reason = reason; // this.timeStamp = timeStamp; // } // // public MetadataChange(String id, MetadataChangeType type, String reason) { // this(id,type,reason,new Date()); // } // // public MetadataChange(String id, MetadataChangeType type) { // this(id,type,null,new Date()); // } // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeType.java // public enum MetadataChangeType { // ADD, // REMOVE, // MODIFY, // CHATTR // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContext.java // public interface MetadataStoreContext extends Serializable { // // public MetadataIndex getIndex(); // public MetadataChangeNotifier getChangeNotifier(); // // } // Path: src/main/java/net/nordu/mdx/store/fs/FileSystemMetadataStore.java import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.TimerTask; import net.nordu.mdx.scanner.MetadataChange; import net.nordu.mdx.scanner.MetadataChangeType; import net.nordu.mdx.store.MetadataStore; import net.nordu.mdx.store.MetadataStoreContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.oasis.saml.metadata.EntityDescriptorDocument; import org.oasis.saml.metadata.EntityDescriptorType; package net.nordu.mdx.store.fs; public class FileSystemMetadataStore implements MetadataStore { private URLMetadataStoreContext context; public String getDirectory() { return context.getUrl().getPath(); } public void setContext(URLMetadataStoreContext context) { this.context = context; } public URLMetadataStoreContext getContext() { return context; } private File getDir() { return new File(getDirectory()); }
public void setContext(MetadataStoreContext c) throws Exception {
leifj/saml-md-aggregator
src/main/java/net/nordu/mdx/store/fs/FileSystemMetadataStore.java
// Path: src/main/java/net/nordu/mdx/scanner/MetadataChange.java // public class MetadataChange implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6750830823194935907L; // // private String id; // private String reason; // private Date timeStamp; // private MetadataChangeType type; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public Date getTimeStamp() { // return timeStamp; // } // // public void setTimeStamp(Date timeStamp) { // this.timeStamp = timeStamp; // } // // public MetadataChangeType getType() { // return type; // } // // public void setType(MetadataChangeType type) { // this.type = type; // } // // public String toString() { // return "EntityDescriptor["+id+"] changed: "+timeStamp+", "+type+(reason == null ? "" : ": "+reason); // } // // public MetadataChange(String id, MetadataChangeType type, String reason, Date timeStamp) { // this.id = id; // this.type = type; // this.reason = reason; // this.timeStamp = timeStamp; // } // // public MetadataChange(String id, MetadataChangeType type, String reason) { // this(id,type,reason,new Date()); // } // // public MetadataChange(String id, MetadataChangeType type) { // this(id,type,null,new Date()); // } // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeType.java // public enum MetadataChangeType { // ADD, // REMOVE, // MODIFY, // CHATTR // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContext.java // public interface MetadataStoreContext extends Serializable { // // public MetadataIndex getIndex(); // public MetadataChangeNotifier getChangeNotifier(); // // }
import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.TimerTask; import net.nordu.mdx.scanner.MetadataChange; import net.nordu.mdx.scanner.MetadataChangeType; import net.nordu.mdx.store.MetadataStore; import net.nordu.mdx.store.MetadataStoreContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.oasis.saml.metadata.EntityDescriptorDocument; import org.oasis.saml.metadata.EntityDescriptorType;
} private File _file(String id) { return new File(getDir(),id+".xml"); } @Override public boolean exists(String id) throws Exception { File f = _file(id); return f.exists() && f.canRead(); } @Override public Calendar lastModified(String id) { File f = _file(id); Calendar t = Calendar.getInstance(); t.setTimeInMillis(f.lastModified()); return t; } @Override public TimerTask scanner() { final MetadataStore store = this; return new TimerTask() { private final Log log = LogFactory.getLog(this.getClass()); public void run() { try { for (String id: store.listIDs()) { if (!context.getIndex().exists(id))
// Path: src/main/java/net/nordu/mdx/scanner/MetadataChange.java // public class MetadataChange implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6750830823194935907L; // // private String id; // private String reason; // private Date timeStamp; // private MetadataChangeType type; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public Date getTimeStamp() { // return timeStamp; // } // // public void setTimeStamp(Date timeStamp) { // this.timeStamp = timeStamp; // } // // public MetadataChangeType getType() { // return type; // } // // public void setType(MetadataChangeType type) { // this.type = type; // } // // public String toString() { // return "EntityDescriptor["+id+"] changed: "+timeStamp+", "+type+(reason == null ? "" : ": "+reason); // } // // public MetadataChange(String id, MetadataChangeType type, String reason, Date timeStamp) { // this.id = id; // this.type = type; // this.reason = reason; // this.timeStamp = timeStamp; // } // // public MetadataChange(String id, MetadataChangeType type, String reason) { // this(id,type,reason,new Date()); // } // // public MetadataChange(String id, MetadataChangeType type) { // this(id,type,null,new Date()); // } // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeType.java // public enum MetadataChangeType { // ADD, // REMOVE, // MODIFY, // CHATTR // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContext.java // public interface MetadataStoreContext extends Serializable { // // public MetadataIndex getIndex(); // public MetadataChangeNotifier getChangeNotifier(); // // } // Path: src/main/java/net/nordu/mdx/store/fs/FileSystemMetadataStore.java import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.TimerTask; import net.nordu.mdx.scanner.MetadataChange; import net.nordu.mdx.scanner.MetadataChangeType; import net.nordu.mdx.store.MetadataStore; import net.nordu.mdx.store.MetadataStoreContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.oasis.saml.metadata.EntityDescriptorDocument; import org.oasis.saml.metadata.EntityDescriptorType; } private File _file(String id) { return new File(getDir(),id+".xml"); } @Override public boolean exists(String id) throws Exception { File f = _file(id); return f.exists() && f.canRead(); } @Override public Calendar lastModified(String id) { File f = _file(id); Calendar t = Calendar.getInstance(); t.setTimeInMillis(f.lastModified()); return t; } @Override public TimerTask scanner() { final MetadataStore store = this; return new TimerTask() { private final Log log = LogFactory.getLog(this.getClass()); public void run() { try { for (String id: store.listIDs()) { if (!context.getIndex().exists(id))
context.getChangeNotifier().notifyChange(new MetadataChange(id, MetadataChangeType.ADD));
leifj/saml-md-aggregator
src/main/java/net/nordu/mdx/store/fs/FileSystemMetadataStore.java
// Path: src/main/java/net/nordu/mdx/scanner/MetadataChange.java // public class MetadataChange implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6750830823194935907L; // // private String id; // private String reason; // private Date timeStamp; // private MetadataChangeType type; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public Date getTimeStamp() { // return timeStamp; // } // // public void setTimeStamp(Date timeStamp) { // this.timeStamp = timeStamp; // } // // public MetadataChangeType getType() { // return type; // } // // public void setType(MetadataChangeType type) { // this.type = type; // } // // public String toString() { // return "EntityDescriptor["+id+"] changed: "+timeStamp+", "+type+(reason == null ? "" : ": "+reason); // } // // public MetadataChange(String id, MetadataChangeType type, String reason, Date timeStamp) { // this.id = id; // this.type = type; // this.reason = reason; // this.timeStamp = timeStamp; // } // // public MetadataChange(String id, MetadataChangeType type, String reason) { // this(id,type,reason,new Date()); // } // // public MetadataChange(String id, MetadataChangeType type) { // this(id,type,null,new Date()); // } // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeType.java // public enum MetadataChangeType { // ADD, // REMOVE, // MODIFY, // CHATTR // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContext.java // public interface MetadataStoreContext extends Serializable { // // public MetadataIndex getIndex(); // public MetadataChangeNotifier getChangeNotifier(); // // }
import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.TimerTask; import net.nordu.mdx.scanner.MetadataChange; import net.nordu.mdx.scanner.MetadataChangeType; import net.nordu.mdx.store.MetadataStore; import net.nordu.mdx.store.MetadataStoreContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.oasis.saml.metadata.EntityDescriptorDocument; import org.oasis.saml.metadata.EntityDescriptorType;
} private File _file(String id) { return new File(getDir(),id+".xml"); } @Override public boolean exists(String id) throws Exception { File f = _file(id); return f.exists() && f.canRead(); } @Override public Calendar lastModified(String id) { File f = _file(id); Calendar t = Calendar.getInstance(); t.setTimeInMillis(f.lastModified()); return t; } @Override public TimerTask scanner() { final MetadataStore store = this; return new TimerTask() { private final Log log = LogFactory.getLog(this.getClass()); public void run() { try { for (String id: store.listIDs()) { if (!context.getIndex().exists(id))
// Path: src/main/java/net/nordu/mdx/scanner/MetadataChange.java // public class MetadataChange implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6750830823194935907L; // // private String id; // private String reason; // private Date timeStamp; // private MetadataChangeType type; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public Date getTimeStamp() { // return timeStamp; // } // // public void setTimeStamp(Date timeStamp) { // this.timeStamp = timeStamp; // } // // public MetadataChangeType getType() { // return type; // } // // public void setType(MetadataChangeType type) { // this.type = type; // } // // public String toString() { // return "EntityDescriptor["+id+"] changed: "+timeStamp+", "+type+(reason == null ? "" : ": "+reason); // } // // public MetadataChange(String id, MetadataChangeType type, String reason, Date timeStamp) { // this.id = id; // this.type = type; // this.reason = reason; // this.timeStamp = timeStamp; // } // // public MetadataChange(String id, MetadataChangeType type, String reason) { // this(id,type,reason,new Date()); // } // // public MetadataChange(String id, MetadataChangeType type) { // this(id,type,null,new Date()); // } // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeType.java // public enum MetadataChangeType { // ADD, // REMOVE, // MODIFY, // CHATTR // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStore.java // public interface MetadataStore { // // public List<String> listIDs() throws Exception; // public boolean exists(String id) throws Exception; // public EntityDescriptorType load(String id) throws Exception; // public Calendar lastModified(String id); // public TimerTask scanner(); // public void setContext(MetadataStoreContext params) throws Exception; // // } // // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContext.java // public interface MetadataStoreContext extends Serializable { // // public MetadataIndex getIndex(); // public MetadataChangeNotifier getChangeNotifier(); // // } // Path: src/main/java/net/nordu/mdx/store/fs/FileSystemMetadataStore.java import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.TimerTask; import net.nordu.mdx.scanner.MetadataChange; import net.nordu.mdx.scanner.MetadataChangeType; import net.nordu.mdx.store.MetadataStore; import net.nordu.mdx.store.MetadataStoreContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.oasis.saml.metadata.EntityDescriptorDocument; import org.oasis.saml.metadata.EntityDescriptorType; } private File _file(String id) { return new File(getDir(),id+".xml"); } @Override public boolean exists(String id) throws Exception { File f = _file(id); return f.exists() && f.canRead(); } @Override public Calendar lastModified(String id) { File f = _file(id); Calendar t = Calendar.getInstance(); t.setTimeInMillis(f.lastModified()); return t; } @Override public TimerTask scanner() { final MetadataStore store = this; return new TimerTask() { private final Log log = LogFactory.getLog(this.getClass()); public void run() { try { for (String id: store.listIDs()) { if (!context.getIndex().exists(id))
context.getChangeNotifier().notifyChange(new MetadataChange(id, MetadataChangeType.ADD));
leifj/saml-md-aggregator
src/main/java/net/nordu/mdx/store/MetadataStoreContextBase.java
// Path: src/main/java/net/nordu/mdx/index/MetadataIndex.java // public interface MetadataIndex { // // public Iterable<String> find(String[] tags) throws Exception; // public void update(String id, EntityDescriptorType entity) throws Exception; // public void remove(String id); // public boolean exists(String id); // public Iterable<String> listIDs(); // public Calendar lastModified(String id); // // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeNotifier.java // public interface MetadataChangeNotifier { // // @Gateway(requestChannel="changes") // public void notifyChange(MetadataChange change); // // }
import net.nordu.mdx.index.MetadataIndex; import net.nordu.mdx.scanner.MetadataChangeNotifier;
package net.nordu.mdx.store; public abstract class MetadataStoreContextBase implements MetadataStoreContext { /** * */ private static final long serialVersionUID = -8559068110972869231L;
// Path: src/main/java/net/nordu/mdx/index/MetadataIndex.java // public interface MetadataIndex { // // public Iterable<String> find(String[] tags) throws Exception; // public void update(String id, EntityDescriptorType entity) throws Exception; // public void remove(String id); // public boolean exists(String id); // public Iterable<String> listIDs(); // public Calendar lastModified(String id); // // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeNotifier.java // public interface MetadataChangeNotifier { // // @Gateway(requestChannel="changes") // public void notifyChange(MetadataChange change); // // } // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContextBase.java import net.nordu.mdx.index.MetadataIndex; import net.nordu.mdx.scanner.MetadataChangeNotifier; package net.nordu.mdx.store; public abstract class MetadataStoreContextBase implements MetadataStoreContext { /** * */ private static final long serialVersionUID = -8559068110972869231L;
private MetadataChangeNotifier changeNotifier;
leifj/saml-md-aggregator
src/main/java/net/nordu/mdx/store/MetadataStoreContextBase.java
// Path: src/main/java/net/nordu/mdx/index/MetadataIndex.java // public interface MetadataIndex { // // public Iterable<String> find(String[] tags) throws Exception; // public void update(String id, EntityDescriptorType entity) throws Exception; // public void remove(String id); // public boolean exists(String id); // public Iterable<String> listIDs(); // public Calendar lastModified(String id); // // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeNotifier.java // public interface MetadataChangeNotifier { // // @Gateway(requestChannel="changes") // public void notifyChange(MetadataChange change); // // }
import net.nordu.mdx.index.MetadataIndex; import net.nordu.mdx.scanner.MetadataChangeNotifier;
package net.nordu.mdx.store; public abstract class MetadataStoreContextBase implements MetadataStoreContext { /** * */ private static final long serialVersionUID = -8559068110972869231L; private MetadataChangeNotifier changeNotifier;
// Path: src/main/java/net/nordu/mdx/index/MetadataIndex.java // public interface MetadataIndex { // // public Iterable<String> find(String[] tags) throws Exception; // public void update(String id, EntityDescriptorType entity) throws Exception; // public void remove(String id); // public boolean exists(String id); // public Iterable<String> listIDs(); // public Calendar lastModified(String id); // // } // // Path: src/main/java/net/nordu/mdx/scanner/MetadataChangeNotifier.java // public interface MetadataChangeNotifier { // // @Gateway(requestChannel="changes") // public void notifyChange(MetadataChange change); // // } // Path: src/main/java/net/nordu/mdx/store/MetadataStoreContextBase.java import net.nordu.mdx.index.MetadataIndex; import net.nordu.mdx.scanner.MetadataChangeNotifier; package net.nordu.mdx.store; public abstract class MetadataStoreContextBase implements MetadataStoreContext { /** * */ private static final long serialVersionUID = -8559068110972869231L; private MetadataChangeNotifier changeNotifier;
private MetadataIndex index;
leifj/saml-md-aggregator
src/main/java/net/nordu/mdx/utils/MetadataUtils.java
// Path: src/main/java/net/nordu/mdx/MetadataIOException.java // public class MetadataIOException extends MetadataException { // // private static final long serialVersionUID = -4323006006007227142L; // // public MetadataIOException() { super(); } // public MetadataIOException(String msg) { super(msg); } // public MetadataIOException(Exception inner) { super(inner); } // // }
import java.io.ByteArrayInputStream; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Calendar; import java.util.Collection; import java.util.Date; import net.nordu.mdx.MetadataIOException; import org.apache.xml.security.exceptions.Base64DecodingException; import org.apache.xml.security.utils.Base64; import org.apache.xmlbeans.GDuration; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.oasis.saml.assertion.AssertionType; import org.oasis.saml.assertion.AttributeStatementType; import org.oasis.saml.assertion.AttributeType; import org.oasis.saml.metadata.AdditionalMetadataLocationType; import org.oasis.saml.metadata.EntitiesDescriptorDocument; import org.oasis.saml.metadata.EntitiesDescriptorType; import org.oasis.saml.metadata.EntityDescriptorType; import org.oasis.saml.metadata.RoleDescriptorType; import org.oasis.saml.metadata.attribute.EntityAttributesDocument; import org.oasis.saml.metadata.attribute.EntityAttributesType; import org.w3c.dom.NodeList;
package net.nordu.mdx.utils; public class MetadataUtils { private static final String NSDECL = "declare namespace ds='http://www.w3.org/2000/09/xmldsig#';"+ "declare namespace md='urn:oasis:names:tc:SAML:2.0:metadata';"+ "declare namespace shibmd='urn:mace:shibboleth:metadata:1.0';";
// Path: src/main/java/net/nordu/mdx/MetadataIOException.java // public class MetadataIOException extends MetadataException { // // private static final long serialVersionUID = -4323006006007227142L; // // public MetadataIOException() { super(); } // public MetadataIOException(String msg) { super(msg); } // public MetadataIOException(Exception inner) { super(inner); } // // } // Path: src/main/java/net/nordu/mdx/utils/MetadataUtils.java import java.io.ByteArrayInputStream; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Calendar; import java.util.Collection; import java.util.Date; import net.nordu.mdx.MetadataIOException; import org.apache.xml.security.exceptions.Base64DecodingException; import org.apache.xml.security.utils.Base64; import org.apache.xmlbeans.GDuration; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.oasis.saml.assertion.AssertionType; import org.oasis.saml.assertion.AttributeStatementType; import org.oasis.saml.assertion.AttributeType; import org.oasis.saml.metadata.AdditionalMetadataLocationType; import org.oasis.saml.metadata.EntitiesDescriptorDocument; import org.oasis.saml.metadata.EntitiesDescriptorType; import org.oasis.saml.metadata.EntityDescriptorType; import org.oasis.saml.metadata.RoleDescriptorType; import org.oasis.saml.metadata.attribute.EntityAttributesDocument; import org.oasis.saml.metadata.attribute.EntityAttributesType; import org.w3c.dom.NodeList; package net.nordu.mdx.utils; public class MetadataUtils { private static final String NSDECL = "declare namespace ds='http://www.w3.org/2000/09/xmldsig#';"+ "declare namespace md='urn:oasis:names:tc:SAML:2.0:metadata';"+ "declare namespace shibmd='urn:mace:shibboleth:metadata:1.0';";
public static EntityAttributesType findAttributes(EntityDescriptorType entity) throws MetadataIOException {
wuyan345/onlineShop
src/test/java/shop/MybatisTest.java
// Path: src/main/java/com/shop/dao/CartMapper.java // public interface CartMapper { // int deleteByPrimaryKey(Integer id); // // int insert(Cart record); // // int insertSelective(Cart record); // // Cart selectByPrimaryKey(Integer id); // // int updateByPrimaryKeySelective(Cart record); // // int updateByPrimaryKey(Cart record); // // /** // * 返回用户所有购物车 // * @param userId // * @return // */ // List<Cart> selectByUserId(Integer userId); // // /** // * 返回用户所有勾选或未勾选的购物车 // * @param userId // * @param selected // * @return // */ // List<Cart> selectByUserIdSelected(@Param("userId")Integer userId, @Param("selected")int selected); // // /** // * 返回指定用户所有购物车以及对应商品 // * @param userId // * @return // */ // List<CartGoodsBo> selectAllCartGoods(Integer userId); // // int batchUpdate(List<Cart> cartList); // // int batchUpdateTest(List<Cart> cartList); // // /** // * 返回用户所有勾选的购物车对应的商品信息 // * @param userId // * @return // */ // List<Goods> selectGoodsByUserId(Integer userId); // // List<com.shop.bo.order.CartGoodsBo> querySelectedCartGoods(Integer userId); // // int batchDelete(List<com.shop.bo.order.CartGoodsBo> cartGoodsBoList); // // /** // * 返回用户指定购物车 // */ // Cart selectCartByGoodsId(@Param("userId")Integer userId, @Param("goodsId")Integer goodsId); // // int deleteByCartIdUserId(@Param("userId")Integer userId, @Param("cartId")Integer cartId); // } // // Path: src/main/java/com/shop/pojo/Cart.java // public class Cart { // private Integer id; // // private Integer userId; // // private Integer goodsId; // // private BigDecimal price; // // private Integer quantity; // // private Integer selected; // // private Date createTime; // // private Date updateTime; // // public Cart(Integer id, Integer userId, Integer goodsId, BigDecimal price, Integer quantity, Integer selected, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.goodsId = goodsId; // this.price = price; // this.quantity = quantity; // this.selected = selected; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Cart() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Integer getGoodsId() { // return goodsId; // } // // public void setGoodsId(Integer goodsId) { // this.goodsId = goodsId; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public Integer getSelected() { // return selected; // } // // public void setSelected(Integer selected) { // this.selected = selected; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // }
import static org.junit.Assert.*; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.BeforeClass; import org.junit.Test; import com.shop.dao.CartMapper; import com.shop.pojo.Cart;
package shop; /** * 测试失败,mybatisConfig.xml配置错误 * @author WY * */ public class MybatisTest { private static SqlSessionFactory sqlSessionFactory; @BeforeClass public static void setUp() throws Exception { // create an SqlSessionFactory Reader reader = Resources.getResourceAsReader("mybatisConfig.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); reader.close(); // populate in-memory database // SqlSession session = sqlSessionFactory.openSession(); // Connection conn = session.getConnection(); // reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/basetest/CreateDB.sql"); // ScriptRunner runner = new ScriptRunner(conn); // runner.setLogWriter(null); // runner.runScript(reader); // conn.close(); // reader.close(); // session.close(); } @Test public void shouldGetACart() { SqlSession sqlSession = sqlSessionFactory.openSession(); try {
// Path: src/main/java/com/shop/dao/CartMapper.java // public interface CartMapper { // int deleteByPrimaryKey(Integer id); // // int insert(Cart record); // // int insertSelective(Cart record); // // Cart selectByPrimaryKey(Integer id); // // int updateByPrimaryKeySelective(Cart record); // // int updateByPrimaryKey(Cart record); // // /** // * 返回用户所有购物车 // * @param userId // * @return // */ // List<Cart> selectByUserId(Integer userId); // // /** // * 返回用户所有勾选或未勾选的购物车 // * @param userId // * @param selected // * @return // */ // List<Cart> selectByUserIdSelected(@Param("userId")Integer userId, @Param("selected")int selected); // // /** // * 返回指定用户所有购物车以及对应商品 // * @param userId // * @return // */ // List<CartGoodsBo> selectAllCartGoods(Integer userId); // // int batchUpdate(List<Cart> cartList); // // int batchUpdateTest(List<Cart> cartList); // // /** // * 返回用户所有勾选的购物车对应的商品信息 // * @param userId // * @return // */ // List<Goods> selectGoodsByUserId(Integer userId); // // List<com.shop.bo.order.CartGoodsBo> querySelectedCartGoods(Integer userId); // // int batchDelete(List<com.shop.bo.order.CartGoodsBo> cartGoodsBoList); // // /** // * 返回用户指定购物车 // */ // Cart selectCartByGoodsId(@Param("userId")Integer userId, @Param("goodsId")Integer goodsId); // // int deleteByCartIdUserId(@Param("userId")Integer userId, @Param("cartId")Integer cartId); // } // // Path: src/main/java/com/shop/pojo/Cart.java // public class Cart { // private Integer id; // // private Integer userId; // // private Integer goodsId; // // private BigDecimal price; // // private Integer quantity; // // private Integer selected; // // private Date createTime; // // private Date updateTime; // // public Cart(Integer id, Integer userId, Integer goodsId, BigDecimal price, Integer quantity, Integer selected, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.goodsId = goodsId; // this.price = price; // this.quantity = quantity; // this.selected = selected; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Cart() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Integer getGoodsId() { // return goodsId; // } // // public void setGoodsId(Integer goodsId) { // this.goodsId = goodsId; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public Integer getSelected() { // return selected; // } // // public void setSelected(Integer selected) { // this.selected = selected; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // } // Path: src/test/java/shop/MybatisTest.java import static org.junit.Assert.*; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.BeforeClass; import org.junit.Test; import com.shop.dao.CartMapper; import com.shop.pojo.Cart; package shop; /** * 测试失败,mybatisConfig.xml配置错误 * @author WY * */ public class MybatisTest { private static SqlSessionFactory sqlSessionFactory; @BeforeClass public static void setUp() throws Exception { // create an SqlSessionFactory Reader reader = Resources.getResourceAsReader("mybatisConfig.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); reader.close(); // populate in-memory database // SqlSession session = sqlSessionFactory.openSession(); // Connection conn = session.getConnection(); // reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/basetest/CreateDB.sql"); // ScriptRunner runner = new ScriptRunner(conn); // runner.setLogWriter(null); // runner.runScript(reader); // conn.close(); // reader.close(); // session.close(); } @Test public void shouldGetACart() { SqlSession sqlSession = sqlSessionFactory.openSession(); try {
CartMapper cartMapper = sqlSession.getMapper(CartMapper.class);
wuyan345/onlineShop
src/test/java/shop/MybatisTest.java
// Path: src/main/java/com/shop/dao/CartMapper.java // public interface CartMapper { // int deleteByPrimaryKey(Integer id); // // int insert(Cart record); // // int insertSelective(Cart record); // // Cart selectByPrimaryKey(Integer id); // // int updateByPrimaryKeySelective(Cart record); // // int updateByPrimaryKey(Cart record); // // /** // * 返回用户所有购物车 // * @param userId // * @return // */ // List<Cart> selectByUserId(Integer userId); // // /** // * 返回用户所有勾选或未勾选的购物车 // * @param userId // * @param selected // * @return // */ // List<Cart> selectByUserIdSelected(@Param("userId")Integer userId, @Param("selected")int selected); // // /** // * 返回指定用户所有购物车以及对应商品 // * @param userId // * @return // */ // List<CartGoodsBo> selectAllCartGoods(Integer userId); // // int batchUpdate(List<Cart> cartList); // // int batchUpdateTest(List<Cart> cartList); // // /** // * 返回用户所有勾选的购物车对应的商品信息 // * @param userId // * @return // */ // List<Goods> selectGoodsByUserId(Integer userId); // // List<com.shop.bo.order.CartGoodsBo> querySelectedCartGoods(Integer userId); // // int batchDelete(List<com.shop.bo.order.CartGoodsBo> cartGoodsBoList); // // /** // * 返回用户指定购物车 // */ // Cart selectCartByGoodsId(@Param("userId")Integer userId, @Param("goodsId")Integer goodsId); // // int deleteByCartIdUserId(@Param("userId")Integer userId, @Param("cartId")Integer cartId); // } // // Path: src/main/java/com/shop/pojo/Cart.java // public class Cart { // private Integer id; // // private Integer userId; // // private Integer goodsId; // // private BigDecimal price; // // private Integer quantity; // // private Integer selected; // // private Date createTime; // // private Date updateTime; // // public Cart(Integer id, Integer userId, Integer goodsId, BigDecimal price, Integer quantity, Integer selected, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.goodsId = goodsId; // this.price = price; // this.quantity = quantity; // this.selected = selected; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Cart() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Integer getGoodsId() { // return goodsId; // } // // public void setGoodsId(Integer goodsId) { // this.goodsId = goodsId; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public Integer getSelected() { // return selected; // } // // public void setSelected(Integer selected) { // this.selected = selected; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // }
import static org.junit.Assert.*; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.BeforeClass; import org.junit.Test; import com.shop.dao.CartMapper; import com.shop.pojo.Cart;
package shop; /** * 测试失败,mybatisConfig.xml配置错误 * @author WY * */ public class MybatisTest { private static SqlSessionFactory sqlSessionFactory; @BeforeClass public static void setUp() throws Exception { // create an SqlSessionFactory Reader reader = Resources.getResourceAsReader("mybatisConfig.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); reader.close(); // populate in-memory database // SqlSession session = sqlSessionFactory.openSession(); // Connection conn = session.getConnection(); // reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/basetest/CreateDB.sql"); // ScriptRunner runner = new ScriptRunner(conn); // runner.setLogWriter(null); // runner.runScript(reader); // conn.close(); // reader.close(); // session.close(); } @Test public void shouldGetACart() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { CartMapper cartMapper = sqlSession.getMapper(CartMapper.class);
// Path: src/main/java/com/shop/dao/CartMapper.java // public interface CartMapper { // int deleteByPrimaryKey(Integer id); // // int insert(Cart record); // // int insertSelective(Cart record); // // Cart selectByPrimaryKey(Integer id); // // int updateByPrimaryKeySelective(Cart record); // // int updateByPrimaryKey(Cart record); // // /** // * 返回用户所有购物车 // * @param userId // * @return // */ // List<Cart> selectByUserId(Integer userId); // // /** // * 返回用户所有勾选或未勾选的购物车 // * @param userId // * @param selected // * @return // */ // List<Cart> selectByUserIdSelected(@Param("userId")Integer userId, @Param("selected")int selected); // // /** // * 返回指定用户所有购物车以及对应商品 // * @param userId // * @return // */ // List<CartGoodsBo> selectAllCartGoods(Integer userId); // // int batchUpdate(List<Cart> cartList); // // int batchUpdateTest(List<Cart> cartList); // // /** // * 返回用户所有勾选的购物车对应的商品信息 // * @param userId // * @return // */ // List<Goods> selectGoodsByUserId(Integer userId); // // List<com.shop.bo.order.CartGoodsBo> querySelectedCartGoods(Integer userId); // // int batchDelete(List<com.shop.bo.order.CartGoodsBo> cartGoodsBoList); // // /** // * 返回用户指定购物车 // */ // Cart selectCartByGoodsId(@Param("userId")Integer userId, @Param("goodsId")Integer goodsId); // // int deleteByCartIdUserId(@Param("userId")Integer userId, @Param("cartId")Integer cartId); // } // // Path: src/main/java/com/shop/pojo/Cart.java // public class Cart { // private Integer id; // // private Integer userId; // // private Integer goodsId; // // private BigDecimal price; // // private Integer quantity; // // private Integer selected; // // private Date createTime; // // private Date updateTime; // // public Cart(Integer id, Integer userId, Integer goodsId, BigDecimal price, Integer quantity, Integer selected, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.goodsId = goodsId; // this.price = price; // this.quantity = quantity; // this.selected = selected; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Cart() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Integer getGoodsId() { // return goodsId; // } // // public void setGoodsId(Integer goodsId) { // this.goodsId = goodsId; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Integer getQuantity() { // return quantity; // } // // public void setQuantity(Integer quantity) { // this.quantity = quantity; // } // // public Integer getSelected() { // return selected; // } // // public void setSelected(Integer selected) { // this.selected = selected; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // } // Path: src/test/java/shop/MybatisTest.java import static org.junit.Assert.*; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.BeforeClass; import org.junit.Test; import com.shop.dao.CartMapper; import com.shop.pojo.Cart; package shop; /** * 测试失败,mybatisConfig.xml配置错误 * @author WY * */ public class MybatisTest { private static SqlSessionFactory sqlSessionFactory; @BeforeClass public static void setUp() throws Exception { // create an SqlSessionFactory Reader reader = Resources.getResourceAsReader("mybatisConfig.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); reader.close(); // populate in-memory database // SqlSession session = sqlSessionFactory.openSession(); // Connection conn = session.getConnection(); // reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/basetest/CreateDB.sql"); // ScriptRunner runner = new ScriptRunner(conn); // runner.setLogWriter(null); // runner.runScript(reader); // conn.close(); // reader.close(); // session.close(); } @Test public void shouldGetACart() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { CartMapper cartMapper = sqlSession.getMapper(CartMapper.class);
Cart cart = cartMapper.selectByPrimaryKey(301);
wuyan345/onlineShop
src/main/java/com/shop/dao/RoleMapper.java
// Path: src/main/java/com/shop/pojo/Role.java // public class Role { // private Integer id; // // private Integer userId; // // private Integer roleNo; // // private Date createTime; // // private Date updateTime; // // public Role(Integer id, Integer userId, Integer roleNo, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.roleNo = roleNo; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Role() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Integer getRoleNo() { // return roleNo; // } // // public void setRoleNo(Integer roleNo) { // this.roleNo = roleNo; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // }
import com.shop.pojo.Role;
package com.shop.dao; public interface RoleMapper { int deleteByPrimaryKey(Integer id);
// Path: src/main/java/com/shop/pojo/Role.java // public class Role { // private Integer id; // // private Integer userId; // // private Integer roleNo; // // private Date createTime; // // private Date updateTime; // // public Role(Integer id, Integer userId, Integer roleNo, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.roleNo = roleNo; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Role() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Integer getRoleNo() { // return roleNo; // } // // public void setRoleNo(Integer roleNo) { // this.roleNo = roleNo; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // } // Path: src/main/java/com/shop/dao/RoleMapper.java import com.shop.pojo.Role; package com.shop.dao; public interface RoleMapper { int deleteByPrimaryKey(Integer id);
int insert(Role record);
wuyan345/onlineShop
src/main/java/com/shop/dao/OrderMapper.java
// Path: src/main/java/com/shop/pojo/Order.java // public class Order { // private Integer id; // // private Integer userId; // // private Integer shippingId; // // private Long orderNo; // // private BigDecimal payment; // // private Integer paymentType; // // private BigDecimal postage; // // private Integer status; // // private Date paymentTime; // // private Date deliveryTime; // // private Date receiveTime; // // private Date returnGoodsTime; // // private Date refundTime; // // private Date closeTime; // // private Date createTime; // // private Date updateTime; // // public Order(Integer id, Integer userId, Integer shippingId, Long orderNo, BigDecimal payment, Integer paymentType, BigDecimal postage, Integer status, Date paymentTime, Date deliveryTime, Date receiveTime, Date returnGoodsTime, Date refundTime, Date closeTime, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.shippingId = shippingId; // this.orderNo = orderNo; // this.payment = payment; // this.paymentType = paymentType; // this.postage = postage; // this.status = status; // this.paymentTime = paymentTime; // this.deliveryTime = deliveryTime; // this.receiveTime = receiveTime; // this.returnGoodsTime = returnGoodsTime; // this.refundTime = refundTime; // this.closeTime = closeTime; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Order() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Integer getShippingId() { // return shippingId; // } // // public void setShippingId(Integer shippingId) { // this.shippingId = shippingId; // } // // public Long getOrderNo() { // return orderNo; // } // // public void setOrderNo(Long orderNo) { // this.orderNo = orderNo; // } // // public BigDecimal getPayment() { // return payment; // } // // public void setPayment(BigDecimal payment) { // this.payment = payment; // } // // public Integer getPaymentType() { // return paymentType; // } // // public void setPaymentType(Integer paymentType) { // this.paymentType = paymentType; // } // // public BigDecimal getPostage() { // return postage; // } // // public void setPostage(BigDecimal postage) { // this.postage = postage; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public Date getPaymentTime() { // return paymentTime; // } // // public void setPaymentTime(Date paymentTime) { // this.paymentTime = paymentTime; // } // // public Date getDeliveryTime() { // return deliveryTime; // } // // public void setDeliveryTime(Date deliveryTime) { // this.deliveryTime = deliveryTime; // } // // public Date getReceiveTime() { // return receiveTime; // } // // public void setReceiveTime(Date receiveTime) { // this.receiveTime = receiveTime; // } // // public Date getReturnGoodsTime() { // return returnGoodsTime; // } // // public void setReturnGoodsTime(Date returnGoodsTime) { // this.returnGoodsTime = returnGoodsTime; // } // // public Date getRefundTime() { // return refundTime; // } // // public void setRefundTime(Date refundTime) { // this.refundTime = refundTime; // } // // public Date getCloseTime() { // return closeTime; // } // // public void setCloseTime(Date closeTime) { // this.closeTime = closeTime; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // }
import java.util.List; import org.apache.ibatis.annotations.Param; import com.shop.pojo.Order;
package com.shop.dao; public interface OrderMapper { int deleteByPrimaryKey(Integer id);
// Path: src/main/java/com/shop/pojo/Order.java // public class Order { // private Integer id; // // private Integer userId; // // private Integer shippingId; // // private Long orderNo; // // private BigDecimal payment; // // private Integer paymentType; // // private BigDecimal postage; // // private Integer status; // // private Date paymentTime; // // private Date deliveryTime; // // private Date receiveTime; // // private Date returnGoodsTime; // // private Date refundTime; // // private Date closeTime; // // private Date createTime; // // private Date updateTime; // // public Order(Integer id, Integer userId, Integer shippingId, Long orderNo, BigDecimal payment, Integer paymentType, BigDecimal postage, Integer status, Date paymentTime, Date deliveryTime, Date receiveTime, Date returnGoodsTime, Date refundTime, Date closeTime, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.shippingId = shippingId; // this.orderNo = orderNo; // this.payment = payment; // this.paymentType = paymentType; // this.postage = postage; // this.status = status; // this.paymentTime = paymentTime; // this.deliveryTime = deliveryTime; // this.receiveTime = receiveTime; // this.returnGoodsTime = returnGoodsTime; // this.refundTime = refundTime; // this.closeTime = closeTime; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Order() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Integer getShippingId() { // return shippingId; // } // // public void setShippingId(Integer shippingId) { // this.shippingId = shippingId; // } // // public Long getOrderNo() { // return orderNo; // } // // public void setOrderNo(Long orderNo) { // this.orderNo = orderNo; // } // // public BigDecimal getPayment() { // return payment; // } // // public void setPayment(BigDecimal payment) { // this.payment = payment; // } // // public Integer getPaymentType() { // return paymentType; // } // // public void setPaymentType(Integer paymentType) { // this.paymentType = paymentType; // } // // public BigDecimal getPostage() { // return postage; // } // // public void setPostage(BigDecimal postage) { // this.postage = postage; // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public Date getPaymentTime() { // return paymentTime; // } // // public void setPaymentTime(Date paymentTime) { // this.paymentTime = paymentTime; // } // // public Date getDeliveryTime() { // return deliveryTime; // } // // public void setDeliveryTime(Date deliveryTime) { // this.deliveryTime = deliveryTime; // } // // public Date getReceiveTime() { // return receiveTime; // } // // public void setReceiveTime(Date receiveTime) { // this.receiveTime = receiveTime; // } // // public Date getReturnGoodsTime() { // return returnGoodsTime; // } // // public void setReturnGoodsTime(Date returnGoodsTime) { // this.returnGoodsTime = returnGoodsTime; // } // // public Date getRefundTime() { // return refundTime; // } // // public void setRefundTime(Date refundTime) { // this.refundTime = refundTime; // } // // public Date getCloseTime() { // return closeTime; // } // // public void setCloseTime(Date closeTime) { // this.closeTime = closeTime; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // } // Path: src/main/java/com/shop/dao/OrderMapper.java import java.util.List; import org.apache.ibatis.annotations.Param; import com.shop.pojo.Order; package com.shop.dao; public interface OrderMapper { int deleteByPrimaryKey(Integer id);
int insert(Order record);
wuyan345/onlineShop
src/main/java/com/shop/dao/UserMapper.java
// Path: src/main/java/com/shop/pojo/User.java // public class User { // private Integer id; // // private String username; // // private String password; // // private String phone; // // private String email; // // private String question; // // private String answer; // // private Date createTime; // // private Date updateTime; // // public User(Integer id, String username, String password, String phone, String email, String question, String answer, Date createTime, Date updateTime) { // this.id = id; // this.username = username; // this.password = password; // this.phone = phone; // this.email = email; // this.question = question; // this.answer = answer; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public User() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username == null ? null : username.trim(); // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email == null ? null : email.trim(); // } // // public String getQuestion() { // return question; // } // // public void setQuestion(String question) { // this.question = question == null ? null : question.trim(); // } // // public String getAnswer() { // return answer; // } // // public void setAnswer(String answer) { // this.answer = answer == null ? null : answer.trim(); // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // }
import org.apache.ibatis.annotations.Param; import com.shop.pojo.User;
package com.shop.dao; public interface UserMapper { int deleteByPrimaryKey(Integer id);
// Path: src/main/java/com/shop/pojo/User.java // public class User { // private Integer id; // // private String username; // // private String password; // // private String phone; // // private String email; // // private String question; // // private String answer; // // private Date createTime; // // private Date updateTime; // // public User(Integer id, String username, String password, String phone, String email, String question, String answer, Date createTime, Date updateTime) { // this.id = id; // this.username = username; // this.password = password; // this.phone = phone; // this.email = email; // this.question = question; // this.answer = answer; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public User() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username == null ? null : username.trim(); // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email == null ? null : email.trim(); // } // // public String getQuestion() { // return question; // } // // public void setQuestion(String question) { // this.question = question == null ? null : question.trim(); // } // // public String getAnswer() { // return answer; // } // // public void setAnswer(String answer) { // this.answer = answer == null ? null : answer.trim(); // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // } // Path: src/main/java/com/shop/dao/UserMapper.java import org.apache.ibatis.annotations.Param; import com.shop.pojo.User; package com.shop.dao; public interface UserMapper { int deleteByPrimaryKey(Integer id);
int insert(User record);
wuyan345/onlineShop
src/main/java/com/shop/dao/PayInfoMapper.java
// Path: src/main/java/com/shop/pojo/PayInfo.java // public class PayInfo { // private Integer id; // // private Integer userId; // // private Long orderNo; // // private Integer payPlatform; // // private String platformNumber; // // private String platformStatus; // // private Date createTime; // // private Date updateTime; // // public PayInfo(Integer id, Integer userId, Long orderNo, Integer payPlatform, String platformNumber, String platformStatus, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.orderNo = orderNo; // this.payPlatform = payPlatform; // this.platformNumber = platformNumber; // this.platformStatus = platformStatus; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public PayInfo() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Long getOrderNo() { // return orderNo; // } // // public void setOrderNo(Long orderNo) { // this.orderNo = orderNo; // } // // public Integer getPayPlatform() { // return payPlatform; // } // // public void setPayPlatform(Integer payPlatform) { // this.payPlatform = payPlatform; // } // // public String getPlatformNumber() { // return platformNumber; // } // // public void setPlatformNumber(String platformNumber) { // this.platformNumber = platformNumber == null ? null : platformNumber.trim(); // } // // public String getPlatformStatus() { // return platformStatus; // } // // public void setPlatformStatus(String platformStatus) { // this.platformStatus = platformStatus == null ? null : platformStatus.trim(); // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // }
import com.shop.pojo.PayInfo;
package com.shop.dao; public interface PayInfoMapper { int deleteByPrimaryKey(Integer id);
// Path: src/main/java/com/shop/pojo/PayInfo.java // public class PayInfo { // private Integer id; // // private Integer userId; // // private Long orderNo; // // private Integer payPlatform; // // private String platformNumber; // // private String platformStatus; // // private Date createTime; // // private Date updateTime; // // public PayInfo(Integer id, Integer userId, Long orderNo, Integer payPlatform, String platformNumber, String platformStatus, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.orderNo = orderNo; // this.payPlatform = payPlatform; // this.platformNumber = platformNumber; // this.platformStatus = platformStatus; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public PayInfo() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Long getOrderNo() { // return orderNo; // } // // public void setOrderNo(Long orderNo) { // this.orderNo = orderNo; // } // // public Integer getPayPlatform() { // return payPlatform; // } // // public void setPayPlatform(Integer payPlatform) { // this.payPlatform = payPlatform; // } // // public String getPlatformNumber() { // return platformNumber; // } // // public void setPlatformNumber(String platformNumber) { // this.platformNumber = platformNumber == null ? null : platformNumber.trim(); // } // // public String getPlatformStatus() { // return platformStatus; // } // // public void setPlatformStatus(String platformStatus) { // this.platformStatus = platformStatus == null ? null : platformStatus.trim(); // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // } // Path: src/main/java/com/shop/dao/PayInfoMapper.java import com.shop.pojo.PayInfo; package com.shop.dao; public interface PayInfoMapper { int deleteByPrimaryKey(Integer id);
int insert(PayInfo record);
wuyan345/onlineShop
src/main/java/com/shop/controller/portal/CategoryController.java
// Path: src/main/java/com/shop/common/Message.java // public class Message <T> { // // private String msg; // private int status; // private T data; // // private Message(int status) { // super(); // this.status = status; // } // private Message(String msg, int status) { // super(); // this.msg = msg; // this.status = status; // } // private Message(T data, int status) { // super(); // this.status = status; // this.data = data; // } // private Message(String msg, int status, T data) { // super(); // this.msg = msg; // this.status = status; // this.data = data; // } // // public T getData() { // return data; // } // public String getMsg() { // return msg; // } // public int getStatus() { // return status; // } // // // json里不会出现"success : true"或"success : false" // @JsonIgnore // public boolean isSuccess(){ // if(status == Const.SUCCESS) // return true; // return false; // } // // public static <T> Message<T> success(){ // return new Message<T>(Const.SUCCESS); // } // public static <T> Message<T> successMsg(String msg){ // return new Message<T>(msg, Const.SUCCESS); // } // public static <T> Message<T> successData(T data){ // return new Message<T>(data, Const.SUCCESS); // } // public static <T> Message<T> successMsgData(String msg, T data){ // return new Message<T>(msg, Const.SUCCESS, data); // } // // public static <T> Message<T> errorMsg(String msg){ // return new Message<T>(msg, Const.FAILED); // } // public static <T> Message<T> errorMsgData(String msg, T data){ // return new Message<T>(msg, Const.FAILED, data); // } // } // // Path: src/main/java/com/shop/service/ICategoryService.java // public interface ICategoryService { // // Message addCategory(int parentId, String name); // // Message editCategoryName(int categoryId, String name); // // Message getChrildrenCategory(int categoryId); // // Message getDeepCategory(int categoryId); // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.shop.common.Message; import com.shop.service.ICategoryService;
package com.shop.controller.portal; @Controller @RequestMapping("/category") public class CategoryController { @Autowired
// Path: src/main/java/com/shop/common/Message.java // public class Message <T> { // // private String msg; // private int status; // private T data; // // private Message(int status) { // super(); // this.status = status; // } // private Message(String msg, int status) { // super(); // this.msg = msg; // this.status = status; // } // private Message(T data, int status) { // super(); // this.status = status; // this.data = data; // } // private Message(String msg, int status, T data) { // super(); // this.msg = msg; // this.status = status; // this.data = data; // } // // public T getData() { // return data; // } // public String getMsg() { // return msg; // } // public int getStatus() { // return status; // } // // // json里不会出现"success : true"或"success : false" // @JsonIgnore // public boolean isSuccess(){ // if(status == Const.SUCCESS) // return true; // return false; // } // // public static <T> Message<T> success(){ // return new Message<T>(Const.SUCCESS); // } // public static <T> Message<T> successMsg(String msg){ // return new Message<T>(msg, Const.SUCCESS); // } // public static <T> Message<T> successData(T data){ // return new Message<T>(data, Const.SUCCESS); // } // public static <T> Message<T> successMsgData(String msg, T data){ // return new Message<T>(msg, Const.SUCCESS, data); // } // // public static <T> Message<T> errorMsg(String msg){ // return new Message<T>(msg, Const.FAILED); // } // public static <T> Message<T> errorMsgData(String msg, T data){ // return new Message<T>(msg, Const.FAILED, data); // } // } // // Path: src/main/java/com/shop/service/ICategoryService.java // public interface ICategoryService { // // Message addCategory(int parentId, String name); // // Message editCategoryName(int categoryId, String name); // // Message getChrildrenCategory(int categoryId); // // Message getDeepCategory(int categoryId); // } // Path: src/main/java/com/shop/controller/portal/CategoryController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.shop.common.Message; import com.shop.service.ICategoryService; package com.shop.controller.portal; @Controller @RequestMapping("/category") public class CategoryController { @Autowired
private ICategoryService iCategoryService;
wuyan345/onlineShop
src/main/java/com/shop/dao/CategoryMapper.java
// Path: src/main/java/com/shop/pojo/Category.java // public class Category { // private Integer id; // // private Integer parentId; // // private String name; // // private Integer status; // // private Date createTime; // // private Date updateTime; // // public Category(Integer id, Integer parentId, String name, Integer status, Date createTime, Date updateTime) { // this.id = id; // this.parentId = parentId; // this.name = name; // this.status = status; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Category() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getParentId() { // return parentId; // } // // public void setParentId(Integer parentId) { // this.parentId = parentId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name == null ? null : name.trim(); // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // @Override // public String toString() { // return "Category [id=" + id + ", parentId=" + parentId + ", name=" + name + ", status=" + status // + ", createTime=" + createTime + ", updateTime=" + updateTime + "]"; // } // }
import java.util.List; import com.shop.pojo.Category;
package com.shop.dao; public interface CategoryMapper { int deleteByPrimaryKey(Integer id);
// Path: src/main/java/com/shop/pojo/Category.java // public class Category { // private Integer id; // // private Integer parentId; // // private String name; // // private Integer status; // // private Date createTime; // // private Date updateTime; // // public Category(Integer id, Integer parentId, String name, Integer status, Date createTime, Date updateTime) { // this.id = id; // this.parentId = parentId; // this.name = name; // this.status = status; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Category() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getParentId() { // return parentId; // } // // public void setParentId(Integer parentId) { // this.parentId = parentId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name == null ? null : name.trim(); // } // // public Integer getStatus() { // return status; // } // // public void setStatus(Integer status) { // this.status = status; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // // @Override // public String toString() { // return "Category [id=" + id + ", parentId=" + parentId + ", name=" + name + ", status=" + status // + ", createTime=" + createTime + ", updateTime=" + updateTime + "]"; // } // } // Path: src/main/java/com/shop/dao/CategoryMapper.java import java.util.List; import com.shop.pojo.Category; package com.shop.dao; public interface CategoryMapper { int deleteByPrimaryKey(Integer id);
int insert(Category record);
wuyan345/onlineShop
src/main/java/com/shop/utils/FTPUtil.java
// Path: src/main/java/com/shop/common/Message.java // public class Message <T> { // // private String msg; // private int status; // private T data; // // private Message(int status) { // super(); // this.status = status; // } // private Message(String msg, int status) { // super(); // this.msg = msg; // this.status = status; // } // private Message(T data, int status) { // super(); // this.status = status; // this.data = data; // } // private Message(String msg, int status, T data) { // super(); // this.msg = msg; // this.status = status; // this.data = data; // } // // public T getData() { // return data; // } // public String getMsg() { // return msg; // } // public int getStatus() { // return status; // } // // // json里不会出现"success : true"或"success : false" // @JsonIgnore // public boolean isSuccess(){ // if(status == Const.SUCCESS) // return true; // return false; // } // // public static <T> Message<T> success(){ // return new Message<T>(Const.SUCCESS); // } // public static <T> Message<T> successMsg(String msg){ // return new Message<T>(msg, Const.SUCCESS); // } // public static <T> Message<T> successData(T data){ // return new Message<T>(data, Const.SUCCESS); // } // public static <T> Message<T> successMsgData(String msg, T data){ // return new Message<T>(msg, Const.SUCCESS, data); // } // // public static <T> Message<T> errorMsg(String msg){ // return new Message<T>(msg, Const.FAILED); // } // public static <T> Message<T> errorMsgData(String msg, T data){ // return new Message<T>(msg, Const.FAILED, data); // } // }
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.apache.commons.net.ftp.FTPClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.multipart.MultipartFile; import com.shop.common.Message;
package com.shop.utils; public class FTPUtil { private static final Logger logger = LoggerFactory.getLogger(FTPUtil.class); private static final String IP = PropertiesUtil.getProperty("ftp.ip"); private static final String USERNAME = PropertiesUtil.getProperty("ftp.username"); private static final String PASSWORD = PropertiesUtil.getProperty("ftp.password");
// Path: src/main/java/com/shop/common/Message.java // public class Message <T> { // // private String msg; // private int status; // private T data; // // private Message(int status) { // super(); // this.status = status; // } // private Message(String msg, int status) { // super(); // this.msg = msg; // this.status = status; // } // private Message(T data, int status) { // super(); // this.status = status; // this.data = data; // } // private Message(String msg, int status, T data) { // super(); // this.msg = msg; // this.status = status; // this.data = data; // } // // public T getData() { // return data; // } // public String getMsg() { // return msg; // } // public int getStatus() { // return status; // } // // // json里不会出现"success : true"或"success : false" // @JsonIgnore // public boolean isSuccess(){ // if(status == Const.SUCCESS) // return true; // return false; // } // // public static <T> Message<T> success(){ // return new Message<T>(Const.SUCCESS); // } // public static <T> Message<T> successMsg(String msg){ // return new Message<T>(msg, Const.SUCCESS); // } // public static <T> Message<T> successData(T data){ // return new Message<T>(data, Const.SUCCESS); // } // public static <T> Message<T> successMsgData(String msg, T data){ // return new Message<T>(msg, Const.SUCCESS, data); // } // // public static <T> Message<T> errorMsg(String msg){ // return new Message<T>(msg, Const.FAILED); // } // public static <T> Message<T> errorMsgData(String msg, T data){ // return new Message<T>(msg, Const.FAILED, data); // } // } // Path: src/main/java/com/shop/utils/FTPUtil.java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.apache.commons.net.ftp.FTPClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.multipart.MultipartFile; import com.shop.common.Message; package com.shop.utils; public class FTPUtil { private static final Logger logger = LoggerFactory.getLogger(FTPUtil.class); private static final String IP = PropertiesUtil.getProperty("ftp.ip"); private static final String USERNAME = PropertiesUtil.getProperty("ftp.username"); private static final String PASSWORD = PropertiesUtil.getProperty("ftp.password");
public static Message<List<String>> upload(MultipartFile[] multipartFiles){
wuyan345/onlineShop
src/main/java/com/shop/dao/LevelMapper.java
// Path: src/main/java/com/shop/pojo/Level.java // public class Level { // private Integer id; // // private Integer userId; // // private Integer level; // // private Integer exp; // // private Date createTime; // // private Date updateTime; // // public Level(Integer id, Integer userId, Integer level, Integer exp, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.level = level; // this.exp = exp; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Level() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Integer getLevel() { // return level; // } // // public void setLevel(Integer level) { // this.level = level; // } // // public Integer getExp() { // return exp; // } // // public void setExp(Integer exp) { // this.exp = exp; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // }
import com.shop.pojo.Level;
package com.shop.dao; public interface LevelMapper { int deleteByPrimaryKey(Integer id);
// Path: src/main/java/com/shop/pojo/Level.java // public class Level { // private Integer id; // // private Integer userId; // // private Integer level; // // private Integer exp; // // private Date createTime; // // private Date updateTime; // // public Level(Integer id, Integer userId, Integer level, Integer exp, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.level = level; // this.exp = exp; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Level() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Integer getLevel() { // return level; // } // // public void setLevel(Integer level) { // this.level = level; // } // // public Integer getExp() { // return exp; // } // // public void setExp(Integer exp) { // this.exp = exp; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // } // Path: src/main/java/com/shop/dao/LevelMapper.java import com.shop.pojo.Level; package com.shop.dao; public interface LevelMapper { int deleteByPrimaryKey(Integer id);
int insert(Level record);
wuyan345/onlineShop
src/main/java/com/shop/controller/portal/GoodsController.java
// Path: src/main/java/com/shop/common/Message.java // public class Message <T> { // // private String msg; // private int status; // private T data; // // private Message(int status) { // super(); // this.status = status; // } // private Message(String msg, int status) { // super(); // this.msg = msg; // this.status = status; // } // private Message(T data, int status) { // super(); // this.status = status; // this.data = data; // } // private Message(String msg, int status, T data) { // super(); // this.msg = msg; // this.status = status; // this.data = data; // } // // public T getData() { // return data; // } // public String getMsg() { // return msg; // } // public int getStatus() { // return status; // } // // // json里不会出现"success : true"或"success : false" // @JsonIgnore // public boolean isSuccess(){ // if(status == Const.SUCCESS) // return true; // return false; // } // // public static <T> Message<T> success(){ // return new Message<T>(Const.SUCCESS); // } // public static <T> Message<T> successMsg(String msg){ // return new Message<T>(msg, Const.SUCCESS); // } // public static <T> Message<T> successData(T data){ // return new Message<T>(data, Const.SUCCESS); // } // public static <T> Message<T> successMsgData(String msg, T data){ // return new Message<T>(msg, Const.SUCCESS, data); // } // // public static <T> Message<T> errorMsg(String msg){ // return new Message<T>(msg, Const.FAILED); // } // public static <T> Message<T> errorMsgData(String msg, T data){ // return new Message<T>(msg, Const.FAILED, data); // } // } // // Path: src/main/java/com/shop/service/IGoodsService.java // public interface IGoodsService { // // Message addGoods(Goods goods); // // Message<PageInfo> list(Integer categoryId, int pageNum, int pageSize); // // Message getGoodsDetail(int goodsId); // // Message<PageInfo> searchGoods(String keyword, int pageNum, int pageSize); // }
import java.io.UnsupportedEncodingException; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.github.pagehelper.PageInfo; import com.shop.common.Message; import com.shop.service.IGoodsService;
package com.shop.controller.portal; @Controller @RequestMapping("/goods") public class GoodsController { @Autowired
// Path: src/main/java/com/shop/common/Message.java // public class Message <T> { // // private String msg; // private int status; // private T data; // // private Message(int status) { // super(); // this.status = status; // } // private Message(String msg, int status) { // super(); // this.msg = msg; // this.status = status; // } // private Message(T data, int status) { // super(); // this.status = status; // this.data = data; // } // private Message(String msg, int status, T data) { // super(); // this.msg = msg; // this.status = status; // this.data = data; // } // // public T getData() { // return data; // } // public String getMsg() { // return msg; // } // public int getStatus() { // return status; // } // // // json里不会出现"success : true"或"success : false" // @JsonIgnore // public boolean isSuccess(){ // if(status == Const.SUCCESS) // return true; // return false; // } // // public static <T> Message<T> success(){ // return new Message<T>(Const.SUCCESS); // } // public static <T> Message<T> successMsg(String msg){ // return new Message<T>(msg, Const.SUCCESS); // } // public static <T> Message<T> successData(T data){ // return new Message<T>(data, Const.SUCCESS); // } // public static <T> Message<T> successMsgData(String msg, T data){ // return new Message<T>(msg, Const.SUCCESS, data); // } // // public static <T> Message<T> errorMsg(String msg){ // return new Message<T>(msg, Const.FAILED); // } // public static <T> Message<T> errorMsgData(String msg, T data){ // return new Message<T>(msg, Const.FAILED, data); // } // } // // Path: src/main/java/com/shop/service/IGoodsService.java // public interface IGoodsService { // // Message addGoods(Goods goods); // // Message<PageInfo> list(Integer categoryId, int pageNum, int pageSize); // // Message getGoodsDetail(int goodsId); // // Message<PageInfo> searchGoods(String keyword, int pageNum, int pageSize); // } // Path: src/main/java/com/shop/controller/portal/GoodsController.java import java.io.UnsupportedEncodingException; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.github.pagehelper.PageInfo; import com.shop.common.Message; import com.shop.service.IGoodsService; package com.shop.controller.portal; @Controller @RequestMapping("/goods") public class GoodsController { @Autowired
private IGoodsService iGoodsService;
wuyan345/onlineShop
src/main/java/com/shop/controller/portal/GoodsController.java
// Path: src/main/java/com/shop/common/Message.java // public class Message <T> { // // private String msg; // private int status; // private T data; // // private Message(int status) { // super(); // this.status = status; // } // private Message(String msg, int status) { // super(); // this.msg = msg; // this.status = status; // } // private Message(T data, int status) { // super(); // this.status = status; // this.data = data; // } // private Message(String msg, int status, T data) { // super(); // this.msg = msg; // this.status = status; // this.data = data; // } // // public T getData() { // return data; // } // public String getMsg() { // return msg; // } // public int getStatus() { // return status; // } // // // json里不会出现"success : true"或"success : false" // @JsonIgnore // public boolean isSuccess(){ // if(status == Const.SUCCESS) // return true; // return false; // } // // public static <T> Message<T> success(){ // return new Message<T>(Const.SUCCESS); // } // public static <T> Message<T> successMsg(String msg){ // return new Message<T>(msg, Const.SUCCESS); // } // public static <T> Message<T> successData(T data){ // return new Message<T>(data, Const.SUCCESS); // } // public static <T> Message<T> successMsgData(String msg, T data){ // return new Message<T>(msg, Const.SUCCESS, data); // } // // public static <T> Message<T> errorMsg(String msg){ // return new Message<T>(msg, Const.FAILED); // } // public static <T> Message<T> errorMsgData(String msg, T data){ // return new Message<T>(msg, Const.FAILED, data); // } // } // // Path: src/main/java/com/shop/service/IGoodsService.java // public interface IGoodsService { // // Message addGoods(Goods goods); // // Message<PageInfo> list(Integer categoryId, int pageNum, int pageSize); // // Message getGoodsDetail(int goodsId); // // Message<PageInfo> searchGoods(String keyword, int pageNum, int pageSize); // }
import java.io.UnsupportedEncodingException; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.github.pagehelper.PageInfo; import com.shop.common.Message; import com.shop.service.IGoodsService;
package com.shop.controller.portal; @Controller @RequestMapping("/goods") public class GoodsController { @Autowired private IGoodsService iGoodsService; @RequestMapping("/test") @ResponseBody public void test(String a, String b){ System.out.println(new Date()); System.out.println("a: " + a + ", b: " + b); } @RequestMapping("/list") @ResponseBody
// Path: src/main/java/com/shop/common/Message.java // public class Message <T> { // // private String msg; // private int status; // private T data; // // private Message(int status) { // super(); // this.status = status; // } // private Message(String msg, int status) { // super(); // this.msg = msg; // this.status = status; // } // private Message(T data, int status) { // super(); // this.status = status; // this.data = data; // } // private Message(String msg, int status, T data) { // super(); // this.msg = msg; // this.status = status; // this.data = data; // } // // public T getData() { // return data; // } // public String getMsg() { // return msg; // } // public int getStatus() { // return status; // } // // // json里不会出现"success : true"或"success : false" // @JsonIgnore // public boolean isSuccess(){ // if(status == Const.SUCCESS) // return true; // return false; // } // // public static <T> Message<T> success(){ // return new Message<T>(Const.SUCCESS); // } // public static <T> Message<T> successMsg(String msg){ // return new Message<T>(msg, Const.SUCCESS); // } // public static <T> Message<T> successData(T data){ // return new Message<T>(data, Const.SUCCESS); // } // public static <T> Message<T> successMsgData(String msg, T data){ // return new Message<T>(msg, Const.SUCCESS, data); // } // // public static <T> Message<T> errorMsg(String msg){ // return new Message<T>(msg, Const.FAILED); // } // public static <T> Message<T> errorMsgData(String msg, T data){ // return new Message<T>(msg, Const.FAILED, data); // } // } // // Path: src/main/java/com/shop/service/IGoodsService.java // public interface IGoodsService { // // Message addGoods(Goods goods); // // Message<PageInfo> list(Integer categoryId, int pageNum, int pageSize); // // Message getGoodsDetail(int goodsId); // // Message<PageInfo> searchGoods(String keyword, int pageNum, int pageSize); // } // Path: src/main/java/com/shop/controller/portal/GoodsController.java import java.io.UnsupportedEncodingException; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.github.pagehelper.PageInfo; import com.shop.common.Message; import com.shop.service.IGoodsService; package com.shop.controller.portal; @Controller @RequestMapping("/goods") public class GoodsController { @Autowired private IGoodsService iGoodsService; @RequestMapping("/test") @ResponseBody public void test(String a, String b){ System.out.println(new Date()); System.out.println("a: " + a + ", b: " + b); } @RequestMapping("/list") @ResponseBody
public Message<PageInfo> list(Integer categoryId){
wuyan345/onlineShop
src/main/java/com/shop/common/LoginCheck.java
// Path: src/main/java/com/shop/dao/RoleMapper.java // public interface RoleMapper { // int deleteByPrimaryKey(Integer id); // // int insert(Role record); // // int insertSelective(Role record); // // Role selectByPrimaryKey(Integer id); // // int updateByPrimaryKeySelective(Role record); // // int updateByPrimaryKey(Role record); // // Role selectByUserId(int userId); // } // // Path: src/main/java/com/shop/pojo/Role.java // public class Role { // private Integer id; // // private Integer userId; // // private Integer roleNo; // // private Date createTime; // // private Date updateTime; // // public Role(Integer id, Integer userId, Integer roleNo, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.roleNo = roleNo; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Role() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Integer getRoleNo() { // return roleNo; // } // // public void setRoleNo(Integer roleNo) { // this.roleNo = roleNo; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // } // // Path: src/main/java/com/shop/pojo/User.java // public class User { // private Integer id; // // private String username; // // private String password; // // private String phone; // // private String email; // // private String question; // // private String answer; // // private Date createTime; // // private Date updateTime; // // public User(Integer id, String username, String password, String phone, String email, String question, String answer, Date createTime, Date updateTime) { // this.id = id; // this.username = username; // this.password = password; // this.phone = phone; // this.email = email; // this.question = question; // this.answer = answer; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public User() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username == null ? null : username.trim(); // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email == null ? null : email.trim(); // } // // public String getQuestion() { // return question; // } // // public void setQuestion(String question) { // this.question = question == null ? null : question.trim(); // } // // public String getAnswer() { // return answer; // } // // public void setAnswer(String answer) { // this.answer = answer == null ? null : answer.trim(); // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // }
import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.shop.dao.RoleMapper; import com.shop.pojo.Role; import com.shop.pojo.User;
package com.shop.common; @Component("loginCheck") public class LoginCheck { @Autowired
// Path: src/main/java/com/shop/dao/RoleMapper.java // public interface RoleMapper { // int deleteByPrimaryKey(Integer id); // // int insert(Role record); // // int insertSelective(Role record); // // Role selectByPrimaryKey(Integer id); // // int updateByPrimaryKeySelective(Role record); // // int updateByPrimaryKey(Role record); // // Role selectByUserId(int userId); // } // // Path: src/main/java/com/shop/pojo/Role.java // public class Role { // private Integer id; // // private Integer userId; // // private Integer roleNo; // // private Date createTime; // // private Date updateTime; // // public Role(Integer id, Integer userId, Integer roleNo, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.roleNo = roleNo; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Role() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Integer getRoleNo() { // return roleNo; // } // // public void setRoleNo(Integer roleNo) { // this.roleNo = roleNo; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // } // // Path: src/main/java/com/shop/pojo/User.java // public class User { // private Integer id; // // private String username; // // private String password; // // private String phone; // // private String email; // // private String question; // // private String answer; // // private Date createTime; // // private Date updateTime; // // public User(Integer id, String username, String password, String phone, String email, String question, String answer, Date createTime, Date updateTime) { // this.id = id; // this.username = username; // this.password = password; // this.phone = phone; // this.email = email; // this.question = question; // this.answer = answer; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public User() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username == null ? null : username.trim(); // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email == null ? null : email.trim(); // } // // public String getQuestion() { // return question; // } // // public void setQuestion(String question) { // this.question = question == null ? null : question.trim(); // } // // public String getAnswer() { // return answer; // } // // public void setAnswer(String answer) { // this.answer = answer == null ? null : answer.trim(); // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // } // Path: src/main/java/com/shop/common/LoginCheck.java import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.shop.dao.RoleMapper; import com.shop.pojo.Role; import com.shop.pojo.User; package com.shop.common; @Component("loginCheck") public class LoginCheck { @Autowired
private RoleMapper roleMapper;
wuyan345/onlineShop
src/main/java/com/shop/common/LoginCheck.java
// Path: src/main/java/com/shop/dao/RoleMapper.java // public interface RoleMapper { // int deleteByPrimaryKey(Integer id); // // int insert(Role record); // // int insertSelective(Role record); // // Role selectByPrimaryKey(Integer id); // // int updateByPrimaryKeySelective(Role record); // // int updateByPrimaryKey(Role record); // // Role selectByUserId(int userId); // } // // Path: src/main/java/com/shop/pojo/Role.java // public class Role { // private Integer id; // // private Integer userId; // // private Integer roleNo; // // private Date createTime; // // private Date updateTime; // // public Role(Integer id, Integer userId, Integer roleNo, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.roleNo = roleNo; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Role() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Integer getRoleNo() { // return roleNo; // } // // public void setRoleNo(Integer roleNo) { // this.roleNo = roleNo; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // } // // Path: src/main/java/com/shop/pojo/User.java // public class User { // private Integer id; // // private String username; // // private String password; // // private String phone; // // private String email; // // private String question; // // private String answer; // // private Date createTime; // // private Date updateTime; // // public User(Integer id, String username, String password, String phone, String email, String question, String answer, Date createTime, Date updateTime) { // this.id = id; // this.username = username; // this.password = password; // this.phone = phone; // this.email = email; // this.question = question; // this.answer = answer; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public User() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username == null ? null : username.trim(); // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email == null ? null : email.trim(); // } // // public String getQuestion() { // return question; // } // // public void setQuestion(String question) { // this.question = question == null ? null : question.trim(); // } // // public String getAnswer() { // return answer; // } // // public void setAnswer(String answer) { // this.answer = answer == null ? null : answer.trim(); // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // }
import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.shop.dao.RoleMapper; import com.shop.pojo.Role; import com.shop.pojo.User;
package com.shop.common; @Component("loginCheck") public class LoginCheck { @Autowired private RoleMapper roleMapper; /** * 没登录: false<br> * 权限不对: false * @param session * @param roleNo * @return */ public boolean check(HttpSession session, int roleNo){
// Path: src/main/java/com/shop/dao/RoleMapper.java // public interface RoleMapper { // int deleteByPrimaryKey(Integer id); // // int insert(Role record); // // int insertSelective(Role record); // // Role selectByPrimaryKey(Integer id); // // int updateByPrimaryKeySelective(Role record); // // int updateByPrimaryKey(Role record); // // Role selectByUserId(int userId); // } // // Path: src/main/java/com/shop/pojo/Role.java // public class Role { // private Integer id; // // private Integer userId; // // private Integer roleNo; // // private Date createTime; // // private Date updateTime; // // public Role(Integer id, Integer userId, Integer roleNo, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.roleNo = roleNo; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Role() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Integer getRoleNo() { // return roleNo; // } // // public void setRoleNo(Integer roleNo) { // this.roleNo = roleNo; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // } // // Path: src/main/java/com/shop/pojo/User.java // public class User { // private Integer id; // // private String username; // // private String password; // // private String phone; // // private String email; // // private String question; // // private String answer; // // private Date createTime; // // private Date updateTime; // // public User(Integer id, String username, String password, String phone, String email, String question, String answer, Date createTime, Date updateTime) { // this.id = id; // this.username = username; // this.password = password; // this.phone = phone; // this.email = email; // this.question = question; // this.answer = answer; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public User() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username == null ? null : username.trim(); // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email == null ? null : email.trim(); // } // // public String getQuestion() { // return question; // } // // public void setQuestion(String question) { // this.question = question == null ? null : question.trim(); // } // // public String getAnswer() { // return answer; // } // // public void setAnswer(String answer) { // this.answer = answer == null ? null : answer.trim(); // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // } // Path: src/main/java/com/shop/common/LoginCheck.java import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.shop.dao.RoleMapper; import com.shop.pojo.Role; import com.shop.pojo.User; package com.shop.common; @Component("loginCheck") public class LoginCheck { @Autowired private RoleMapper roleMapper; /** * 没登录: false<br> * 权限不对: false * @param session * @param roleNo * @return */ public boolean check(HttpSession session, int roleNo){
User user = (User) session.getAttribute(Const.CURRENT_USER);
wuyan345/onlineShop
src/main/java/com/shop/common/LoginCheck.java
// Path: src/main/java/com/shop/dao/RoleMapper.java // public interface RoleMapper { // int deleteByPrimaryKey(Integer id); // // int insert(Role record); // // int insertSelective(Role record); // // Role selectByPrimaryKey(Integer id); // // int updateByPrimaryKeySelective(Role record); // // int updateByPrimaryKey(Role record); // // Role selectByUserId(int userId); // } // // Path: src/main/java/com/shop/pojo/Role.java // public class Role { // private Integer id; // // private Integer userId; // // private Integer roleNo; // // private Date createTime; // // private Date updateTime; // // public Role(Integer id, Integer userId, Integer roleNo, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.roleNo = roleNo; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Role() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Integer getRoleNo() { // return roleNo; // } // // public void setRoleNo(Integer roleNo) { // this.roleNo = roleNo; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // } // // Path: src/main/java/com/shop/pojo/User.java // public class User { // private Integer id; // // private String username; // // private String password; // // private String phone; // // private String email; // // private String question; // // private String answer; // // private Date createTime; // // private Date updateTime; // // public User(Integer id, String username, String password, String phone, String email, String question, String answer, Date createTime, Date updateTime) { // this.id = id; // this.username = username; // this.password = password; // this.phone = phone; // this.email = email; // this.question = question; // this.answer = answer; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public User() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username == null ? null : username.trim(); // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email == null ? null : email.trim(); // } // // public String getQuestion() { // return question; // } // // public void setQuestion(String question) { // this.question = question == null ? null : question.trim(); // } // // public String getAnswer() { // return answer; // } // // public void setAnswer(String answer) { // this.answer = answer == null ? null : answer.trim(); // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // }
import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.shop.dao.RoleMapper; import com.shop.pojo.Role; import com.shop.pojo.User;
package com.shop.common; @Component("loginCheck") public class LoginCheck { @Autowired private RoleMapper roleMapper; /** * 没登录: false<br> * 权限不对: false * @param session * @param roleNo * @return */ public boolean check(HttpSession session, int roleNo){ User user = (User) session.getAttribute(Const.CURRENT_USER); if(user == null) return false; // 未登录
// Path: src/main/java/com/shop/dao/RoleMapper.java // public interface RoleMapper { // int deleteByPrimaryKey(Integer id); // // int insert(Role record); // // int insertSelective(Role record); // // Role selectByPrimaryKey(Integer id); // // int updateByPrimaryKeySelective(Role record); // // int updateByPrimaryKey(Role record); // // Role selectByUserId(int userId); // } // // Path: src/main/java/com/shop/pojo/Role.java // public class Role { // private Integer id; // // private Integer userId; // // private Integer roleNo; // // private Date createTime; // // private Date updateTime; // // public Role(Integer id, Integer userId, Integer roleNo, Date createTime, Date updateTime) { // this.id = id; // this.userId = userId; // this.roleNo = roleNo; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public Role() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public Integer getRoleNo() { // return roleNo; // } // // public void setRoleNo(Integer roleNo) { // this.roleNo = roleNo; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // } // // Path: src/main/java/com/shop/pojo/User.java // public class User { // private Integer id; // // private String username; // // private String password; // // private String phone; // // private String email; // // private String question; // // private String answer; // // private Date createTime; // // private Date updateTime; // // public User(Integer id, String username, String password, String phone, String email, String question, String answer, Date createTime, Date updateTime) { // this.id = id; // this.username = username; // this.password = password; // this.phone = phone; // this.email = email; // this.question = question; // this.answer = answer; // this.createTime = createTime; // this.updateTime = updateTime; // } // // public User() { // super(); // } // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username == null ? null : username.trim(); // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password == null ? null : password.trim(); // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone == null ? null : phone.trim(); // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email == null ? null : email.trim(); // } // // public String getQuestion() { // return question; // } // // public void setQuestion(String question) { // this.question = question == null ? null : question.trim(); // } // // public String getAnswer() { // return answer; // } // // public void setAnswer(String answer) { // this.answer = answer == null ? null : answer.trim(); // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // public Date getUpdateTime() { // return updateTime; // } // // public void setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // } // } // Path: src/main/java/com/shop/common/LoginCheck.java import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.shop.dao.RoleMapper; import com.shop.pojo.Role; import com.shop.pojo.User; package com.shop.common; @Component("loginCheck") public class LoginCheck { @Autowired private RoleMapper roleMapper; /** * 没登录: false<br> * 权限不对: false * @param session * @param roleNo * @return */ public boolean check(HttpSession session, int roleNo){ User user = (User) session.getAttribute(Const.CURRENT_USER); if(user == null) return false; // 未登录
Role role = roleMapper.selectByUserId(user.getId());
rwitzel/CouchRepository
src/test/java/com/github/rwitzel/couchrepository/api/ProductRepository.java
// Path: src/test/java/com/github/rwitzel/couchrepository/model/Comment.java // public class Comment { // // private String author; // // private String text; // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((author == null) ? 0 : author.hashCode()); // result = prime * result + ((text == null) ? 0 : text.hashCode()); // return result; // } // // /** // * Generated by Eclipse. // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Comment other = (Comment) obj; // if (author == null) { // if (other.author != null) // return false; // } else if (!author.equals(other.author)) // return false; // if (text == null) { // if (other.text != null) // return false; // } else if (!text.equals(other.text)) // return false; // return true; // } // // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/Product.java // public class Product extends BaseDocument { // // private Date lastModification; // // private String manufacturerId; // // private String text; // // private ProductRating rating; // // private boolean hidden; // // private Integer numBuyers; // // private double weight; // // private BigDecimal price; // // private List<String> tags; // // private List<Comment> comments; // // private int isoProductCode; // // public Date getLastModification() { // return lastModification; // } // // public void setLastModification(Date lastModification) { // this.lastModification = lastModification; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public ProductRating getRating() { // return rating; // } // // public void setRating(ProductRating rating) { // this.rating = rating; // } // // public boolean isHidden() { // return hidden; // } // // public void setHidden(boolean hidden) { // this.hidden = hidden; // } // // public Integer getNumBuyers() { // return numBuyers; // } // // public void setNumBuyers(Integer numBuyers) { // this.numBuyers = numBuyers; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public List<String> getTags() { // if (tags == null) { // return new ArrayList<String>(); // } // return tags; // } // // public void setTags(List<String> tags) { // this.tags = tags; // } // // public List<Comment> getComments() { // if (comments == null) { // comments = new ArrayList<Comment>(); // } // return comments; // } // // public void setComments(List<Comment> comments) { // this.comments = comments; // } // // public String getManufacturerId() { // return manufacturerId; // } // // public void setManufacturerId(String manufacturerId) { // this.manufacturerId = manufacturerId; // } // // public int getIsoProductCode() { // return isoProductCode; // } // // public void setIsoProductCode(int isoProductCode) { // this.isoProductCode = isoProductCode; // } // }
import java.util.List; import javax.inject.Named; import com.github.rwitzel.couchrepository.model.Comment; import com.github.rwitzel.couchrepository.model.Product;
package com.github.rwitzel.couchrepository.api; public interface ProductRepository extends CouchDbCrudRepository<Product, String>, ProductRepositoryCustom { ViewResult findByComment(@Named("key") Object[] key, @Named("descending") Boolean descending, @Named("viewParams") ViewParams viewParams, @Named("valueType") Class<?> valueType); ViewResult findByComment();
// Path: src/test/java/com/github/rwitzel/couchrepository/model/Comment.java // public class Comment { // // private String author; // // private String text; // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((author == null) ? 0 : author.hashCode()); // result = prime * result + ((text == null) ? 0 : text.hashCode()); // return result; // } // // /** // * Generated by Eclipse. // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Comment other = (Comment) obj; // if (author == null) { // if (other.author != null) // return false; // } else if (!author.equals(other.author)) // return false; // if (text == null) { // if (other.text != null) // return false; // } else if (!text.equals(other.text)) // return false; // return true; // } // // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/Product.java // public class Product extends BaseDocument { // // private Date lastModification; // // private String manufacturerId; // // private String text; // // private ProductRating rating; // // private boolean hidden; // // private Integer numBuyers; // // private double weight; // // private BigDecimal price; // // private List<String> tags; // // private List<Comment> comments; // // private int isoProductCode; // // public Date getLastModification() { // return lastModification; // } // // public void setLastModification(Date lastModification) { // this.lastModification = lastModification; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public ProductRating getRating() { // return rating; // } // // public void setRating(ProductRating rating) { // this.rating = rating; // } // // public boolean isHidden() { // return hidden; // } // // public void setHidden(boolean hidden) { // this.hidden = hidden; // } // // public Integer getNumBuyers() { // return numBuyers; // } // // public void setNumBuyers(Integer numBuyers) { // this.numBuyers = numBuyers; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public List<String> getTags() { // if (tags == null) { // return new ArrayList<String>(); // } // return tags; // } // // public void setTags(List<String> tags) { // this.tags = tags; // } // // public List<Comment> getComments() { // if (comments == null) { // comments = new ArrayList<Comment>(); // } // return comments; // } // // public void setComments(List<Comment> comments) { // this.comments = comments; // } // // public String getManufacturerId() { // return manufacturerId; // } // // public void setManufacturerId(String manufacturerId) { // this.manufacturerId = manufacturerId; // } // // public int getIsoProductCode() { // return isoProductCode; // } // // public void setIsoProductCode(int isoProductCode) { // this.isoProductCode = isoProductCode; // } // } // Path: src/test/java/com/github/rwitzel/couchrepository/api/ProductRepository.java import java.util.List; import javax.inject.Named; import com.github.rwitzel.couchrepository.model.Comment; import com.github.rwitzel.couchrepository.model.Product; package com.github.rwitzel.couchrepository.api; public interface ProductRepository extends CouchDbCrudRepository<Product, String>, ProductRepositoryCustom { ViewResult findByComment(@Named("key") Object[] key, @Named("descending") Boolean descending, @Named("viewParams") ViewParams viewParams, @Named("valueType") Class<?> valueType); ViewResult findByComment();
List<Comment> findByComment(@Named("key") Object[] key, @Named("viewParams") ViewParams viewParams);
rwitzel/CouchRepository
src/test/java/com/github/rwitzel/couchrepository/api/AbstractCouchdbCrudRepositoryTest.java
// Path: src/test/java/com/github/rwitzel/couchrepository/api/viewresult/ProductSummary.java // public class ProductSummary { // // private ProductFacts facts; // // public ProductFacts getFacts() { // return facts; // } // // public void setFacts(ProductFacts facts) { // this.facts = facts; // } // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/Product.java // public class Product extends BaseDocument { // // private Date lastModification; // // private String manufacturerId; // // private String text; // // private ProductRating rating; // // private boolean hidden; // // private Integer numBuyers; // // private double weight; // // private BigDecimal price; // // private List<String> tags; // // private List<Comment> comments; // // private int isoProductCode; // // public Date getLastModification() { // return lastModification; // } // // public void setLastModification(Date lastModification) { // this.lastModification = lastModification; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public ProductRating getRating() { // return rating; // } // // public void setRating(ProductRating rating) { // this.rating = rating; // } // // public boolean isHidden() { // return hidden; // } // // public void setHidden(boolean hidden) { // this.hidden = hidden; // } // // public Integer getNumBuyers() { // return numBuyers; // } // // public void setNumBuyers(Integer numBuyers) { // this.numBuyers = numBuyers; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public List<String> getTags() { // if (tags == null) { // return new ArrayList<String>(); // } // return tags; // } // // public void setTags(List<String> tags) { // this.tags = tags; // } // // public List<Comment> getComments() { // if (comments == null) { // comments = new ArrayList<Comment>(); // } // return comments; // } // // public void setComments(List<Comment> comments) { // this.comments = comments; // } // // public String getManufacturerId() { // return manufacturerId; // } // // public void setManufacturerId(String manufacturerId) { // this.manufacturerId = manufacturerId; // } // // public int getIsoProductCode() { // return isoProductCode; // } // // public void setIsoProductCode(int isoProductCode) { // this.isoProductCode = isoProductCode; // } // }
import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.rwitzel.couchrepository.api.viewresult.ProductSummary; import com.github.rwitzel.couchrepository.model.Product;
package com.github.rwitzel.couchrepository.api; /** * Tests implementations of {@link CouchDbCrudRepository}. * * @author rwitzel */ public abstract class AbstractCouchdbCrudRepositoryTest extends AbstractCrudRepositoryTest { @Autowired
// Path: src/test/java/com/github/rwitzel/couchrepository/api/viewresult/ProductSummary.java // public class ProductSummary { // // private ProductFacts facts; // // public ProductFacts getFacts() { // return facts; // } // // public void setFacts(ProductFacts facts) { // this.facts = facts; // } // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/Product.java // public class Product extends BaseDocument { // // private Date lastModification; // // private String manufacturerId; // // private String text; // // private ProductRating rating; // // private boolean hidden; // // private Integer numBuyers; // // private double weight; // // private BigDecimal price; // // private List<String> tags; // // private List<Comment> comments; // // private int isoProductCode; // // public Date getLastModification() { // return lastModification; // } // // public void setLastModification(Date lastModification) { // this.lastModification = lastModification; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public ProductRating getRating() { // return rating; // } // // public void setRating(ProductRating rating) { // this.rating = rating; // } // // public boolean isHidden() { // return hidden; // } // // public void setHidden(boolean hidden) { // this.hidden = hidden; // } // // public Integer getNumBuyers() { // return numBuyers; // } // // public void setNumBuyers(Integer numBuyers) { // this.numBuyers = numBuyers; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public List<String> getTags() { // if (tags == null) { // return new ArrayList<String>(); // } // return tags; // } // // public void setTags(List<String> tags) { // this.tags = tags; // } // // public List<Comment> getComments() { // if (comments == null) { // comments = new ArrayList<Comment>(); // } // return comments; // } // // public void setComments(List<Comment> comments) { // this.comments = comments; // } // // public String getManufacturerId() { // return manufacturerId; // } // // public void setManufacturerId(String manufacturerId) { // this.manufacturerId = manufacturerId; // } // // public int getIsoProductCode() { // return isoProductCode; // } // // public void setIsoProductCode(int isoProductCode) { // this.isoProductCode = isoProductCode; // } // } // Path: src/test/java/com/github/rwitzel/couchrepository/api/AbstractCouchdbCrudRepositoryTest.java import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.rwitzel.couchrepository.api.viewresult.ProductSummary; import com.github.rwitzel.couchrepository.model.Product; package com.github.rwitzel.couchrepository.api; /** * Tests implementations of {@link CouchDbCrudRepository}. * * @author rwitzel */ public abstract class AbstractCouchdbCrudRepositoryTest extends AbstractCrudRepositoryTest { @Autowired
private CouchDbCrudRepository<Product, String> productRepo;
rwitzel/CouchRepository
src/test/java/com/github/rwitzel/couchrepository/api/AbstractCouchdbCrudRepositoryTest.java
// Path: src/test/java/com/github/rwitzel/couchrepository/api/viewresult/ProductSummary.java // public class ProductSummary { // // private ProductFacts facts; // // public ProductFacts getFacts() { // return facts; // } // // public void setFacts(ProductFacts facts) { // this.facts = facts; // } // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/Product.java // public class Product extends BaseDocument { // // private Date lastModification; // // private String manufacturerId; // // private String text; // // private ProductRating rating; // // private boolean hidden; // // private Integer numBuyers; // // private double weight; // // private BigDecimal price; // // private List<String> tags; // // private List<Comment> comments; // // private int isoProductCode; // // public Date getLastModification() { // return lastModification; // } // // public void setLastModification(Date lastModification) { // this.lastModification = lastModification; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public ProductRating getRating() { // return rating; // } // // public void setRating(ProductRating rating) { // this.rating = rating; // } // // public boolean isHidden() { // return hidden; // } // // public void setHidden(boolean hidden) { // this.hidden = hidden; // } // // public Integer getNumBuyers() { // return numBuyers; // } // // public void setNumBuyers(Integer numBuyers) { // this.numBuyers = numBuyers; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public List<String> getTags() { // if (tags == null) { // return new ArrayList<String>(); // } // return tags; // } // // public void setTags(List<String> tags) { // this.tags = tags; // } // // public List<Comment> getComments() { // if (comments == null) { // comments = new ArrayList<Comment>(); // } // return comments; // } // // public void setComments(List<Comment> comments) { // this.comments = comments; // } // // public String getManufacturerId() { // return manufacturerId; // } // // public void setManufacturerId(String manufacturerId) { // this.manufacturerId = manufacturerId; // } // // public int getIsoProductCode() { // return isoProductCode; // } // // public void setIsoProductCode(int isoProductCode) { // this.isoProductCode = isoProductCode; // } // }
import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.rwitzel.couchrepository.api.viewresult.ProductSummary; import com.github.rwitzel.couchrepository.model.Product;
package com.github.rwitzel.couchrepository.api; /** * Tests implementations of {@link CouchDbCrudRepository}. * * @author rwitzel */ public abstract class AbstractCouchdbCrudRepositoryTest extends AbstractCrudRepositoryTest { @Autowired private CouchDbCrudRepository<Product, String> productRepo; private Product p1 = readDocument("../documents/p1_allAttributesSet.js", Product.class); private Product p2 = newProduct("Oak table 1922", "Lumberjack1 Inc."); private Product p3 = newProduct("Oak table 1923", "Lumberjack1 Inc."); private Product p4 = newProduct("Oak table 1924", "Lumberjack Inc."); private ViewParams params = new ViewParams(); protected void deleteProductRepoAndCreateSomeProducts() { productRepo.deleteAll(); productRepo.save(p1); productRepo.save(p2); productRepo.save(p3); productRepo.save(p4); params.setView("by_manufacturerId"); params.setReduce(false); params.setKeyType(String.class);
// Path: src/test/java/com/github/rwitzel/couchrepository/api/viewresult/ProductSummary.java // public class ProductSummary { // // private ProductFacts facts; // // public ProductFacts getFacts() { // return facts; // } // // public void setFacts(ProductFacts facts) { // this.facts = facts; // } // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/Product.java // public class Product extends BaseDocument { // // private Date lastModification; // // private String manufacturerId; // // private String text; // // private ProductRating rating; // // private boolean hidden; // // private Integer numBuyers; // // private double weight; // // private BigDecimal price; // // private List<String> tags; // // private List<Comment> comments; // // private int isoProductCode; // // public Date getLastModification() { // return lastModification; // } // // public void setLastModification(Date lastModification) { // this.lastModification = lastModification; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public ProductRating getRating() { // return rating; // } // // public void setRating(ProductRating rating) { // this.rating = rating; // } // // public boolean isHidden() { // return hidden; // } // // public void setHidden(boolean hidden) { // this.hidden = hidden; // } // // public Integer getNumBuyers() { // return numBuyers; // } // // public void setNumBuyers(Integer numBuyers) { // this.numBuyers = numBuyers; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public List<String> getTags() { // if (tags == null) { // return new ArrayList<String>(); // } // return tags; // } // // public void setTags(List<String> tags) { // this.tags = tags; // } // // public List<Comment> getComments() { // if (comments == null) { // comments = new ArrayList<Comment>(); // } // return comments; // } // // public void setComments(List<Comment> comments) { // this.comments = comments; // } // // public String getManufacturerId() { // return manufacturerId; // } // // public void setManufacturerId(String manufacturerId) { // this.manufacturerId = manufacturerId; // } // // public int getIsoProductCode() { // return isoProductCode; // } // // public void setIsoProductCode(int isoProductCode) { // this.isoProductCode = isoProductCode; // } // } // Path: src/test/java/com/github/rwitzel/couchrepository/api/AbstractCouchdbCrudRepositoryTest.java import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.rwitzel.couchrepository.api.viewresult.ProductSummary; import com.github.rwitzel.couchrepository.model.Product; package com.github.rwitzel.couchrepository.api; /** * Tests implementations of {@link CouchDbCrudRepository}. * * @author rwitzel */ public abstract class AbstractCouchdbCrudRepositoryTest extends AbstractCrudRepositoryTest { @Autowired private CouchDbCrudRepository<Product, String> productRepo; private Product p1 = readDocument("../documents/p1_allAttributesSet.js", Product.class); private Product p2 = newProduct("Oak table 1922", "Lumberjack1 Inc."); private Product p3 = newProduct("Oak table 1923", "Lumberjack1 Inc."); private Product p4 = newProduct("Oak table 1924", "Lumberjack Inc."); private ViewParams params = new ViewParams(); protected void deleteProductRepoAndCreateSomeProducts() { productRepo.deleteAll(); productRepo.save(p1); productRepo.save(p2); productRepo.save(p3); productRepo.save(p4); params.setView("by_manufacturerId"); params.setReduce(false); params.setKeyType(String.class);
params.setValueType(ProductSummary.class);
rwitzel/CouchRepository
src/main/java/com/github/rwitzel/couchrepository/support/DocumentLoader.java
// Path: src/main/java/com/github/rwitzel/couchrepository/api/CouchDbCrudRepository.java // public interface CouchDbCrudRepository<T, ID extends Serializable> extends CrudRepository<T, ID> { // // /** // * Queries the database with the given parameters. // * // * @param viewParams the query parameters // * @param <R> the return type, depends on {@link ViewParams#getReturnType()}. // * @return Returns the result of the query. The type of the return value depends on {@link ViewParams#getReturnType()}. // */ // <R> R find(ViewParams viewParams); // // }
import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Optional; import org.yaml.snakeyaml.Yaml; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.rwitzel.couchrepository.api.CouchDbCrudRepository;
package com.github.rwitzel.couchrepository.support; /** * Loads a document into the database. Useful for the initialization of a database. * * @author rwitzel */ public class DocumentLoader { @SuppressWarnings("rawtypes")
// Path: src/main/java/com/github/rwitzel/couchrepository/api/CouchDbCrudRepository.java // public interface CouchDbCrudRepository<T, ID extends Serializable> extends CrudRepository<T, ID> { // // /** // * Queries the database with the given parameters. // * // * @param viewParams the query parameters // * @param <R> the return type, depends on {@link ViewParams#getReturnType()}. // * @return Returns the result of the query. The type of the return value depends on {@link ViewParams#getReturnType()}. // */ // <R> R find(ViewParams viewParams); // // } // Path: src/main/java/com/github/rwitzel/couchrepository/support/DocumentLoader.java import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Optional; import org.yaml.snakeyaml.Yaml; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.rwitzel.couchrepository.api.CouchDbCrudRepository; package com.github.rwitzel.couchrepository.support; /** * Loads a document into the database. Useful for the initialization of a database. * * @author rwitzel */ public class DocumentLoader { @SuppressWarnings("rawtypes")
private CouchDbCrudRepository<Map, String> repository;
rwitzel/CouchRepository
src/main/java/com/github/rwitzel/couchrepository/internal/AdapterUtils.java
// Path: src/main/java/com/github/rwitzel/couchrepository/api/ViewResult.java // public class ViewResult { // // protected long totalRows; // // protected long updateSeq; // // protected int offset; // // protected List<ViewResultRow> rows; // // public long getTotalRows() { // return totalRows; // } // // public void setTotalRows(long totalRows) { // this.totalRows = totalRows; // } // // public long getUpdateSeq() { // return updateSeq; // } // // public void setUpdateSeq(long updateSeq) { // this.updateSeq = updateSeq; // } // // public int getOffset() { // return offset; // } // // public void setOffset(int offset) { // this.offset = offset; // } // // public List<ViewResultRow> getRows() { // if (rows == null) { // rows = new ArrayList<ViewResultRow>(); // } // return rows; // } // // public void setRows(List<ViewResultRow> rows) { // this.rows = rows; // } // // @Override // public String toString() { // return "ViewResult [totalRows=" + totalRows + ", updateSeq=" + updateSeq + ", offset=" + offset + ", rows=" // + rows + "]"; // } // } // // Path: src/main/java/com/github/rwitzel/couchrepository/api/ViewResultRow.java // public class ViewResultRow { // // /** // * The CouchDB ID of the document. // */ // protected String id; // // protected Object key; // // protected Object value; // // protected Object doc; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @SuppressWarnings("unchecked") // public <K> K getKey() { // return (K) key; // } // // public void setKey(Object key) { // this.key = key; // } // // @SuppressWarnings("unchecked") // public <V> V getValue() { // return (V) value; // } // // public void setValue(Object value) { // this.value = value; // } // // @SuppressWarnings("unchecked") // public <D> D getDoc() { // return (D) doc; // } // // public void setDoc(Object doc) { // this.doc = doc; // } // // @Override // public String toString() { // return "ViewResultRow [id=" + id + ", key=" + key + ", value=" + value + ", doc=" + doc + "]"; // } // // }
import java.util.ArrayList; import java.util.List; import com.github.rwitzel.couchrepository.api.ViewResult; import com.github.rwitzel.couchrepository.api.ViewResultRow;
package com.github.rwitzel.couchrepository.internal; /** * Transforms Spring Data specific values to CouchDB driver specific values and the other way around. * * @author rwitzel */ public class AdapterUtils { /** * Copies the elements of {@link Iterable} into a list and returns them. * * @param iter the iterable that contains the elements * @param <E> the type of the elements * @return Returns the elements of the {@link Iterable}. */ public static <E> List<E> toList(Iterable<E> iter) { List<E> list = new ArrayList<E>(); for (E item : iter) { list.add(item); } return list; } /** * Transforms the view result to a list of keys or values or documents or IDs depending on the given return type. If * the return type is null, the view result is not transformed. * * @param viewResult the original view result * @param returnType * null or "key or "value" or "doc" or "id" * @param <E> the type of the elements * @return Returns the transformed view result. */ @SuppressWarnings("unchecked")
// Path: src/main/java/com/github/rwitzel/couchrepository/api/ViewResult.java // public class ViewResult { // // protected long totalRows; // // protected long updateSeq; // // protected int offset; // // protected List<ViewResultRow> rows; // // public long getTotalRows() { // return totalRows; // } // // public void setTotalRows(long totalRows) { // this.totalRows = totalRows; // } // // public long getUpdateSeq() { // return updateSeq; // } // // public void setUpdateSeq(long updateSeq) { // this.updateSeq = updateSeq; // } // // public int getOffset() { // return offset; // } // // public void setOffset(int offset) { // this.offset = offset; // } // // public List<ViewResultRow> getRows() { // if (rows == null) { // rows = new ArrayList<ViewResultRow>(); // } // return rows; // } // // public void setRows(List<ViewResultRow> rows) { // this.rows = rows; // } // // @Override // public String toString() { // return "ViewResult [totalRows=" + totalRows + ", updateSeq=" + updateSeq + ", offset=" + offset + ", rows=" // + rows + "]"; // } // } // // Path: src/main/java/com/github/rwitzel/couchrepository/api/ViewResultRow.java // public class ViewResultRow { // // /** // * The CouchDB ID of the document. // */ // protected String id; // // protected Object key; // // protected Object value; // // protected Object doc; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @SuppressWarnings("unchecked") // public <K> K getKey() { // return (K) key; // } // // public void setKey(Object key) { // this.key = key; // } // // @SuppressWarnings("unchecked") // public <V> V getValue() { // return (V) value; // } // // public void setValue(Object value) { // this.value = value; // } // // @SuppressWarnings("unchecked") // public <D> D getDoc() { // return (D) doc; // } // // public void setDoc(Object doc) { // this.doc = doc; // } // // @Override // public String toString() { // return "ViewResultRow [id=" + id + ", key=" + key + ", value=" + value + ", doc=" + doc + "]"; // } // // } // Path: src/main/java/com/github/rwitzel/couchrepository/internal/AdapterUtils.java import java.util.ArrayList; import java.util.List; import com.github.rwitzel.couchrepository.api.ViewResult; import com.github.rwitzel.couchrepository.api.ViewResultRow; package com.github.rwitzel.couchrepository.internal; /** * Transforms Spring Data specific values to CouchDB driver specific values and the other way around. * * @author rwitzel */ public class AdapterUtils { /** * Copies the elements of {@link Iterable} into a list and returns them. * * @param iter the iterable that contains the elements * @param <E> the type of the elements * @return Returns the elements of the {@link Iterable}. */ public static <E> List<E> toList(Iterable<E> iter) { List<E> list = new ArrayList<E>(); for (E item : iter) { list.add(item); } return list; } /** * Transforms the view result to a list of keys or values or documents or IDs depending on the given return type. If * the return type is null, the view result is not transformed. * * @param viewResult the original view result * @param returnType * null or "key or "value" or "doc" or "id" * @param <E> the type of the elements * @return Returns the transformed view result. */ @SuppressWarnings("unchecked")
public static <E> E transformViewResult(ViewResult viewResult, String returnType) {
rwitzel/CouchRepository
src/main/java/com/github/rwitzel/couchrepository/internal/AdapterUtils.java
// Path: src/main/java/com/github/rwitzel/couchrepository/api/ViewResult.java // public class ViewResult { // // protected long totalRows; // // protected long updateSeq; // // protected int offset; // // protected List<ViewResultRow> rows; // // public long getTotalRows() { // return totalRows; // } // // public void setTotalRows(long totalRows) { // this.totalRows = totalRows; // } // // public long getUpdateSeq() { // return updateSeq; // } // // public void setUpdateSeq(long updateSeq) { // this.updateSeq = updateSeq; // } // // public int getOffset() { // return offset; // } // // public void setOffset(int offset) { // this.offset = offset; // } // // public List<ViewResultRow> getRows() { // if (rows == null) { // rows = new ArrayList<ViewResultRow>(); // } // return rows; // } // // public void setRows(List<ViewResultRow> rows) { // this.rows = rows; // } // // @Override // public String toString() { // return "ViewResult [totalRows=" + totalRows + ", updateSeq=" + updateSeq + ", offset=" + offset + ", rows=" // + rows + "]"; // } // } // // Path: src/main/java/com/github/rwitzel/couchrepository/api/ViewResultRow.java // public class ViewResultRow { // // /** // * The CouchDB ID of the document. // */ // protected String id; // // protected Object key; // // protected Object value; // // protected Object doc; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @SuppressWarnings("unchecked") // public <K> K getKey() { // return (K) key; // } // // public void setKey(Object key) { // this.key = key; // } // // @SuppressWarnings("unchecked") // public <V> V getValue() { // return (V) value; // } // // public void setValue(Object value) { // this.value = value; // } // // @SuppressWarnings("unchecked") // public <D> D getDoc() { // return (D) doc; // } // // public void setDoc(Object doc) { // this.doc = doc; // } // // @Override // public String toString() { // return "ViewResultRow [id=" + id + ", key=" + key + ", value=" + value + ", doc=" + doc + "]"; // } // // }
import java.util.ArrayList; import java.util.List; import com.github.rwitzel.couchrepository.api.ViewResult; import com.github.rwitzel.couchrepository.api.ViewResultRow;
package com.github.rwitzel.couchrepository.internal; /** * Transforms Spring Data specific values to CouchDB driver specific values and the other way around. * * @author rwitzel */ public class AdapterUtils { /** * Copies the elements of {@link Iterable} into a list and returns them. * * @param iter the iterable that contains the elements * @param <E> the type of the elements * @return Returns the elements of the {@link Iterable}. */ public static <E> List<E> toList(Iterable<E> iter) { List<E> list = new ArrayList<E>(); for (E item : iter) { list.add(item); } return list; } /** * Transforms the view result to a list of keys or values or documents or IDs depending on the given return type. If * the return type is null, the view result is not transformed. * * @param viewResult the original view result * @param returnType * null or "key or "value" or "doc" or "id" * @param <E> the type of the elements * @return Returns the transformed view result. */ @SuppressWarnings("unchecked") public static <E> E transformViewResult(ViewResult viewResult, String returnType) { if (returnType == null) { return (E) viewResult; } else { List<Object> list = new ArrayList<Object>();
// Path: src/main/java/com/github/rwitzel/couchrepository/api/ViewResult.java // public class ViewResult { // // protected long totalRows; // // protected long updateSeq; // // protected int offset; // // protected List<ViewResultRow> rows; // // public long getTotalRows() { // return totalRows; // } // // public void setTotalRows(long totalRows) { // this.totalRows = totalRows; // } // // public long getUpdateSeq() { // return updateSeq; // } // // public void setUpdateSeq(long updateSeq) { // this.updateSeq = updateSeq; // } // // public int getOffset() { // return offset; // } // // public void setOffset(int offset) { // this.offset = offset; // } // // public List<ViewResultRow> getRows() { // if (rows == null) { // rows = new ArrayList<ViewResultRow>(); // } // return rows; // } // // public void setRows(List<ViewResultRow> rows) { // this.rows = rows; // } // // @Override // public String toString() { // return "ViewResult [totalRows=" + totalRows + ", updateSeq=" + updateSeq + ", offset=" + offset + ", rows=" // + rows + "]"; // } // } // // Path: src/main/java/com/github/rwitzel/couchrepository/api/ViewResultRow.java // public class ViewResultRow { // // /** // * The CouchDB ID of the document. // */ // protected String id; // // protected Object key; // // protected Object value; // // protected Object doc; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @SuppressWarnings("unchecked") // public <K> K getKey() { // return (K) key; // } // // public void setKey(Object key) { // this.key = key; // } // // @SuppressWarnings("unchecked") // public <V> V getValue() { // return (V) value; // } // // public void setValue(Object value) { // this.value = value; // } // // @SuppressWarnings("unchecked") // public <D> D getDoc() { // return (D) doc; // } // // public void setDoc(Object doc) { // this.doc = doc; // } // // @Override // public String toString() { // return "ViewResultRow [id=" + id + ", key=" + key + ", value=" + value + ", doc=" + doc + "]"; // } // // } // Path: src/main/java/com/github/rwitzel/couchrepository/internal/AdapterUtils.java import java.util.ArrayList; import java.util.List; import com.github.rwitzel.couchrepository.api.ViewResult; import com.github.rwitzel.couchrepository.api.ViewResultRow; package com.github.rwitzel.couchrepository.internal; /** * Transforms Spring Data specific values to CouchDB driver specific values and the other way around. * * @author rwitzel */ public class AdapterUtils { /** * Copies the elements of {@link Iterable} into a list and returns them. * * @param iter the iterable that contains the elements * @param <E> the type of the elements * @return Returns the elements of the {@link Iterable}. */ public static <E> List<E> toList(Iterable<E> iter) { List<E> list = new ArrayList<E>(); for (E item : iter) { list.add(item); } return list; } /** * Transforms the view result to a list of keys or values or documents or IDs depending on the given return type. If * the return type is null, the view result is not transformed. * * @param viewResult the original view result * @param returnType * null or "key or "value" or "doc" or "id" * @param <E> the type of the elements * @return Returns the transformed view result. */ @SuppressWarnings("unchecked") public static <E> E transformViewResult(ViewResult viewResult, String returnType) { if (returnType == null) { return (E) viewResult; } else { List<Object> list = new ArrayList<Object>();
for (ViewResultRow row : viewResult.getRows()) {
rwitzel/CouchRepository
src/test/java/com/github/rwitzel/couchrepository/api/AbstractCustomImplementationTest.java
// Path: src/test/java/com/github/rwitzel/couchrepository/model/Product.java // public class Product extends BaseDocument { // // private Date lastModification; // // private String manufacturerId; // // private String text; // // private ProductRating rating; // // private boolean hidden; // // private Integer numBuyers; // // private double weight; // // private BigDecimal price; // // private List<String> tags; // // private List<Comment> comments; // // private int isoProductCode; // // public Date getLastModification() { // return lastModification; // } // // public void setLastModification(Date lastModification) { // this.lastModification = lastModification; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public ProductRating getRating() { // return rating; // } // // public void setRating(ProductRating rating) { // this.rating = rating; // } // // public boolean isHidden() { // return hidden; // } // // public void setHidden(boolean hidden) { // this.hidden = hidden; // } // // public Integer getNumBuyers() { // return numBuyers; // } // // public void setNumBuyers(Integer numBuyers) { // this.numBuyers = numBuyers; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public List<String> getTags() { // if (tags == null) { // return new ArrayList<String>(); // } // return tags; // } // // public void setTags(List<String> tags) { // this.tags = tags; // } // // public List<Comment> getComments() { // if (comments == null) { // comments = new ArrayList<Comment>(); // } // return comments; // } // // public void setComments(List<Comment> comments) { // this.comments = comments; // } // // public String getManufacturerId() { // return manufacturerId; // } // // public void setManufacturerId(String manufacturerId) { // this.manufacturerId = manufacturerId; // } // // public int getIsoProductCode() { // return isoProductCode; // } // // public void setIsoProductCode(int isoProductCode) { // this.isoProductCode = isoProductCode; // } // }
import static com.googlecode.catchexception.CatchException.catchException; import static com.googlecode.catchexception.CatchException.caughtException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.github.rwitzel.couchrepository.model.Product;
package com.github.rwitzel.couchrepository.api; /** * Tests the integration of custom implementations of query methods. * * @author rwitzel */ public abstract class AbstractCustomImplementationTest extends AbstractAutomaticImplementationTest { @Autowired private ProductRepository productRepo; @Test public void testDelegateToCustomImplementation() throws Exception { deleteProductRepoAndCreateSomeProducts();
// Path: src/test/java/com/github/rwitzel/couchrepository/model/Product.java // public class Product extends BaseDocument { // // private Date lastModification; // // private String manufacturerId; // // private String text; // // private ProductRating rating; // // private boolean hidden; // // private Integer numBuyers; // // private double weight; // // private BigDecimal price; // // private List<String> tags; // // private List<Comment> comments; // // private int isoProductCode; // // public Date getLastModification() { // return lastModification; // } // // public void setLastModification(Date lastModification) { // this.lastModification = lastModification; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public ProductRating getRating() { // return rating; // } // // public void setRating(ProductRating rating) { // this.rating = rating; // } // // public boolean isHidden() { // return hidden; // } // // public void setHidden(boolean hidden) { // this.hidden = hidden; // } // // public Integer getNumBuyers() { // return numBuyers; // } // // public void setNumBuyers(Integer numBuyers) { // this.numBuyers = numBuyers; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public List<String> getTags() { // if (tags == null) { // return new ArrayList<String>(); // } // return tags; // } // // public void setTags(List<String> tags) { // this.tags = tags; // } // // public List<Comment> getComments() { // if (comments == null) { // comments = new ArrayList<Comment>(); // } // return comments; // } // // public void setComments(List<Comment> comments) { // this.comments = comments; // } // // public String getManufacturerId() { // return manufacturerId; // } // // public void setManufacturerId(String manufacturerId) { // this.manufacturerId = manufacturerId; // } // // public int getIsoProductCode() { // return isoProductCode; // } // // public void setIsoProductCode(int isoProductCode) { // this.isoProductCode = isoProductCode; // } // } // Path: src/test/java/com/github/rwitzel/couchrepository/api/AbstractCustomImplementationTest.java import static com.googlecode.catchexception.CatchException.catchException; import static com.googlecode.catchexception.CatchException.caughtException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.github.rwitzel.couchrepository.model.Product; package com.github.rwitzel.couchrepository.api; /** * Tests the integration of custom implementations of query methods. * * @author rwitzel */ public abstract class AbstractCustomImplementationTest extends AbstractAutomaticImplementationTest { @Autowired private ProductRepository productRepo; @Test public void testDelegateToCustomImplementation() throws Exception { deleteProductRepoAndCreateSomeProducts();
List<Product> products = productRepo.findByComment(new Object[] { "authorB", "textB" }, true);
rwitzel/CouchRepository
src/test/java/com/github/rwitzel/couchrepository/api/AbstractExoticTest.java
// Path: src/test/java/com/github/rwitzel/couchrepository/model/Exotic.java // @JsonInclude(Include.NON_NULL) // public class Exotic { // // /** // * CouchDB-specific property that allows us to distinct exotic documents from other documents. // */ // @JsonProperty("type") // private String type = "exotic"; // // /** // * The ID for CouchDB. Computed from {@link #id}. // */ // @SerializedName("_id") // @JsonProperty("_id") // private String computedKey; // // /** // * The domain-specific ID. // */ // @JsonProperty("internalId") // private ExoticId id; // // /** // * The revision property for CouchDB. // */ // @SerializedName("_rev") // @JsonProperty("_rev") // private String version; // // private String data; // // public Exotic() { // super(); // } // // public Exotic(ExoticId id) { // super(); // this.id = id; // this.computedKey = id.toCouchId(); // } // // public String getData() { // return data; // } // // public void setData(String data) { // this.data = data; // } // // public ExoticId getId() { // return id; // } // // public void setId(ExoticId id) { // this.id = id; // } // // public String getComputedKey() { // return computedKey; // } // // public void setComputedKey(String computedKey) { // this.computedKey = computedKey; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/ExoticId.java // public class ExoticId implements Serializable { // // private static final long serialVersionUID = -2640126433764396121L; // // private Integer idPart1; // // private String idPart2; // // private Boolean idPart3; // // public ExoticId() { // super(); // } // // public ExoticId(String couchId) { // super(); // // String[] parts = couchId.split("_"); // this.idPart1 = Integer.parseInt(parts[0]); // this.idPart2 = parts[1]; // this.idPart3 = Boolean.parseBoolean(parts[2]); // } // // public ExoticId(Integer idPart1, String idPart2, Boolean idPart3) { // super(); // this.idPart1 = idPart1; // this.idPart2 = idPart2; // this.idPart3 = idPart3; // } // // public Integer getIdPart1() { // return idPart1; // } // // public String getIdPart2() { // return idPart2; // } // // public Boolean getIdPart3() { // return idPart3; // } // // public String toCouchId() { // return toCouchId(idPart1, idPart2, idPart3); // } // // public static String toCouchId(Integer idPart1, String idPart2, Boolean idPart3) { // return idPart1 + "_" + idPart2 + "_" + idPart3; // } // }
import static java.util.Collections.singleton; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.github.rwitzel.couchrepository.model.Exotic; import com.github.rwitzel.couchrepository.model.ExoticId;
package com.github.rwitzel.couchrepository.api; /** * Tests entities with custom ID and revision attributes. * * @author rwitzel */ public abstract class AbstractExoticTest extends AbstractCustomImplementationTest { @Autowired
// Path: src/test/java/com/github/rwitzel/couchrepository/model/Exotic.java // @JsonInclude(Include.NON_NULL) // public class Exotic { // // /** // * CouchDB-specific property that allows us to distinct exotic documents from other documents. // */ // @JsonProperty("type") // private String type = "exotic"; // // /** // * The ID for CouchDB. Computed from {@link #id}. // */ // @SerializedName("_id") // @JsonProperty("_id") // private String computedKey; // // /** // * The domain-specific ID. // */ // @JsonProperty("internalId") // private ExoticId id; // // /** // * The revision property for CouchDB. // */ // @SerializedName("_rev") // @JsonProperty("_rev") // private String version; // // private String data; // // public Exotic() { // super(); // } // // public Exotic(ExoticId id) { // super(); // this.id = id; // this.computedKey = id.toCouchId(); // } // // public String getData() { // return data; // } // // public void setData(String data) { // this.data = data; // } // // public ExoticId getId() { // return id; // } // // public void setId(ExoticId id) { // this.id = id; // } // // public String getComputedKey() { // return computedKey; // } // // public void setComputedKey(String computedKey) { // this.computedKey = computedKey; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/ExoticId.java // public class ExoticId implements Serializable { // // private static final long serialVersionUID = -2640126433764396121L; // // private Integer idPart1; // // private String idPart2; // // private Boolean idPart3; // // public ExoticId() { // super(); // } // // public ExoticId(String couchId) { // super(); // // String[] parts = couchId.split("_"); // this.idPart1 = Integer.parseInt(parts[0]); // this.idPart2 = parts[1]; // this.idPart3 = Boolean.parseBoolean(parts[2]); // } // // public ExoticId(Integer idPart1, String idPart2, Boolean idPart3) { // super(); // this.idPart1 = idPart1; // this.idPart2 = idPart2; // this.idPart3 = idPart3; // } // // public Integer getIdPart1() { // return idPart1; // } // // public String getIdPart2() { // return idPart2; // } // // public Boolean getIdPart3() { // return idPart3; // } // // public String toCouchId() { // return toCouchId(idPart1, idPart2, idPart3); // } // // public static String toCouchId(Integer idPart1, String idPart2, Boolean idPart3) { // return idPart1 + "_" + idPart2 + "_" + idPart3; // } // } // Path: src/test/java/com/github/rwitzel/couchrepository/api/AbstractExoticTest.java import static java.util.Collections.singleton; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.github.rwitzel.couchrepository.model.Exotic; import com.github.rwitzel.couchrepository.model.ExoticId; package com.github.rwitzel.couchrepository.api; /** * Tests entities with custom ID and revision attributes. * * @author rwitzel */ public abstract class AbstractExoticTest extends AbstractCustomImplementationTest { @Autowired
CouchDbCrudRepository<Exotic, ExoticId> exoticRepository;
rwitzel/CouchRepository
src/test/java/com/github/rwitzel/couchrepository/api/AbstractExoticTest.java
// Path: src/test/java/com/github/rwitzel/couchrepository/model/Exotic.java // @JsonInclude(Include.NON_NULL) // public class Exotic { // // /** // * CouchDB-specific property that allows us to distinct exotic documents from other documents. // */ // @JsonProperty("type") // private String type = "exotic"; // // /** // * The ID for CouchDB. Computed from {@link #id}. // */ // @SerializedName("_id") // @JsonProperty("_id") // private String computedKey; // // /** // * The domain-specific ID. // */ // @JsonProperty("internalId") // private ExoticId id; // // /** // * The revision property for CouchDB. // */ // @SerializedName("_rev") // @JsonProperty("_rev") // private String version; // // private String data; // // public Exotic() { // super(); // } // // public Exotic(ExoticId id) { // super(); // this.id = id; // this.computedKey = id.toCouchId(); // } // // public String getData() { // return data; // } // // public void setData(String data) { // this.data = data; // } // // public ExoticId getId() { // return id; // } // // public void setId(ExoticId id) { // this.id = id; // } // // public String getComputedKey() { // return computedKey; // } // // public void setComputedKey(String computedKey) { // this.computedKey = computedKey; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/ExoticId.java // public class ExoticId implements Serializable { // // private static final long serialVersionUID = -2640126433764396121L; // // private Integer idPart1; // // private String idPart2; // // private Boolean idPart3; // // public ExoticId() { // super(); // } // // public ExoticId(String couchId) { // super(); // // String[] parts = couchId.split("_"); // this.idPart1 = Integer.parseInt(parts[0]); // this.idPart2 = parts[1]; // this.idPart3 = Boolean.parseBoolean(parts[2]); // } // // public ExoticId(Integer idPart1, String idPart2, Boolean idPart3) { // super(); // this.idPart1 = idPart1; // this.idPart2 = idPart2; // this.idPart3 = idPart3; // } // // public Integer getIdPart1() { // return idPart1; // } // // public String getIdPart2() { // return idPart2; // } // // public Boolean getIdPart3() { // return idPart3; // } // // public String toCouchId() { // return toCouchId(idPart1, idPart2, idPart3); // } // // public static String toCouchId(Integer idPart1, String idPart2, Boolean idPart3) { // return idPart1 + "_" + idPart2 + "_" + idPart3; // } // }
import static java.util.Collections.singleton; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.github.rwitzel.couchrepository.model.Exotic; import com.github.rwitzel.couchrepository.model.ExoticId;
package com.github.rwitzel.couchrepository.api; /** * Tests entities with custom ID and revision attributes. * * @author rwitzel */ public abstract class AbstractExoticTest extends AbstractCustomImplementationTest { @Autowired
// Path: src/test/java/com/github/rwitzel/couchrepository/model/Exotic.java // @JsonInclude(Include.NON_NULL) // public class Exotic { // // /** // * CouchDB-specific property that allows us to distinct exotic documents from other documents. // */ // @JsonProperty("type") // private String type = "exotic"; // // /** // * The ID for CouchDB. Computed from {@link #id}. // */ // @SerializedName("_id") // @JsonProperty("_id") // private String computedKey; // // /** // * The domain-specific ID. // */ // @JsonProperty("internalId") // private ExoticId id; // // /** // * The revision property for CouchDB. // */ // @SerializedName("_rev") // @JsonProperty("_rev") // private String version; // // private String data; // // public Exotic() { // super(); // } // // public Exotic(ExoticId id) { // super(); // this.id = id; // this.computedKey = id.toCouchId(); // } // // public String getData() { // return data; // } // // public void setData(String data) { // this.data = data; // } // // public ExoticId getId() { // return id; // } // // public void setId(ExoticId id) { // this.id = id; // } // // public String getComputedKey() { // return computedKey; // } // // public void setComputedKey(String computedKey) { // this.computedKey = computedKey; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/ExoticId.java // public class ExoticId implements Serializable { // // private static final long serialVersionUID = -2640126433764396121L; // // private Integer idPart1; // // private String idPart2; // // private Boolean idPart3; // // public ExoticId() { // super(); // } // // public ExoticId(String couchId) { // super(); // // String[] parts = couchId.split("_"); // this.idPart1 = Integer.parseInt(parts[0]); // this.idPart2 = parts[1]; // this.idPart3 = Boolean.parseBoolean(parts[2]); // } // // public ExoticId(Integer idPart1, String idPart2, Boolean idPart3) { // super(); // this.idPart1 = idPart1; // this.idPart2 = idPart2; // this.idPart3 = idPart3; // } // // public Integer getIdPart1() { // return idPart1; // } // // public String getIdPart2() { // return idPart2; // } // // public Boolean getIdPart3() { // return idPart3; // } // // public String toCouchId() { // return toCouchId(idPart1, idPart2, idPart3); // } // // public static String toCouchId(Integer idPart1, String idPart2, Boolean idPart3) { // return idPart1 + "_" + idPart2 + "_" + idPart3; // } // } // Path: src/test/java/com/github/rwitzel/couchrepository/api/AbstractExoticTest.java import static java.util.Collections.singleton; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.github.rwitzel.couchrepository.model.Exotic; import com.github.rwitzel.couchrepository.model.ExoticId; package com.github.rwitzel.couchrepository.api; /** * Tests entities with custom ID and revision attributes. * * @author rwitzel */ public abstract class AbstractExoticTest extends AbstractCustomImplementationTest { @Autowired
CouchDbCrudRepository<Exotic, ExoticId> exoticRepository;
rwitzel/CouchRepository
src/test/java/com/github/rwitzel/couchrepository/api/viewresult/ProductFacts.java
// Path: src/test/java/com/github/rwitzel/couchrepository/model/Comment.java // public class Comment { // // private String author; // // private String text; // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((author == null) ? 0 : author.hashCode()); // result = prime * result + ((text == null) ? 0 : text.hashCode()); // return result; // } // // /** // * Generated by Eclipse. // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Comment other = (Comment) obj; // if (author == null) { // if (other.author != null) // return false; // } else if (!author.equals(other.author)) // return false; // if (text == null) { // if (other.text != null) // return false; // } else if (!text.equals(other.text)) // return false; // return true; // } // // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/Product.java // public class Product extends BaseDocument { // // private Date lastModification; // // private String manufacturerId; // // private String text; // // private ProductRating rating; // // private boolean hidden; // // private Integer numBuyers; // // private double weight; // // private BigDecimal price; // // private List<String> tags; // // private List<Comment> comments; // // private int isoProductCode; // // public Date getLastModification() { // return lastModification; // } // // public void setLastModification(Date lastModification) { // this.lastModification = lastModification; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public ProductRating getRating() { // return rating; // } // // public void setRating(ProductRating rating) { // this.rating = rating; // } // // public boolean isHidden() { // return hidden; // } // // public void setHidden(boolean hidden) { // this.hidden = hidden; // } // // public Integer getNumBuyers() { // return numBuyers; // } // // public void setNumBuyers(Integer numBuyers) { // this.numBuyers = numBuyers; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public List<String> getTags() { // if (tags == null) { // return new ArrayList<String>(); // } // return tags; // } // // public void setTags(List<String> tags) { // this.tags = tags; // } // // public List<Comment> getComments() { // if (comments == null) { // comments = new ArrayList<Comment>(); // } // return comments; // } // // public void setComments(List<Comment> comments) { // this.comments = comments; // } // // public String getManufacturerId() { // return manufacturerId; // } // // public void setManufacturerId(String manufacturerId) { // this.manufacturerId = manufacturerId; // } // // public int getIsoProductCode() { // return isoProductCode; // } // // public void setIsoProductCode(int isoProductCode) { // this.isoProductCode = isoProductCode; // } // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/ProductRating.java // public enum ProductRating { // // FiveStars, FourStars, ThreeStars, TwoStars, OneStars // // }
import java.math.BigDecimal; import java.util.Date; import java.util.List; import com.github.rwitzel.couchrepository.model.Comment; import com.github.rwitzel.couchrepository.model.Product; import com.github.rwitzel.couchrepository.model.ProductRating;
package com.github.rwitzel.couchrepository.api.viewresult; /** * This class duplicates the properties of a {@link Product} and assists in testing views. * * @author rwitzel */ public class ProductFacts { private String docId; private Date lastModification; private String text;
// Path: src/test/java/com/github/rwitzel/couchrepository/model/Comment.java // public class Comment { // // private String author; // // private String text; // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((author == null) ? 0 : author.hashCode()); // result = prime * result + ((text == null) ? 0 : text.hashCode()); // return result; // } // // /** // * Generated by Eclipse. // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Comment other = (Comment) obj; // if (author == null) { // if (other.author != null) // return false; // } else if (!author.equals(other.author)) // return false; // if (text == null) { // if (other.text != null) // return false; // } else if (!text.equals(other.text)) // return false; // return true; // } // // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/Product.java // public class Product extends BaseDocument { // // private Date lastModification; // // private String manufacturerId; // // private String text; // // private ProductRating rating; // // private boolean hidden; // // private Integer numBuyers; // // private double weight; // // private BigDecimal price; // // private List<String> tags; // // private List<Comment> comments; // // private int isoProductCode; // // public Date getLastModification() { // return lastModification; // } // // public void setLastModification(Date lastModification) { // this.lastModification = lastModification; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public ProductRating getRating() { // return rating; // } // // public void setRating(ProductRating rating) { // this.rating = rating; // } // // public boolean isHidden() { // return hidden; // } // // public void setHidden(boolean hidden) { // this.hidden = hidden; // } // // public Integer getNumBuyers() { // return numBuyers; // } // // public void setNumBuyers(Integer numBuyers) { // this.numBuyers = numBuyers; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public List<String> getTags() { // if (tags == null) { // return new ArrayList<String>(); // } // return tags; // } // // public void setTags(List<String> tags) { // this.tags = tags; // } // // public List<Comment> getComments() { // if (comments == null) { // comments = new ArrayList<Comment>(); // } // return comments; // } // // public void setComments(List<Comment> comments) { // this.comments = comments; // } // // public String getManufacturerId() { // return manufacturerId; // } // // public void setManufacturerId(String manufacturerId) { // this.manufacturerId = manufacturerId; // } // // public int getIsoProductCode() { // return isoProductCode; // } // // public void setIsoProductCode(int isoProductCode) { // this.isoProductCode = isoProductCode; // } // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/ProductRating.java // public enum ProductRating { // // FiveStars, FourStars, ThreeStars, TwoStars, OneStars // // } // Path: src/test/java/com/github/rwitzel/couchrepository/api/viewresult/ProductFacts.java import java.math.BigDecimal; import java.util.Date; import java.util.List; import com.github.rwitzel.couchrepository.model.Comment; import com.github.rwitzel.couchrepository.model.Product; import com.github.rwitzel.couchrepository.model.ProductRating; package com.github.rwitzel.couchrepository.api.viewresult; /** * This class duplicates the properties of a {@link Product} and assists in testing views. * * @author rwitzel */ public class ProductFacts { private String docId; private Date lastModification; private String text;
private ProductRating rating;
rwitzel/CouchRepository
src/test/java/com/github/rwitzel/couchrepository/api/viewresult/ProductFacts.java
// Path: src/test/java/com/github/rwitzel/couchrepository/model/Comment.java // public class Comment { // // private String author; // // private String text; // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((author == null) ? 0 : author.hashCode()); // result = prime * result + ((text == null) ? 0 : text.hashCode()); // return result; // } // // /** // * Generated by Eclipse. // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Comment other = (Comment) obj; // if (author == null) { // if (other.author != null) // return false; // } else if (!author.equals(other.author)) // return false; // if (text == null) { // if (other.text != null) // return false; // } else if (!text.equals(other.text)) // return false; // return true; // } // // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/Product.java // public class Product extends BaseDocument { // // private Date lastModification; // // private String manufacturerId; // // private String text; // // private ProductRating rating; // // private boolean hidden; // // private Integer numBuyers; // // private double weight; // // private BigDecimal price; // // private List<String> tags; // // private List<Comment> comments; // // private int isoProductCode; // // public Date getLastModification() { // return lastModification; // } // // public void setLastModification(Date lastModification) { // this.lastModification = lastModification; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public ProductRating getRating() { // return rating; // } // // public void setRating(ProductRating rating) { // this.rating = rating; // } // // public boolean isHidden() { // return hidden; // } // // public void setHidden(boolean hidden) { // this.hidden = hidden; // } // // public Integer getNumBuyers() { // return numBuyers; // } // // public void setNumBuyers(Integer numBuyers) { // this.numBuyers = numBuyers; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public List<String> getTags() { // if (tags == null) { // return new ArrayList<String>(); // } // return tags; // } // // public void setTags(List<String> tags) { // this.tags = tags; // } // // public List<Comment> getComments() { // if (comments == null) { // comments = new ArrayList<Comment>(); // } // return comments; // } // // public void setComments(List<Comment> comments) { // this.comments = comments; // } // // public String getManufacturerId() { // return manufacturerId; // } // // public void setManufacturerId(String manufacturerId) { // this.manufacturerId = manufacturerId; // } // // public int getIsoProductCode() { // return isoProductCode; // } // // public void setIsoProductCode(int isoProductCode) { // this.isoProductCode = isoProductCode; // } // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/ProductRating.java // public enum ProductRating { // // FiveStars, FourStars, ThreeStars, TwoStars, OneStars // // }
import java.math.BigDecimal; import java.util.Date; import java.util.List; import com.github.rwitzel.couchrepository.model.Comment; import com.github.rwitzel.couchrepository.model.Product; import com.github.rwitzel.couchrepository.model.ProductRating;
package com.github.rwitzel.couchrepository.api.viewresult; /** * This class duplicates the properties of a {@link Product} and assists in testing views. * * @author rwitzel */ public class ProductFacts { private String docId; private Date lastModification; private String text; private ProductRating rating; private boolean hidden; private Integer numBuyers; private double weight; private BigDecimal price; private List<String> tags;
// Path: src/test/java/com/github/rwitzel/couchrepository/model/Comment.java // public class Comment { // // private String author; // // private String text; // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((author == null) ? 0 : author.hashCode()); // result = prime * result + ((text == null) ? 0 : text.hashCode()); // return result; // } // // /** // * Generated by Eclipse. // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Comment other = (Comment) obj; // if (author == null) { // if (other.author != null) // return false; // } else if (!author.equals(other.author)) // return false; // if (text == null) { // if (other.text != null) // return false; // } else if (!text.equals(other.text)) // return false; // return true; // } // // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/Product.java // public class Product extends BaseDocument { // // private Date lastModification; // // private String manufacturerId; // // private String text; // // private ProductRating rating; // // private boolean hidden; // // private Integer numBuyers; // // private double weight; // // private BigDecimal price; // // private List<String> tags; // // private List<Comment> comments; // // private int isoProductCode; // // public Date getLastModification() { // return lastModification; // } // // public void setLastModification(Date lastModification) { // this.lastModification = lastModification; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public ProductRating getRating() { // return rating; // } // // public void setRating(ProductRating rating) { // this.rating = rating; // } // // public boolean isHidden() { // return hidden; // } // // public void setHidden(boolean hidden) { // this.hidden = hidden; // } // // public Integer getNumBuyers() { // return numBuyers; // } // // public void setNumBuyers(Integer numBuyers) { // this.numBuyers = numBuyers; // } // // public double getWeight() { // return weight; // } // // public void setWeight(double weight) { // this.weight = weight; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public List<String> getTags() { // if (tags == null) { // return new ArrayList<String>(); // } // return tags; // } // // public void setTags(List<String> tags) { // this.tags = tags; // } // // public List<Comment> getComments() { // if (comments == null) { // comments = new ArrayList<Comment>(); // } // return comments; // } // // public void setComments(List<Comment> comments) { // this.comments = comments; // } // // public String getManufacturerId() { // return manufacturerId; // } // // public void setManufacturerId(String manufacturerId) { // this.manufacturerId = manufacturerId; // } // // public int getIsoProductCode() { // return isoProductCode; // } // // public void setIsoProductCode(int isoProductCode) { // this.isoProductCode = isoProductCode; // } // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/ProductRating.java // public enum ProductRating { // // FiveStars, FourStars, ThreeStars, TwoStars, OneStars // // } // Path: src/test/java/com/github/rwitzel/couchrepository/api/viewresult/ProductFacts.java import java.math.BigDecimal; import java.util.Date; import java.util.List; import com.github.rwitzel.couchrepository.model.Comment; import com.github.rwitzel.couchrepository.model.Product; import com.github.rwitzel.couchrepository.model.ProductRating; package com.github.rwitzel.couchrepository.api.viewresult; /** * This class duplicates the properties of a {@link Product} and assists in testing views. * * @author rwitzel */ public class ProductFacts { private String docId; private Date lastModification; private String text; private ProductRating rating; private boolean hidden; private Integer numBuyers; private double weight; private BigDecimal price; private List<String> tags;
private List<Comment> comments;
rwitzel/CouchRepository
src/test/java/com/github/rwitzel/couchrepository/api/AbstractAutomaticImplementationTest.java
// Path: src/main/java/com/github/rwitzel/couchrepository/internal/QueryMethodHandler.java // @SuppressWarnings("rawtypes") // public class QueryMethodHandler implements InvocationHandler { // // protected CouchDbCrudRepository crudRepository; // // protected Object customRepository; // // protected ViewParamsMerger viewParamsMerger; // // public QueryMethodHandler(CouchDbCrudRepository crudRepository, Object customRepository, // ViewParamsMerger viewParamsMerger) { // super(); // this.crudRepository = crudRepository; // this.customRepository = customRepository; // this.viewParamsMerger = viewParamsMerger; // } // // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // // // delegate to the custom repository? // if (customRepository != null) { // Method underlyingMethod = ReflectionUtils.findMethod(customRepository.getClass(), method.getName(), // method.getParameterTypes()); // // if (underlyingMethod != null) { // try { // return underlyingMethod.invoke(customRepository, args); // } catch (InvocationTargetException e) { // throw e.getCause(); // we want to throw the original exception // } // } // } // // // delegate to the underlying CRUD repository? // Method underlyingMethod = ReflectionUtils.findMethod(crudRepository.getClass(), method.getName(), // method.getParameterTypes()); // if (underlyingMethod != null) { // try { // return underlyingMethod.invoke(crudRepository, args); // } catch (InvocationTargetException e) { // throw e.getCause(); // we want to throw the original exception // } // } // // // find by view // ViewParams viewParams = new ViewParams(); // viewParamsMerger.mergeViewParams(viewParams, method, args); // return crudRepository.find(viewParams); // } // // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/Comment.java // public class Comment { // // private String author; // // private String text; // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((author == null) ? 0 : author.hashCode()); // result = prime * result + ((text == null) ? 0 : text.hashCode()); // return result; // } // // /** // * Generated by Eclipse. // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Comment other = (Comment) obj; // if (author == null) { // if (other.author != null) // return false; // } else if (!author.equals(other.author)) // return false; // if (text == null) { // if (other.text != null) // return false; // } else if (!text.equals(other.text)) // return false; // return true; // } // // }
import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.github.rwitzel.couchrepository.internal.QueryMethodHandler; import com.github.rwitzel.couchrepository.model.Comment;
package com.github.rwitzel.couchrepository.api; /** * Tests interfaces that must be automatically implemented by {@link QueryMethodHandler}. * * @author rwitzel */ public abstract class AbstractAutomaticImplementationTest extends AbstractCouchdbCrudRepositoryTest { @Autowired private ProductRepository productRepo; @Test public void testDelegateToFindByViewParams() throws Exception { deleteProductRepoAndCreateSomeProducts(); ViewParams viewParams = new ViewParams(); viewParams.setKeyType(String[].class); viewParams.setReduce(false); ViewResult comments = productRepo.findByComment(new Object[] { "authorB", "textB" }, null, viewParams, HashMap.class); assertEquals(1, comments.getRows().size()); Map<String, Object> value = comments.getRows().get(0).getValue(); assertEquals("textB", value.get("text")); } @Test public void testDelegateToFindByViewParams_ReturnValueType() throws Exception { deleteProductRepoAndCreateSomeProducts(); ViewParams viewParams = new ViewParams(); viewParams.setKeyType(String[].class);
// Path: src/main/java/com/github/rwitzel/couchrepository/internal/QueryMethodHandler.java // @SuppressWarnings("rawtypes") // public class QueryMethodHandler implements InvocationHandler { // // protected CouchDbCrudRepository crudRepository; // // protected Object customRepository; // // protected ViewParamsMerger viewParamsMerger; // // public QueryMethodHandler(CouchDbCrudRepository crudRepository, Object customRepository, // ViewParamsMerger viewParamsMerger) { // super(); // this.crudRepository = crudRepository; // this.customRepository = customRepository; // this.viewParamsMerger = viewParamsMerger; // } // // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // // // delegate to the custom repository? // if (customRepository != null) { // Method underlyingMethod = ReflectionUtils.findMethod(customRepository.getClass(), method.getName(), // method.getParameterTypes()); // // if (underlyingMethod != null) { // try { // return underlyingMethod.invoke(customRepository, args); // } catch (InvocationTargetException e) { // throw e.getCause(); // we want to throw the original exception // } // } // } // // // delegate to the underlying CRUD repository? // Method underlyingMethod = ReflectionUtils.findMethod(crudRepository.getClass(), method.getName(), // method.getParameterTypes()); // if (underlyingMethod != null) { // try { // return underlyingMethod.invoke(crudRepository, args); // } catch (InvocationTargetException e) { // throw e.getCause(); // we want to throw the original exception // } // } // // // find by view // ViewParams viewParams = new ViewParams(); // viewParamsMerger.mergeViewParams(viewParams, method, args); // return crudRepository.find(viewParams); // } // // } // // Path: src/test/java/com/github/rwitzel/couchrepository/model/Comment.java // public class Comment { // // private String author; // // private String text; // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((author == null) ? 0 : author.hashCode()); // result = prime * result + ((text == null) ? 0 : text.hashCode()); // return result; // } // // /** // * Generated by Eclipse. // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Comment other = (Comment) obj; // if (author == null) { // if (other.author != null) // return false; // } else if (!author.equals(other.author)) // return false; // if (text == null) { // if (other.text != null) // return false; // } else if (!text.equals(other.text)) // return false; // return true; // } // // } // Path: src/test/java/com/github/rwitzel/couchrepository/api/AbstractAutomaticImplementationTest.java import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.github.rwitzel.couchrepository.internal.QueryMethodHandler; import com.github.rwitzel.couchrepository.model.Comment; package com.github.rwitzel.couchrepository.api; /** * Tests interfaces that must be automatically implemented by {@link QueryMethodHandler}. * * @author rwitzel */ public abstract class AbstractAutomaticImplementationTest extends AbstractCouchdbCrudRepositoryTest { @Autowired private ProductRepository productRepo; @Test public void testDelegateToFindByViewParams() throws Exception { deleteProductRepoAndCreateSomeProducts(); ViewParams viewParams = new ViewParams(); viewParams.setKeyType(String[].class); viewParams.setReduce(false); ViewResult comments = productRepo.findByComment(new Object[] { "authorB", "textB" }, null, viewParams, HashMap.class); assertEquals(1, comments.getRows().size()); Map<String, Object> value = comments.getRows().get(0).getValue(); assertEquals("textB", value.get("text")); } @Test public void testDelegateToFindByViewParams_ReturnValueType() throws Exception { deleteProductRepoAndCreateSomeProducts(); ViewParams viewParams = new ViewParams(); viewParams.setKeyType(String[].class);
viewParams.setValueType(Comment.class);
serayuzgur/heartbeat
heartbeat-network/src/main/java/com/heartbeat/network/udp/UDPHeartBeat.java
// Path: heartbeat-log/src/main/java/com/heartbeat/log/Logger.java // public final class Logger { // private static Level defaultPackageLevel = Level.INFO; // private static PrintStream stream = System.out; // //TODO: Appender system // //TODO: Tag-level checks. // // private Logger() { // } // // public static Level getLevel() { // return defaultPackageLevel; // } // // public static void setLevel(Level defaultPackageLevel) { // Logger.defaultPackageLevel = defaultPackageLevel; // } // // public static final void trace(String tag, String message) { // print(Level.TRACE, tag, message); // // } // // public static final void trace(String tag, String message, Object... args) { // print(Level.TRACE, tag, message, args); // // } // // public static final void debug(String tag, String message) { // print(Level.DEBUG, tag, message); // // } // // public static final void debug(String tag, String message, Object... args) { // print(Level.DEBUG, tag, message, args); // // } // // public static final void info(String tag, String message) { // print(Level.INFO, tag, message); // // } // // public static final void info(String tag, String message, Object... args) { // print(Level.INFO, tag, message, args); // } // // public static final void warn(String tag, String message) { // print(Level.WARNING, tag, message); // } // // public static final void warn(String tag, String message, Object... args) { // print(Level.WARNING, tag, message, args); // } // // public static final void error(String tag, String message) { // print(Level.ERROR, tag, message); // } // // public static final void error(String tag, String message, Object... args) { // print(Level.ERROR, tag, message, args); // } // // public static final void error(String tag, String message, Exception ex) { // print(Level.ERROR, tag, message); // ex.printStackTrace(getStream()); // } // // public static final void error(String tag, String message, Exception ex, Object... args) { // print(Level.ERROR, tag, message, args); // ex.printStackTrace(getStream()); // } // // // private static final void print(Level level, String tag, String message) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(message); // getStream().println(builder.toString()); // } // // // private static final void print(Level level, String tag, String message, Object... args) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(format(message, args)); // getStream().println(builder.toString()); // } // // private static final StringBuilder getBuilderWithDate(Level level, String tag) { // StringBuilder builder = new StringBuilder(); // Calendar now = Calendar.getInstance(); // builder.append('['); // builder.append(now.get(Calendar.YEAR)); // builder.append('-'); // builder.append(now.get(Calendar.MONTH)); // builder.append('-'); // builder.append(now.get(Calendar.DAY_OF_MONTH)); // builder.append(' '); // builder.append(now.get(Calendar.HOUR_OF_DAY)); // builder.append(':'); // builder.append(now.get(Calendar.MINUTE)); // builder.append(':'); // builder.append(now.get(Calendar.SECOND)); // builder.append(','); // builder.append(now.get(Calendar.MILLISECOND)); // builder.append("]\t"); // builder.append(level.name()); // builder.append(" \t"); // builder.append(tag); // builder.append(": \t"); // return builder; // } // // public static PrintStream getStream() { // return stream; // } // // public static void setStream(PrintStream stream) { // Logger.stream = stream; // } // // public enum Level { // TRACE, // DEBUG, // INFO, // WARNING, // ERROR // } // } // // Path: heartbeat-network/src/main/java/com/heartbeat/network/BeatListener.java // public interface BeatListener { // void onBeat(byte[] response); // // void onError(Exception e); // } // // Path: heartbeat-network/src/main/java/com/heartbeat/network/HeartBeatConfiguration.java // public interface HeartBeatConfiguration { // long getInterval(); // // long getFailedRetryInterval(); // // int getSocketTimeout(); // // int getSocketPort(); // // int getServerPort(); // }
import com.heartbeat.log.Logger; import com.heartbeat.network.BeatListener; import com.heartbeat.network.HeartBeatConfiguration; import java.net.*; import java.util.Enumeration;
package com.heartbeat.network.udp; /** * This Class does the broadcasts the given {@link HeartBeatInfo} from the * given {@link #socketPort} to the {@link #serverPort}. * It starts the thread with {@link #start()} method and broadcasts on every {@link #interval}. * On every error thread sleep time becomes {@link #failedInterval}. * If it succeeds, again {@link #interval} will be the sleep time. * It stops the thread with {@link #stop()} method. * Also supports {@link BeatListener} to trigger events on each beat. */ public class UDPHeartBeat { private static final String TAG = UDPHeartBeat.class.getName(); private final int socketPort; private final int serverPort;
// Path: heartbeat-log/src/main/java/com/heartbeat/log/Logger.java // public final class Logger { // private static Level defaultPackageLevel = Level.INFO; // private static PrintStream stream = System.out; // //TODO: Appender system // //TODO: Tag-level checks. // // private Logger() { // } // // public static Level getLevel() { // return defaultPackageLevel; // } // // public static void setLevel(Level defaultPackageLevel) { // Logger.defaultPackageLevel = defaultPackageLevel; // } // // public static final void trace(String tag, String message) { // print(Level.TRACE, tag, message); // // } // // public static final void trace(String tag, String message, Object... args) { // print(Level.TRACE, tag, message, args); // // } // // public static final void debug(String tag, String message) { // print(Level.DEBUG, tag, message); // // } // // public static final void debug(String tag, String message, Object... args) { // print(Level.DEBUG, tag, message, args); // // } // // public static final void info(String tag, String message) { // print(Level.INFO, tag, message); // // } // // public static final void info(String tag, String message, Object... args) { // print(Level.INFO, tag, message, args); // } // // public static final void warn(String tag, String message) { // print(Level.WARNING, tag, message); // } // // public static final void warn(String tag, String message, Object... args) { // print(Level.WARNING, tag, message, args); // } // // public static final void error(String tag, String message) { // print(Level.ERROR, tag, message); // } // // public static final void error(String tag, String message, Object... args) { // print(Level.ERROR, tag, message, args); // } // // public static final void error(String tag, String message, Exception ex) { // print(Level.ERROR, tag, message); // ex.printStackTrace(getStream()); // } // // public static final void error(String tag, String message, Exception ex, Object... args) { // print(Level.ERROR, tag, message, args); // ex.printStackTrace(getStream()); // } // // // private static final void print(Level level, String tag, String message) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(message); // getStream().println(builder.toString()); // } // // // private static final void print(Level level, String tag, String message, Object... args) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(format(message, args)); // getStream().println(builder.toString()); // } // // private static final StringBuilder getBuilderWithDate(Level level, String tag) { // StringBuilder builder = new StringBuilder(); // Calendar now = Calendar.getInstance(); // builder.append('['); // builder.append(now.get(Calendar.YEAR)); // builder.append('-'); // builder.append(now.get(Calendar.MONTH)); // builder.append('-'); // builder.append(now.get(Calendar.DAY_OF_MONTH)); // builder.append(' '); // builder.append(now.get(Calendar.HOUR_OF_DAY)); // builder.append(':'); // builder.append(now.get(Calendar.MINUTE)); // builder.append(':'); // builder.append(now.get(Calendar.SECOND)); // builder.append(','); // builder.append(now.get(Calendar.MILLISECOND)); // builder.append("]\t"); // builder.append(level.name()); // builder.append(" \t"); // builder.append(tag); // builder.append(": \t"); // return builder; // } // // public static PrintStream getStream() { // return stream; // } // // public static void setStream(PrintStream stream) { // Logger.stream = stream; // } // // public enum Level { // TRACE, // DEBUG, // INFO, // WARNING, // ERROR // } // } // // Path: heartbeat-network/src/main/java/com/heartbeat/network/BeatListener.java // public interface BeatListener { // void onBeat(byte[] response); // // void onError(Exception e); // } // // Path: heartbeat-network/src/main/java/com/heartbeat/network/HeartBeatConfiguration.java // public interface HeartBeatConfiguration { // long getInterval(); // // long getFailedRetryInterval(); // // int getSocketTimeout(); // // int getSocketPort(); // // int getServerPort(); // } // Path: heartbeat-network/src/main/java/com/heartbeat/network/udp/UDPHeartBeat.java import com.heartbeat.log.Logger; import com.heartbeat.network.BeatListener; import com.heartbeat.network.HeartBeatConfiguration; import java.net.*; import java.util.Enumeration; package com.heartbeat.network.udp; /** * This Class does the broadcasts the given {@link HeartBeatInfo} from the * given {@link #socketPort} to the {@link #serverPort}. * It starts the thread with {@link #start()} method and broadcasts on every {@link #interval}. * On every error thread sleep time becomes {@link #failedInterval}. * If it succeeds, again {@link #interval} will be the sleep time. * It stops the thread with {@link #stop()} method. * Also supports {@link BeatListener} to trigger events on each beat. */ public class UDPHeartBeat { private static final String TAG = UDPHeartBeat.class.getName(); private final int socketPort; private final int serverPort;
private BeatListener beatListener;
serayuzgur/heartbeat
heartbeat-network/src/main/java/com/heartbeat/network/udp/UDPHeartBeat.java
// Path: heartbeat-log/src/main/java/com/heartbeat/log/Logger.java // public final class Logger { // private static Level defaultPackageLevel = Level.INFO; // private static PrintStream stream = System.out; // //TODO: Appender system // //TODO: Tag-level checks. // // private Logger() { // } // // public static Level getLevel() { // return defaultPackageLevel; // } // // public static void setLevel(Level defaultPackageLevel) { // Logger.defaultPackageLevel = defaultPackageLevel; // } // // public static final void trace(String tag, String message) { // print(Level.TRACE, tag, message); // // } // // public static final void trace(String tag, String message, Object... args) { // print(Level.TRACE, tag, message, args); // // } // // public static final void debug(String tag, String message) { // print(Level.DEBUG, tag, message); // // } // // public static final void debug(String tag, String message, Object... args) { // print(Level.DEBUG, tag, message, args); // // } // // public static final void info(String tag, String message) { // print(Level.INFO, tag, message); // // } // // public static final void info(String tag, String message, Object... args) { // print(Level.INFO, tag, message, args); // } // // public static final void warn(String tag, String message) { // print(Level.WARNING, tag, message); // } // // public static final void warn(String tag, String message, Object... args) { // print(Level.WARNING, tag, message, args); // } // // public static final void error(String tag, String message) { // print(Level.ERROR, tag, message); // } // // public static final void error(String tag, String message, Object... args) { // print(Level.ERROR, tag, message, args); // } // // public static final void error(String tag, String message, Exception ex) { // print(Level.ERROR, tag, message); // ex.printStackTrace(getStream()); // } // // public static final void error(String tag, String message, Exception ex, Object... args) { // print(Level.ERROR, tag, message, args); // ex.printStackTrace(getStream()); // } // // // private static final void print(Level level, String tag, String message) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(message); // getStream().println(builder.toString()); // } // // // private static final void print(Level level, String tag, String message, Object... args) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(format(message, args)); // getStream().println(builder.toString()); // } // // private static final StringBuilder getBuilderWithDate(Level level, String tag) { // StringBuilder builder = new StringBuilder(); // Calendar now = Calendar.getInstance(); // builder.append('['); // builder.append(now.get(Calendar.YEAR)); // builder.append('-'); // builder.append(now.get(Calendar.MONTH)); // builder.append('-'); // builder.append(now.get(Calendar.DAY_OF_MONTH)); // builder.append(' '); // builder.append(now.get(Calendar.HOUR_OF_DAY)); // builder.append(':'); // builder.append(now.get(Calendar.MINUTE)); // builder.append(':'); // builder.append(now.get(Calendar.SECOND)); // builder.append(','); // builder.append(now.get(Calendar.MILLISECOND)); // builder.append("]\t"); // builder.append(level.name()); // builder.append(" \t"); // builder.append(tag); // builder.append(": \t"); // return builder; // } // // public static PrintStream getStream() { // return stream; // } // // public static void setStream(PrintStream stream) { // Logger.stream = stream; // } // // public enum Level { // TRACE, // DEBUG, // INFO, // WARNING, // ERROR // } // } // // Path: heartbeat-network/src/main/java/com/heartbeat/network/BeatListener.java // public interface BeatListener { // void onBeat(byte[] response); // // void onError(Exception e); // } // // Path: heartbeat-network/src/main/java/com/heartbeat/network/HeartBeatConfiguration.java // public interface HeartBeatConfiguration { // long getInterval(); // // long getFailedRetryInterval(); // // int getSocketTimeout(); // // int getSocketPort(); // // int getServerPort(); // }
import com.heartbeat.log.Logger; import com.heartbeat.network.BeatListener; import com.heartbeat.network.HeartBeatConfiguration; import java.net.*; import java.util.Enumeration;
package com.heartbeat.network.udp; /** * This Class does the broadcasts the given {@link HeartBeatInfo} from the * given {@link #socketPort} to the {@link #serverPort}. * It starts the thread with {@link #start()} method and broadcasts on every {@link #interval}. * On every error thread sleep time becomes {@link #failedInterval}. * If it succeeds, again {@link #interval} will be the sleep time. * It stops the thread with {@link #stop()} method. * Also supports {@link BeatListener} to trigger events on each beat. */ public class UDPHeartBeat { private static final String TAG = UDPHeartBeat.class.getName(); private final int socketPort; private final int serverPort; private BeatListener beatListener; private long interval; private long failedInterval; private int socketTimeout; private final HeartBeatInfo me; private Status status; private Thread thread; private boolean pleaseStop = false; /** * @param configuration necessary configuration to start heartbeat * @param me Nodes own information. It will be shared with broadcast messages. */
// Path: heartbeat-log/src/main/java/com/heartbeat/log/Logger.java // public final class Logger { // private static Level defaultPackageLevel = Level.INFO; // private static PrintStream stream = System.out; // //TODO: Appender system // //TODO: Tag-level checks. // // private Logger() { // } // // public static Level getLevel() { // return defaultPackageLevel; // } // // public static void setLevel(Level defaultPackageLevel) { // Logger.defaultPackageLevel = defaultPackageLevel; // } // // public static final void trace(String tag, String message) { // print(Level.TRACE, tag, message); // // } // // public static final void trace(String tag, String message, Object... args) { // print(Level.TRACE, tag, message, args); // // } // // public static final void debug(String tag, String message) { // print(Level.DEBUG, tag, message); // // } // // public static final void debug(String tag, String message, Object... args) { // print(Level.DEBUG, tag, message, args); // // } // // public static final void info(String tag, String message) { // print(Level.INFO, tag, message); // // } // // public static final void info(String tag, String message, Object... args) { // print(Level.INFO, tag, message, args); // } // // public static final void warn(String tag, String message) { // print(Level.WARNING, tag, message); // } // // public static final void warn(String tag, String message, Object... args) { // print(Level.WARNING, tag, message, args); // } // // public static final void error(String tag, String message) { // print(Level.ERROR, tag, message); // } // // public static final void error(String tag, String message, Object... args) { // print(Level.ERROR, tag, message, args); // } // // public static final void error(String tag, String message, Exception ex) { // print(Level.ERROR, tag, message); // ex.printStackTrace(getStream()); // } // // public static final void error(String tag, String message, Exception ex, Object... args) { // print(Level.ERROR, tag, message, args); // ex.printStackTrace(getStream()); // } // // // private static final void print(Level level, String tag, String message) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(message); // getStream().println(builder.toString()); // } // // // private static final void print(Level level, String tag, String message, Object... args) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(format(message, args)); // getStream().println(builder.toString()); // } // // private static final StringBuilder getBuilderWithDate(Level level, String tag) { // StringBuilder builder = new StringBuilder(); // Calendar now = Calendar.getInstance(); // builder.append('['); // builder.append(now.get(Calendar.YEAR)); // builder.append('-'); // builder.append(now.get(Calendar.MONTH)); // builder.append('-'); // builder.append(now.get(Calendar.DAY_OF_MONTH)); // builder.append(' '); // builder.append(now.get(Calendar.HOUR_OF_DAY)); // builder.append(':'); // builder.append(now.get(Calendar.MINUTE)); // builder.append(':'); // builder.append(now.get(Calendar.SECOND)); // builder.append(','); // builder.append(now.get(Calendar.MILLISECOND)); // builder.append("]\t"); // builder.append(level.name()); // builder.append(" \t"); // builder.append(tag); // builder.append(": \t"); // return builder; // } // // public static PrintStream getStream() { // return stream; // } // // public static void setStream(PrintStream stream) { // Logger.stream = stream; // } // // public enum Level { // TRACE, // DEBUG, // INFO, // WARNING, // ERROR // } // } // // Path: heartbeat-network/src/main/java/com/heartbeat/network/BeatListener.java // public interface BeatListener { // void onBeat(byte[] response); // // void onError(Exception e); // } // // Path: heartbeat-network/src/main/java/com/heartbeat/network/HeartBeatConfiguration.java // public interface HeartBeatConfiguration { // long getInterval(); // // long getFailedRetryInterval(); // // int getSocketTimeout(); // // int getSocketPort(); // // int getServerPort(); // } // Path: heartbeat-network/src/main/java/com/heartbeat/network/udp/UDPHeartBeat.java import com.heartbeat.log.Logger; import com.heartbeat.network.BeatListener; import com.heartbeat.network.HeartBeatConfiguration; import java.net.*; import java.util.Enumeration; package com.heartbeat.network.udp; /** * This Class does the broadcasts the given {@link HeartBeatInfo} from the * given {@link #socketPort} to the {@link #serverPort}. * It starts the thread with {@link #start()} method and broadcasts on every {@link #interval}. * On every error thread sleep time becomes {@link #failedInterval}. * If it succeeds, again {@link #interval} will be the sleep time. * It stops the thread with {@link #stop()} method. * Also supports {@link BeatListener} to trigger events on each beat. */ public class UDPHeartBeat { private static final String TAG = UDPHeartBeat.class.getName(); private final int socketPort; private final int serverPort; private BeatListener beatListener; private long interval; private long failedInterval; private int socketTimeout; private final HeartBeatInfo me; private Status status; private Thread thread; private boolean pleaseStop = false; /** * @param configuration necessary configuration to start heartbeat * @param me Nodes own information. It will be shared with broadcast messages. */
public UDPHeartBeat(HeartBeatConfiguration configuration, HeartBeatInfo me) {
serayuzgur/heartbeat
heartbeat-network/src/test/java/com/heartbeat/network/udp/UDPHeartBeatTest.java
// Path: heartbeat-network/src/main/java/com/heartbeat/network/BeatListener.java // public interface BeatListener { // void onBeat(byte[] response); // // void onError(Exception e); // } // // Path: heartbeat-network/src/main/java/com/heartbeat/network/HeartBeatConfiguration.java // public interface HeartBeatConfiguration { // long getInterval(); // // long getFailedRetryInterval(); // // int getSocketTimeout(); // // int getSocketPort(); // // int getServerPort(); // }
import com.heartbeat.network.BeatListener; import com.heartbeat.network.HeartBeatConfiguration; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import java.net.DatagramPacket; import java.net.DatagramSocket;
package com.heartbeat.network.udp; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class UDPHeartBeatTest {
// Path: heartbeat-network/src/main/java/com/heartbeat/network/BeatListener.java // public interface BeatListener { // void onBeat(byte[] response); // // void onError(Exception e); // } // // Path: heartbeat-network/src/main/java/com/heartbeat/network/HeartBeatConfiguration.java // public interface HeartBeatConfiguration { // long getInterval(); // // long getFailedRetryInterval(); // // int getSocketTimeout(); // // int getSocketPort(); // // int getServerPort(); // } // Path: heartbeat-network/src/test/java/com/heartbeat/network/udp/UDPHeartBeatTest.java import com.heartbeat.network.BeatListener; import com.heartbeat.network.HeartBeatConfiguration; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import java.net.DatagramPacket; import java.net.DatagramSocket; package com.heartbeat.network.udp; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class UDPHeartBeatTest {
HeartBeatConfiguration conf = new HeartBeatConfiguration() {
serayuzgur/heartbeat
heartbeat-network/src/test/java/com/heartbeat/network/udp/UDPHeartBeatTest.java
// Path: heartbeat-network/src/main/java/com/heartbeat/network/BeatListener.java // public interface BeatListener { // void onBeat(byte[] response); // // void onError(Exception e); // } // // Path: heartbeat-network/src/main/java/com/heartbeat/network/HeartBeatConfiguration.java // public interface HeartBeatConfiguration { // long getInterval(); // // long getFailedRetryInterval(); // // int getSocketTimeout(); // // int getSocketPort(); // // int getServerPort(); // }
import com.heartbeat.network.BeatListener; import com.heartbeat.network.HeartBeatConfiguration; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import java.net.DatagramPacket; import java.net.DatagramSocket;
@Test public void testStop() throws Exception { UDPHeartBeat heartBeat = new UDPHeartBeat(conf, me); heartBeat.stop(); } @Test public void testStart() throws Exception { UDPHeartBeat heartBeat = new UDPHeartBeat(conf, me); heartBeat.start(); DatagramSocket receiver = new DatagramSocket(conf.getServerPort()); assert new String(UDPOperations.receiveData(receiver)).equals("TestNode"); heartBeat.stop(); receiver.close(); } @Test public void testStartWithResponse() throws Exception { UDPHeartBeat heartBeat = new UDPHeartBeat(conf, me); heartBeat.start(); DatagramSocket receiver = new DatagramSocket(conf.getServerPort()); DatagramPacket receivedPacket = UDPOperations.receive(receiver); assert new String(receivedPacket.getData()).equals("TestNode"); UDPOperations.send(receiver, receivedPacket.getAddress(), receivedPacket.getPort(), "TestServer".getBytes()); heartBeat.stop(); receiver.close(); } @Test public void testStartWithListener() throws Exception {
// Path: heartbeat-network/src/main/java/com/heartbeat/network/BeatListener.java // public interface BeatListener { // void onBeat(byte[] response); // // void onError(Exception e); // } // // Path: heartbeat-network/src/main/java/com/heartbeat/network/HeartBeatConfiguration.java // public interface HeartBeatConfiguration { // long getInterval(); // // long getFailedRetryInterval(); // // int getSocketTimeout(); // // int getSocketPort(); // // int getServerPort(); // } // Path: heartbeat-network/src/test/java/com/heartbeat/network/udp/UDPHeartBeatTest.java import com.heartbeat.network.BeatListener; import com.heartbeat.network.HeartBeatConfiguration; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import java.net.DatagramPacket; import java.net.DatagramSocket; @Test public void testStop() throws Exception { UDPHeartBeat heartBeat = new UDPHeartBeat(conf, me); heartBeat.stop(); } @Test public void testStart() throws Exception { UDPHeartBeat heartBeat = new UDPHeartBeat(conf, me); heartBeat.start(); DatagramSocket receiver = new DatagramSocket(conf.getServerPort()); assert new String(UDPOperations.receiveData(receiver)).equals("TestNode"); heartBeat.stop(); receiver.close(); } @Test public void testStartWithResponse() throws Exception { UDPHeartBeat heartBeat = new UDPHeartBeat(conf, me); heartBeat.start(); DatagramSocket receiver = new DatagramSocket(conf.getServerPort()); DatagramPacket receivedPacket = UDPOperations.receive(receiver); assert new String(receivedPacket.getData()).equals("TestNode"); UDPOperations.send(receiver, receivedPacket.getAddress(), receivedPacket.getPort(), "TestServer".getBytes()); heartBeat.stop(); receiver.close(); } @Test public void testStartWithListener() throws Exception {
UDPHeartBeat heartBeat = new UDPHeartBeat(conf, me, new BeatListener() {
serayuzgur/heartbeat
heartbeat-common/src/main/java/com/heartbeat/common/conf/Configuration.java
// Path: heartbeat-common/src/main/java/com/heartbeat/common/json/ObjectMapper.java // public class ObjectMapper { // // private static final org.boon.json.ObjectMapper instance = JsonFactory.createUseAnnotations(true); // // public static org.boon.json.ObjectMapper getInstance() { // return instance; // } // }
import com.heartbeat.common.json.ObjectMapper; import java.io.InputStream;
package com.heartbeat.common.conf; /** * An abstract class for the all configurations classes to extend. * It provides necessary methods for loading configuration object from several formats. */ public abstract class Configuration { /** * It provides necessary methods for loading configuration object from JSON format * Reads configuration file. Deserializes it with boon * * @param inputStream * @param configClass * @return */ public final static <T extends Configuration> T loadJson(InputStream inputStream, Class<T> configClass) throws ConfigurationException { try {
// Path: heartbeat-common/src/main/java/com/heartbeat/common/json/ObjectMapper.java // public class ObjectMapper { // // private static final org.boon.json.ObjectMapper instance = JsonFactory.createUseAnnotations(true); // // public static org.boon.json.ObjectMapper getInstance() { // return instance; // } // } // Path: heartbeat-common/src/main/java/com/heartbeat/common/conf/Configuration.java import com.heartbeat.common.json.ObjectMapper; import java.io.InputStream; package com.heartbeat.common.conf; /** * An abstract class for the all configurations classes to extend. * It provides necessary methods for loading configuration object from several formats. */ public abstract class Configuration { /** * It provides necessary methods for loading configuration object from JSON format * Reads configuration file. Deserializes it with boon * * @param inputStream * @param configClass * @return */ public final static <T extends Configuration> T loadJson(InputStream inputStream, Class<T> configClass) throws ConfigurationException { try {
T config = ObjectMapper.getInstance().readValue(inputStream, configClass);
serayuzgur/heartbeat
heartbeat-common/src/main/java/com/heartbeat/common/cli/RuntimeCommandExec.java
// Path: heartbeat-common/src/main/java/com/heartbeat/common/board/OperatingSystem.java // public final class OperatingSystem { // private OperatingSystem() { // } // // private static Type os; // // /** // * Detect the operating system from the os.name System property // * // * @returns - the operating system // */ // public static Type getType() { // return getType(false); // } // // /** // * Detect the operating system from the os.name System property // * // * @returns - the operating system // */ // public static Type getType(boolean force) { // if (force || os == null) { // String osName = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); // if (osName.contains("nux")) { // OperatingSystem.os = Type.LINUX; // } else if (osName.contains("win")) { // OperatingSystem.os = Type.WINDOWS; // } else if (osName.contains("mac")) { // OperatingSystem.os = Type.MAC_OS; // } else { // OperatingSystem.os = Type.OTHER; // } // } // return os; // } // // // /** // * Types of Operating Systems and some default values. // */ // public enum Type { // WINDOWS(new String[]{"cmd.exe", "/c"}), // MAC_OS(new String[]{"bash", "-c"}), // LINUX(new String[]{"bash", "-c"}), // OTHER(new String[]{"bash", "-c"}); // hope they are linux :D // // private final String[] cmdPrefix; // // Type(String[] cmdPrefix) { // this.cmdPrefix = cmdPrefix; // } // // /** // * returns the pre commands of the OS command line // * // * @return // */ // public String[] getCmdPrefix() { // return Arrays.copyOf(cmdPrefix, 2); // } // } // }
import com.heartbeat.common.board.OperatingSystem; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;
result.append(line); } boolean hasError = false; // Collect all the errors to the same builder. while ((line = stdError.readLine()) != null) { result.append(line); hasError = true; } //Check the exiting code. try { int niceExit = p.waitFor(); if (niceExit != 0) hasError = true; } catch (InterruptedException e) { } //In case of error, just merge the outputs together and throw an exception. if (hasError) { throw new RuntimeCommandException(result.toString()); } return result.toString(); } catch (IOException e) { throw new RuntimeCommandException(e); } } private static Process getOSSpecificProcess(String command) throws IOException {
// Path: heartbeat-common/src/main/java/com/heartbeat/common/board/OperatingSystem.java // public final class OperatingSystem { // private OperatingSystem() { // } // // private static Type os; // // /** // * Detect the operating system from the os.name System property // * // * @returns - the operating system // */ // public static Type getType() { // return getType(false); // } // // /** // * Detect the operating system from the os.name System property // * // * @returns - the operating system // */ // public static Type getType(boolean force) { // if (force || os == null) { // String osName = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); // if (osName.contains("nux")) { // OperatingSystem.os = Type.LINUX; // } else if (osName.contains("win")) { // OperatingSystem.os = Type.WINDOWS; // } else if (osName.contains("mac")) { // OperatingSystem.os = Type.MAC_OS; // } else { // OperatingSystem.os = Type.OTHER; // } // } // return os; // } // // // /** // * Types of Operating Systems and some default values. // */ // public enum Type { // WINDOWS(new String[]{"cmd.exe", "/c"}), // MAC_OS(new String[]{"bash", "-c"}), // LINUX(new String[]{"bash", "-c"}), // OTHER(new String[]{"bash", "-c"}); // hope they are linux :D // // private final String[] cmdPrefix; // // Type(String[] cmdPrefix) { // this.cmdPrefix = cmdPrefix; // } // // /** // * returns the pre commands of the OS command line // * // * @return // */ // public String[] getCmdPrefix() { // return Arrays.copyOf(cmdPrefix, 2); // } // } // } // Path: heartbeat-common/src/main/java/com/heartbeat/common/cli/RuntimeCommandExec.java import com.heartbeat.common.board.OperatingSystem; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; result.append(line); } boolean hasError = false; // Collect all the errors to the same builder. while ((line = stdError.readLine()) != null) { result.append(line); hasError = true; } //Check the exiting code. try { int niceExit = p.waitFor(); if (niceExit != 0) hasError = true; } catch (InterruptedException e) { } //In case of error, just merge the outputs together and throw an exception. if (hasError) { throw new RuntimeCommandException(result.toString()); } return result.toString(); } catch (IOException e) { throw new RuntimeCommandException(e); } } private static Process getOSSpecificProcess(String command) throws IOException {
ProcessBuilder pb = new ProcessBuilder(OperatingSystem.getType().getCmdPrefix());
serayuzgur/heartbeat
heartbeat-pin/src/main/java/com/heartbeat/pin/Pin.java
// Path: heartbeat-pin/src/main/java/com/heartbeat/pin/command/PinCommand.java // public interface PinCommand { // // /** // * Gets the mode of given pin from system. // * // * @param pin // */ // Pin.Mode getMode(Pin pin) throws PinCommandException; // // /** // * Gets the mode and the pin instance and sets to the system. // * // * @param pin // */ // void setMode(Pin pin, Pin.Mode mode) throws PinCommandException; // // /** // * Enables the given pin from system. // * // * @param pin // */ // void enable(Pin pin) throws PinCommandException; // // /** // * Disable the given pin from system. // * // * @param pin // */ // void disable(Pin pin) throws PinCommandException; // // /** // * Reads the given film from system. // * // * @param pin // * @return // */ // boolean read(Pin pin) throws PinCommandException; // // /** // * Writes the given pins value from the system. // * // * @param pin // * @param value // * @return // */ // void write(Pin pin, boolean value) throws PinCommandException; // // // /** // * Returns the path of the pin. // * // * @param pin // * @return // */ // File path(Pin pin); // } // // Path: heartbeat-pin/src/main/java/com/heartbeat/pin/command/PinCommandException.java // public class PinCommandException extends PinException { // // public PinCommandException(String message) { // super(message); // } // // public PinCommandException() { // } // // public PinCommandException(String message, Throwable cause) { // super(message, cause); // } // // public PinCommandException(Throwable cause) { // super(cause); // } // // public PinCommandException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // }
import com.heartbeat.pin.command.PinCommand; import com.heartbeat.pin.command.PinCommandException; import java.io.File;
package com.heartbeat.pin; /** * A class for Pin. Stores necessary data and some pin lifecycle methods like * <ul> * <li>enable</li> * <li>disable</li> * <li>write</li> * <li>read</li> * <li>setMode</li> * </ul> * Holds code forex. "408" and path "/sys/class/gpio/gpio408 */ public class Pin { /* Pins * * X10-P0: 408 * X10-P1: 409 * X10-P2: 410 * X10-P3: 411 * X10-P4: 412 * X10-P5: 413 * X10-P6: 414 * X10-P7: 415 */ private final String code; private final File path; protected Mode mode;
// Path: heartbeat-pin/src/main/java/com/heartbeat/pin/command/PinCommand.java // public interface PinCommand { // // /** // * Gets the mode of given pin from system. // * // * @param pin // */ // Pin.Mode getMode(Pin pin) throws PinCommandException; // // /** // * Gets the mode and the pin instance and sets to the system. // * // * @param pin // */ // void setMode(Pin pin, Pin.Mode mode) throws PinCommandException; // // /** // * Enables the given pin from system. // * // * @param pin // */ // void enable(Pin pin) throws PinCommandException; // // /** // * Disable the given pin from system. // * // * @param pin // */ // void disable(Pin pin) throws PinCommandException; // // /** // * Reads the given film from system. // * // * @param pin // * @return // */ // boolean read(Pin pin) throws PinCommandException; // // /** // * Writes the given pins value from the system. // * // * @param pin // * @param value // * @return // */ // void write(Pin pin, boolean value) throws PinCommandException; // // // /** // * Returns the path of the pin. // * // * @param pin // * @return // */ // File path(Pin pin); // } // // Path: heartbeat-pin/src/main/java/com/heartbeat/pin/command/PinCommandException.java // public class PinCommandException extends PinException { // // public PinCommandException(String message) { // super(message); // } // // public PinCommandException() { // } // // public PinCommandException(String message, Throwable cause) { // super(message, cause); // } // // public PinCommandException(Throwable cause) { // super(cause); // } // // public PinCommandException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: heartbeat-pin/src/main/java/com/heartbeat/pin/Pin.java import com.heartbeat.pin.command.PinCommand; import com.heartbeat.pin.command.PinCommandException; import java.io.File; package com.heartbeat.pin; /** * A class for Pin. Stores necessary data and some pin lifecycle methods like * <ul> * <li>enable</li> * <li>disable</li> * <li>write</li> * <li>read</li> * <li>setMode</li> * </ul> * Holds code forex. "408" and path "/sys/class/gpio/gpio408 */ public class Pin { /* Pins * * X10-P0: 408 * X10-P1: 409 * X10-P2: 410 * X10-P3: 411 * X10-P4: 412 * X10-P5: 413 * X10-P6: 414 * X10-P7: 415 */ private final String code; private final File path; protected Mode mode;
private final PinCommand command;
serayuzgur/heartbeat
heartbeat-pin/src/main/java/com/heartbeat/pin/Pin.java
// Path: heartbeat-pin/src/main/java/com/heartbeat/pin/command/PinCommand.java // public interface PinCommand { // // /** // * Gets the mode of given pin from system. // * // * @param pin // */ // Pin.Mode getMode(Pin pin) throws PinCommandException; // // /** // * Gets the mode and the pin instance and sets to the system. // * // * @param pin // */ // void setMode(Pin pin, Pin.Mode mode) throws PinCommandException; // // /** // * Enables the given pin from system. // * // * @param pin // */ // void enable(Pin pin) throws PinCommandException; // // /** // * Disable the given pin from system. // * // * @param pin // */ // void disable(Pin pin) throws PinCommandException; // // /** // * Reads the given film from system. // * // * @param pin // * @return // */ // boolean read(Pin pin) throws PinCommandException; // // /** // * Writes the given pins value from the system. // * // * @param pin // * @param value // * @return // */ // void write(Pin pin, boolean value) throws PinCommandException; // // // /** // * Returns the path of the pin. // * // * @param pin // * @return // */ // File path(Pin pin); // } // // Path: heartbeat-pin/src/main/java/com/heartbeat/pin/command/PinCommandException.java // public class PinCommandException extends PinException { // // public PinCommandException(String message) { // super(message); // } // // public PinCommandException() { // } // // public PinCommandException(String message, Throwable cause) { // super(message, cause); // } // // public PinCommandException(Throwable cause) { // super(cause); // } // // public PinCommandException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // }
import com.heartbeat.pin.command.PinCommand; import com.heartbeat.pin.command.PinCommandException; import java.io.File;
package com.heartbeat.pin; /** * A class for Pin. Stores necessary data and some pin lifecycle methods like * <ul> * <li>enable</li> * <li>disable</li> * <li>write</li> * <li>read</li> * <li>setMode</li> * </ul> * Holds code forex. "408" and path "/sys/class/gpio/gpio408 */ public class Pin { /* Pins * * X10-P0: 408 * X10-P1: 409 * X10-P2: 410 * X10-P3: 411 * X10-P4: 412 * X10-P5: 413 * X10-P6: 414 * X10-P7: 415 */ private final String code; private final File path; protected Mode mode; private final PinCommand command; private boolean enabled;
// Path: heartbeat-pin/src/main/java/com/heartbeat/pin/command/PinCommand.java // public interface PinCommand { // // /** // * Gets the mode of given pin from system. // * // * @param pin // */ // Pin.Mode getMode(Pin pin) throws PinCommandException; // // /** // * Gets the mode and the pin instance and sets to the system. // * // * @param pin // */ // void setMode(Pin pin, Pin.Mode mode) throws PinCommandException; // // /** // * Enables the given pin from system. // * // * @param pin // */ // void enable(Pin pin) throws PinCommandException; // // /** // * Disable the given pin from system. // * // * @param pin // */ // void disable(Pin pin) throws PinCommandException; // // /** // * Reads the given film from system. // * // * @param pin // * @return // */ // boolean read(Pin pin) throws PinCommandException; // // /** // * Writes the given pins value from the system. // * // * @param pin // * @param value // * @return // */ // void write(Pin pin, boolean value) throws PinCommandException; // // // /** // * Returns the path of the pin. // * // * @param pin // * @return // */ // File path(Pin pin); // } // // Path: heartbeat-pin/src/main/java/com/heartbeat/pin/command/PinCommandException.java // public class PinCommandException extends PinException { // // public PinCommandException(String message) { // super(message); // } // // public PinCommandException() { // } // // public PinCommandException(String message, Throwable cause) { // super(message, cause); // } // // public PinCommandException(Throwable cause) { // super(cause); // } // // public PinCommandException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: heartbeat-pin/src/main/java/com/heartbeat/pin/Pin.java import com.heartbeat.pin.command.PinCommand; import com.heartbeat.pin.command.PinCommandException; import java.io.File; package com.heartbeat.pin; /** * A class for Pin. Stores necessary data and some pin lifecycle methods like * <ul> * <li>enable</li> * <li>disable</li> * <li>write</li> * <li>read</li> * <li>setMode</li> * </ul> * Holds code forex. "408" and path "/sys/class/gpio/gpio408 */ public class Pin { /* Pins * * X10-P0: 408 * X10-P1: 409 * X10-P2: 410 * X10-P3: 411 * X10-P4: 412 * X10-P5: 413 * X10-P6: 414 * X10-P7: 415 */ private final String code; private final File path; protected Mode mode; private final PinCommand command; private boolean enabled;
public Pin(String code, Mode mode, PinCommand command) throws PinCommandException {
serayuzgur/heartbeat
heartbeat-pin/src/main/java/com/heartbeat/pin/PinWriter.java
// Path: heartbeat-log/src/main/java/com/heartbeat/log/Logger.java // public final class Logger { // private static Level defaultPackageLevel = Level.INFO; // private static PrintStream stream = System.out; // //TODO: Appender system // //TODO: Tag-level checks. // // private Logger() { // } // // public static Level getLevel() { // return defaultPackageLevel; // } // // public static void setLevel(Level defaultPackageLevel) { // Logger.defaultPackageLevel = defaultPackageLevel; // } // // public static final void trace(String tag, String message) { // print(Level.TRACE, tag, message); // // } // // public static final void trace(String tag, String message, Object... args) { // print(Level.TRACE, tag, message, args); // // } // // public static final void debug(String tag, String message) { // print(Level.DEBUG, tag, message); // // } // // public static final void debug(String tag, String message, Object... args) { // print(Level.DEBUG, tag, message, args); // // } // // public static final void info(String tag, String message) { // print(Level.INFO, tag, message); // // } // // public static final void info(String tag, String message, Object... args) { // print(Level.INFO, tag, message, args); // } // // public static final void warn(String tag, String message) { // print(Level.WARNING, tag, message); // } // // public static final void warn(String tag, String message, Object... args) { // print(Level.WARNING, tag, message, args); // } // // public static final void error(String tag, String message) { // print(Level.ERROR, tag, message); // } // // public static final void error(String tag, String message, Object... args) { // print(Level.ERROR, tag, message, args); // } // // public static final void error(String tag, String message, Exception ex) { // print(Level.ERROR, tag, message); // ex.printStackTrace(getStream()); // } // // public static final void error(String tag, String message, Exception ex, Object... args) { // print(Level.ERROR, tag, message, args); // ex.printStackTrace(getStream()); // } // // // private static final void print(Level level, String tag, String message) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(message); // getStream().println(builder.toString()); // } // // // private static final void print(Level level, String tag, String message, Object... args) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(format(message, args)); // getStream().println(builder.toString()); // } // // private static final StringBuilder getBuilderWithDate(Level level, String tag) { // StringBuilder builder = new StringBuilder(); // Calendar now = Calendar.getInstance(); // builder.append('['); // builder.append(now.get(Calendar.YEAR)); // builder.append('-'); // builder.append(now.get(Calendar.MONTH)); // builder.append('-'); // builder.append(now.get(Calendar.DAY_OF_MONTH)); // builder.append(' '); // builder.append(now.get(Calendar.HOUR_OF_DAY)); // builder.append(':'); // builder.append(now.get(Calendar.MINUTE)); // builder.append(':'); // builder.append(now.get(Calendar.SECOND)); // builder.append(','); // builder.append(now.get(Calendar.MILLISECOND)); // builder.append("]\t"); // builder.append(level.name()); // builder.append(" \t"); // builder.append(tag); // builder.append(": \t"); // return builder; // } // // public static PrintStream getStream() { // return stream; // } // // public static void setStream(PrintStream stream) { // Logger.stream = stream; // } // // public enum Level { // TRACE, // DEBUG, // INFO, // WARNING, // ERROR // } // }
import com.heartbeat.log.Logger; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel;
package com.heartbeat.pin; /** * A high performance writer class which opens a {@link FileChannel} to the pin. * It uses {@link ByteBuffer} with the size 1 and reuses it for every write. */ public class PinWriter { private static final String TAG = PinWriter.class.getName(); private final Pin pin; private ByteBuffer TRUE = ByteBuffer.wrap("1".getBytes()); private ByteBuffer FALSE = ByteBuffer.wrap("0".getBytes()); private final FileOutputStream os; private final FileChannel fch; /** * Creates a outputstream and file channel for the pin. * * @param pin * @throws IOException */ public PinWriter(Pin pin) throws IOException { this.pin = pin; os = new FileOutputStream(pin.getPath()); fch = os.getChannel(); } /** * Writes the value. * Writes "1" for true, writes "0" for false. * * @param value value * @throws IOException */ public void write(boolean value) throws IOException { fch.write(value ? TRUE : FALSE); if (value) TRUE.position(0); else FALSE.position(0); fch.position(0); os.flush(); } /** * Closes reader , releases file channel and output stream. */ public void close() { if (fch != null && fch.isOpen()) { try { fch.close(); } catch (IOException e) {
// Path: heartbeat-log/src/main/java/com/heartbeat/log/Logger.java // public final class Logger { // private static Level defaultPackageLevel = Level.INFO; // private static PrintStream stream = System.out; // //TODO: Appender system // //TODO: Tag-level checks. // // private Logger() { // } // // public static Level getLevel() { // return defaultPackageLevel; // } // // public static void setLevel(Level defaultPackageLevel) { // Logger.defaultPackageLevel = defaultPackageLevel; // } // // public static final void trace(String tag, String message) { // print(Level.TRACE, tag, message); // // } // // public static final void trace(String tag, String message, Object... args) { // print(Level.TRACE, tag, message, args); // // } // // public static final void debug(String tag, String message) { // print(Level.DEBUG, tag, message); // // } // // public static final void debug(String tag, String message, Object... args) { // print(Level.DEBUG, tag, message, args); // // } // // public static final void info(String tag, String message) { // print(Level.INFO, tag, message); // // } // // public static final void info(String tag, String message, Object... args) { // print(Level.INFO, tag, message, args); // } // // public static final void warn(String tag, String message) { // print(Level.WARNING, tag, message); // } // // public static final void warn(String tag, String message, Object... args) { // print(Level.WARNING, tag, message, args); // } // // public static final void error(String tag, String message) { // print(Level.ERROR, tag, message); // } // // public static final void error(String tag, String message, Object... args) { // print(Level.ERROR, tag, message, args); // } // // public static final void error(String tag, String message, Exception ex) { // print(Level.ERROR, tag, message); // ex.printStackTrace(getStream()); // } // // public static final void error(String tag, String message, Exception ex, Object... args) { // print(Level.ERROR, tag, message, args); // ex.printStackTrace(getStream()); // } // // // private static final void print(Level level, String tag, String message) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(message); // getStream().println(builder.toString()); // } // // // private static final void print(Level level, String tag, String message, Object... args) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(format(message, args)); // getStream().println(builder.toString()); // } // // private static final StringBuilder getBuilderWithDate(Level level, String tag) { // StringBuilder builder = new StringBuilder(); // Calendar now = Calendar.getInstance(); // builder.append('['); // builder.append(now.get(Calendar.YEAR)); // builder.append('-'); // builder.append(now.get(Calendar.MONTH)); // builder.append('-'); // builder.append(now.get(Calendar.DAY_OF_MONTH)); // builder.append(' '); // builder.append(now.get(Calendar.HOUR_OF_DAY)); // builder.append(':'); // builder.append(now.get(Calendar.MINUTE)); // builder.append(':'); // builder.append(now.get(Calendar.SECOND)); // builder.append(','); // builder.append(now.get(Calendar.MILLISECOND)); // builder.append("]\t"); // builder.append(level.name()); // builder.append(" \t"); // builder.append(tag); // builder.append(": \t"); // return builder; // } // // public static PrintStream getStream() { // return stream; // } // // public static void setStream(PrintStream stream) { // Logger.stream = stream; // } // // public enum Level { // TRACE, // DEBUG, // INFO, // WARNING, // ERROR // } // } // Path: heartbeat-pin/src/main/java/com/heartbeat/pin/PinWriter.java import com.heartbeat.log.Logger; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; package com.heartbeat.pin; /** * A high performance writer class which opens a {@link FileChannel} to the pin. * It uses {@link ByteBuffer} with the size 1 and reuses it for every write. */ public class PinWriter { private static final String TAG = PinWriter.class.getName(); private final Pin pin; private ByteBuffer TRUE = ByteBuffer.wrap("1".getBytes()); private ByteBuffer FALSE = ByteBuffer.wrap("0".getBytes()); private final FileOutputStream os; private final FileChannel fch; /** * Creates a outputstream and file channel for the pin. * * @param pin * @throws IOException */ public PinWriter(Pin pin) throws IOException { this.pin = pin; os = new FileOutputStream(pin.getPath()); fch = os.getChannel(); } /** * Writes the value. * Writes "1" for true, writes "0" for false. * * @param value value * @throws IOException */ public void write(boolean value) throws IOException { fch.write(value ? TRUE : FALSE); if (value) TRUE.position(0); else FALSE.position(0); fch.position(0); os.flush(); } /** * Closes reader , releases file channel and output stream. */ public void close() { if (fch != null && fch.isOpen()) { try { fch.close(); } catch (IOException e) {
Logger.error(TAG, "Can not close Reader FileChannel %s", e, pin.getCode());
serayuzgur/heartbeat
heartbeat-network/src/main/java/com/heartbeat/network/udp/UDPOperations.java
// Path: heartbeat-common/src/main/java/com/heartbeat/common/array/ByteArray.java // public final class ByteArray { // // private ByteArray() { // } // // /** // * Trims the given array. Finds the starting position of null index and copies with {@link Arrays#copyOf(boolean[], int)} // * // * @param bytes original array // * @return trimmed array // */ // public static final byte[] trim(byte[] bytes) { // int i = bytes.length - 1; // while (i >= 0 && bytes[i] == 0) { // --i; // } // // return Arrays.copyOf(bytes, i + 1); // } // // } // // Path: heartbeat-log/src/main/java/com/heartbeat/log/Logger.java // public final class Logger { // private static Level defaultPackageLevel = Level.INFO; // private static PrintStream stream = System.out; // //TODO: Appender system // //TODO: Tag-level checks. // // private Logger() { // } // // public static Level getLevel() { // return defaultPackageLevel; // } // // public static void setLevel(Level defaultPackageLevel) { // Logger.defaultPackageLevel = defaultPackageLevel; // } // // public static final void trace(String tag, String message) { // print(Level.TRACE, tag, message); // // } // // public static final void trace(String tag, String message, Object... args) { // print(Level.TRACE, tag, message, args); // // } // // public static final void debug(String tag, String message) { // print(Level.DEBUG, tag, message); // // } // // public static final void debug(String tag, String message, Object... args) { // print(Level.DEBUG, tag, message, args); // // } // // public static final void info(String tag, String message) { // print(Level.INFO, tag, message); // // } // // public static final void info(String tag, String message, Object... args) { // print(Level.INFO, tag, message, args); // } // // public static final void warn(String tag, String message) { // print(Level.WARNING, tag, message); // } // // public static final void warn(String tag, String message, Object... args) { // print(Level.WARNING, tag, message, args); // } // // public static final void error(String tag, String message) { // print(Level.ERROR, tag, message); // } // // public static final void error(String tag, String message, Object... args) { // print(Level.ERROR, tag, message, args); // } // // public static final void error(String tag, String message, Exception ex) { // print(Level.ERROR, tag, message); // ex.printStackTrace(getStream()); // } // // public static final void error(String tag, String message, Exception ex, Object... args) { // print(Level.ERROR, tag, message, args); // ex.printStackTrace(getStream()); // } // // // private static final void print(Level level, String tag, String message) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(message); // getStream().println(builder.toString()); // } // // // private static final void print(Level level, String tag, String message, Object... args) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(format(message, args)); // getStream().println(builder.toString()); // } // // private static final StringBuilder getBuilderWithDate(Level level, String tag) { // StringBuilder builder = new StringBuilder(); // Calendar now = Calendar.getInstance(); // builder.append('['); // builder.append(now.get(Calendar.YEAR)); // builder.append('-'); // builder.append(now.get(Calendar.MONTH)); // builder.append('-'); // builder.append(now.get(Calendar.DAY_OF_MONTH)); // builder.append(' '); // builder.append(now.get(Calendar.HOUR_OF_DAY)); // builder.append(':'); // builder.append(now.get(Calendar.MINUTE)); // builder.append(':'); // builder.append(now.get(Calendar.SECOND)); // builder.append(','); // builder.append(now.get(Calendar.MILLISECOND)); // builder.append("]\t"); // builder.append(level.name()); // builder.append(" \t"); // builder.append(tag); // builder.append(": \t"); // return builder; // } // // public static PrintStream getStream() { // return stream; // } // // public static void setStream(PrintStream stream) { // Logger.stream = stream; // } // // public enum Level { // TRACE, // DEBUG, // INFO, // WARNING, // ERROR // } // }
import com.heartbeat.common.array.ByteArray; import com.heartbeat.log.Logger; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import static java.lang.String.format;
package com.heartbeat.network.udp; /** * A static helper class for basic common UDP operations. */ public final class UDPOperations { private static final String TAG = UDPOperations.class.getName(); private UDPOperations() { } /** * Sends a UDP datagram to the receiver * * @param socket local socket * @param receiverIP receiver IP address * @param receiverPort receiver port * @param data data to send * @throws IOException */ public static final void send(DatagramSocket socket, InetAddress receiverIP, int receiverPort, byte[] data) throws IOException { DatagramPacket sendPacket = new DatagramPacket(data, data.length, receiverIP, receiverPort); socket.send(sendPacket);
// Path: heartbeat-common/src/main/java/com/heartbeat/common/array/ByteArray.java // public final class ByteArray { // // private ByteArray() { // } // // /** // * Trims the given array. Finds the starting position of null index and copies with {@link Arrays#copyOf(boolean[], int)} // * // * @param bytes original array // * @return trimmed array // */ // public static final byte[] trim(byte[] bytes) { // int i = bytes.length - 1; // while (i >= 0 && bytes[i] == 0) { // --i; // } // // return Arrays.copyOf(bytes, i + 1); // } // // } // // Path: heartbeat-log/src/main/java/com/heartbeat/log/Logger.java // public final class Logger { // private static Level defaultPackageLevel = Level.INFO; // private static PrintStream stream = System.out; // //TODO: Appender system // //TODO: Tag-level checks. // // private Logger() { // } // // public static Level getLevel() { // return defaultPackageLevel; // } // // public static void setLevel(Level defaultPackageLevel) { // Logger.defaultPackageLevel = defaultPackageLevel; // } // // public static final void trace(String tag, String message) { // print(Level.TRACE, tag, message); // // } // // public static final void trace(String tag, String message, Object... args) { // print(Level.TRACE, tag, message, args); // // } // // public static final void debug(String tag, String message) { // print(Level.DEBUG, tag, message); // // } // // public static final void debug(String tag, String message, Object... args) { // print(Level.DEBUG, tag, message, args); // // } // // public static final void info(String tag, String message) { // print(Level.INFO, tag, message); // // } // // public static final void info(String tag, String message, Object... args) { // print(Level.INFO, tag, message, args); // } // // public static final void warn(String tag, String message) { // print(Level.WARNING, tag, message); // } // // public static final void warn(String tag, String message, Object... args) { // print(Level.WARNING, tag, message, args); // } // // public static final void error(String tag, String message) { // print(Level.ERROR, tag, message); // } // // public static final void error(String tag, String message, Object... args) { // print(Level.ERROR, tag, message, args); // } // // public static final void error(String tag, String message, Exception ex) { // print(Level.ERROR, tag, message); // ex.printStackTrace(getStream()); // } // // public static final void error(String tag, String message, Exception ex, Object... args) { // print(Level.ERROR, tag, message, args); // ex.printStackTrace(getStream()); // } // // // private static final void print(Level level, String tag, String message) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(message); // getStream().println(builder.toString()); // } // // // private static final void print(Level level, String tag, String message, Object... args) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(format(message, args)); // getStream().println(builder.toString()); // } // // private static final StringBuilder getBuilderWithDate(Level level, String tag) { // StringBuilder builder = new StringBuilder(); // Calendar now = Calendar.getInstance(); // builder.append('['); // builder.append(now.get(Calendar.YEAR)); // builder.append('-'); // builder.append(now.get(Calendar.MONTH)); // builder.append('-'); // builder.append(now.get(Calendar.DAY_OF_MONTH)); // builder.append(' '); // builder.append(now.get(Calendar.HOUR_OF_DAY)); // builder.append(':'); // builder.append(now.get(Calendar.MINUTE)); // builder.append(':'); // builder.append(now.get(Calendar.SECOND)); // builder.append(','); // builder.append(now.get(Calendar.MILLISECOND)); // builder.append("]\t"); // builder.append(level.name()); // builder.append(" \t"); // builder.append(tag); // builder.append(": \t"); // return builder; // } // // public static PrintStream getStream() { // return stream; // } // // public static void setStream(PrintStream stream) { // Logger.stream = stream; // } // // public enum Level { // TRACE, // DEBUG, // INFO, // WARNING, // ERROR // } // } // Path: heartbeat-network/src/main/java/com/heartbeat/network/udp/UDPOperations.java import com.heartbeat.common.array.ByteArray; import com.heartbeat.log.Logger; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import static java.lang.String.format; package com.heartbeat.network.udp; /** * A static helper class for basic common UDP operations. */ public final class UDPOperations { private static final String TAG = UDPOperations.class.getName(); private UDPOperations() { } /** * Sends a UDP datagram to the receiver * * @param socket local socket * @param receiverIP receiver IP address * @param receiverPort receiver port * @param data data to send * @throws IOException */ public static final void send(DatagramSocket socket, InetAddress receiverIP, int receiverPort, byte[] data) throws IOException { DatagramPacket sendPacket = new DatagramPacket(data, data.length, receiverIP, receiverPort); socket.send(sendPacket);
Logger.info(TAG, format("%s[%d]\tPacket sent\tlength: %d", receiverIP.getHostAddress(), receiverPort, data.length));
serayuzgur/heartbeat
heartbeat-pin/src/test/java/com/heartbeat/pin/TestPinCommand.java
// Path: heartbeat-pin/src/main/java/com/heartbeat/pin/command/PinCommand.java // public interface PinCommand { // // /** // * Gets the mode of given pin from system. // * // * @param pin // */ // Pin.Mode getMode(Pin pin) throws PinCommandException; // // /** // * Gets the mode and the pin instance and sets to the system. // * // * @param pin // */ // void setMode(Pin pin, Pin.Mode mode) throws PinCommandException; // // /** // * Enables the given pin from system. // * // * @param pin // */ // void enable(Pin pin) throws PinCommandException; // // /** // * Disable the given pin from system. // * // * @param pin // */ // void disable(Pin pin) throws PinCommandException; // // /** // * Reads the given film from system. // * // * @param pin // * @return // */ // boolean read(Pin pin) throws PinCommandException; // // /** // * Writes the given pins value from the system. // * // * @param pin // * @param value // * @return // */ // void write(Pin pin, boolean value) throws PinCommandException; // // // /** // * Returns the path of the pin. // * // * @param pin // * @return // */ // File path(Pin pin); // } // // Path: heartbeat-pin/src/main/java/com/heartbeat/pin/command/PinCommandException.java // public class PinCommandException extends PinException { // // public PinCommandException(String message) { // super(message); // } // // public PinCommandException() { // } // // public PinCommandException(String message, Throwable cause) { // super(message, cause); // } // // public PinCommandException(Throwable cause) { // super(cause); // } // // public PinCommandException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // }
import com.heartbeat.pin.command.PinCommand; import com.heartbeat.pin.command.PinCommandException; import java.io.File;
package com.heartbeat.pin; public abstract class TestPinCommand implements PinCommand { @Override
// Path: heartbeat-pin/src/main/java/com/heartbeat/pin/command/PinCommand.java // public interface PinCommand { // // /** // * Gets the mode of given pin from system. // * // * @param pin // */ // Pin.Mode getMode(Pin pin) throws PinCommandException; // // /** // * Gets the mode and the pin instance and sets to the system. // * // * @param pin // */ // void setMode(Pin pin, Pin.Mode mode) throws PinCommandException; // // /** // * Enables the given pin from system. // * // * @param pin // */ // void enable(Pin pin) throws PinCommandException; // // /** // * Disable the given pin from system. // * // * @param pin // */ // void disable(Pin pin) throws PinCommandException; // // /** // * Reads the given film from system. // * // * @param pin // * @return // */ // boolean read(Pin pin) throws PinCommandException; // // /** // * Writes the given pins value from the system. // * // * @param pin // * @param value // * @return // */ // void write(Pin pin, boolean value) throws PinCommandException; // // // /** // * Returns the path of the pin. // * // * @param pin // * @return // */ // File path(Pin pin); // } // // Path: heartbeat-pin/src/main/java/com/heartbeat/pin/command/PinCommandException.java // public class PinCommandException extends PinException { // // public PinCommandException(String message) { // super(message); // } // // public PinCommandException() { // } // // public PinCommandException(String message, Throwable cause) { // super(message, cause); // } // // public PinCommandException(Throwable cause) { // super(cause); // } // // public PinCommandException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: heartbeat-pin/src/test/java/com/heartbeat/pin/TestPinCommand.java import com.heartbeat.pin.command.PinCommand; import com.heartbeat.pin.command.PinCommandException; import java.io.File; package com.heartbeat.pin; public abstract class TestPinCommand implements PinCommand { @Override
public void setMode(Pin pin, Pin.Mode mode) throws PinCommandException {
serayuzgur/heartbeat
heartbeat-pin/src/main/java/com/heartbeat/pin/PinReader.java
// Path: heartbeat-log/src/main/java/com/heartbeat/log/Logger.java // public final class Logger { // private static Level defaultPackageLevel = Level.INFO; // private static PrintStream stream = System.out; // //TODO: Appender system // //TODO: Tag-level checks. // // private Logger() { // } // // public static Level getLevel() { // return defaultPackageLevel; // } // // public static void setLevel(Level defaultPackageLevel) { // Logger.defaultPackageLevel = defaultPackageLevel; // } // // public static final void trace(String tag, String message) { // print(Level.TRACE, tag, message); // // } // // public static final void trace(String tag, String message, Object... args) { // print(Level.TRACE, tag, message, args); // // } // // public static final void debug(String tag, String message) { // print(Level.DEBUG, tag, message); // // } // // public static final void debug(String tag, String message, Object... args) { // print(Level.DEBUG, tag, message, args); // // } // // public static final void info(String tag, String message) { // print(Level.INFO, tag, message); // // } // // public static final void info(String tag, String message, Object... args) { // print(Level.INFO, tag, message, args); // } // // public static final void warn(String tag, String message) { // print(Level.WARNING, tag, message); // } // // public static final void warn(String tag, String message, Object... args) { // print(Level.WARNING, tag, message, args); // } // // public static final void error(String tag, String message) { // print(Level.ERROR, tag, message); // } // // public static final void error(String tag, String message, Object... args) { // print(Level.ERROR, tag, message, args); // } // // public static final void error(String tag, String message, Exception ex) { // print(Level.ERROR, tag, message); // ex.printStackTrace(getStream()); // } // // public static final void error(String tag, String message, Exception ex, Object... args) { // print(Level.ERROR, tag, message, args); // ex.printStackTrace(getStream()); // } // // // private static final void print(Level level, String tag, String message) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(message); // getStream().println(builder.toString()); // } // // // private static final void print(Level level, String tag, String message, Object... args) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(format(message, args)); // getStream().println(builder.toString()); // } // // private static final StringBuilder getBuilderWithDate(Level level, String tag) { // StringBuilder builder = new StringBuilder(); // Calendar now = Calendar.getInstance(); // builder.append('['); // builder.append(now.get(Calendar.YEAR)); // builder.append('-'); // builder.append(now.get(Calendar.MONTH)); // builder.append('-'); // builder.append(now.get(Calendar.DAY_OF_MONTH)); // builder.append(' '); // builder.append(now.get(Calendar.HOUR_OF_DAY)); // builder.append(':'); // builder.append(now.get(Calendar.MINUTE)); // builder.append(':'); // builder.append(now.get(Calendar.SECOND)); // builder.append(','); // builder.append(now.get(Calendar.MILLISECOND)); // builder.append("]\t"); // builder.append(level.name()); // builder.append(" \t"); // builder.append(tag); // builder.append(": \t"); // return builder; // } // // public static PrintStream getStream() { // return stream; // } // // public static void setStream(PrintStream stream) { // Logger.stream = stream; // } // // public enum Level { // TRACE, // DEBUG, // INFO, // WARNING, // ERROR // } // }
import com.heartbeat.log.Logger; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel;
package com.heartbeat.pin; /** * A high performance reader class which opens a {@link FileChannel} to the pin. * It uses {@link ByteBuffer} with the size 1 and reuses it for every read. * Also reads the value and converts to boolean. */ public class PinReader { private static final String TAG = PinReader.class.getName(); private final Pin pin; private ByteBuffer VALUE = ByteBuffer.wrap("0".getBytes()); private final FileChannel fch; /** * Creates a Reader with {@link FileChannel} for the pin. * * @param pin * @throws IOException */ public PinReader(Pin pin) throws IOException { this.pin = pin; fch = FileChannel.open(pin.getPath().toPath()); } /** * Reads the pin and converts its value to boolean * If value of pin is "1" returns true if it is "0" returns false. * * @return * @throws IOException */ public boolean read() throws IOException { VALUE.position(0); fch.read(VALUE); fch.position(0); return VALUE.get(0) == '1'; } /** * Closes reader , releases file channel. */ public void close() { if (fch != null && fch.isOpen()) { try { fch.close(); } catch (IOException e) {
// Path: heartbeat-log/src/main/java/com/heartbeat/log/Logger.java // public final class Logger { // private static Level defaultPackageLevel = Level.INFO; // private static PrintStream stream = System.out; // //TODO: Appender system // //TODO: Tag-level checks. // // private Logger() { // } // // public static Level getLevel() { // return defaultPackageLevel; // } // // public static void setLevel(Level defaultPackageLevel) { // Logger.defaultPackageLevel = defaultPackageLevel; // } // // public static final void trace(String tag, String message) { // print(Level.TRACE, tag, message); // // } // // public static final void trace(String tag, String message, Object... args) { // print(Level.TRACE, tag, message, args); // // } // // public static final void debug(String tag, String message) { // print(Level.DEBUG, tag, message); // // } // // public static final void debug(String tag, String message, Object... args) { // print(Level.DEBUG, tag, message, args); // // } // // public static final void info(String tag, String message) { // print(Level.INFO, tag, message); // // } // // public static final void info(String tag, String message, Object... args) { // print(Level.INFO, tag, message, args); // } // // public static final void warn(String tag, String message) { // print(Level.WARNING, tag, message); // } // // public static final void warn(String tag, String message, Object... args) { // print(Level.WARNING, tag, message, args); // } // // public static final void error(String tag, String message) { // print(Level.ERROR, tag, message); // } // // public static final void error(String tag, String message, Object... args) { // print(Level.ERROR, tag, message, args); // } // // public static final void error(String tag, String message, Exception ex) { // print(Level.ERROR, tag, message); // ex.printStackTrace(getStream()); // } // // public static final void error(String tag, String message, Exception ex, Object... args) { // print(Level.ERROR, tag, message, args); // ex.printStackTrace(getStream()); // } // // // private static final void print(Level level, String tag, String message) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(message); // getStream().println(builder.toString()); // } // // // private static final void print(Level level, String tag, String message, Object... args) { // if (level.ordinal() < defaultPackageLevel.ordinal()) // return; // StringBuilder builder = getBuilderWithDate(level, tag); // builder.append(format(message, args)); // getStream().println(builder.toString()); // } // // private static final StringBuilder getBuilderWithDate(Level level, String tag) { // StringBuilder builder = new StringBuilder(); // Calendar now = Calendar.getInstance(); // builder.append('['); // builder.append(now.get(Calendar.YEAR)); // builder.append('-'); // builder.append(now.get(Calendar.MONTH)); // builder.append('-'); // builder.append(now.get(Calendar.DAY_OF_MONTH)); // builder.append(' '); // builder.append(now.get(Calendar.HOUR_OF_DAY)); // builder.append(':'); // builder.append(now.get(Calendar.MINUTE)); // builder.append(':'); // builder.append(now.get(Calendar.SECOND)); // builder.append(','); // builder.append(now.get(Calendar.MILLISECOND)); // builder.append("]\t"); // builder.append(level.name()); // builder.append(" \t"); // builder.append(tag); // builder.append(": \t"); // return builder; // } // // public static PrintStream getStream() { // return stream; // } // // public static void setStream(PrintStream stream) { // Logger.stream = stream; // } // // public enum Level { // TRACE, // DEBUG, // INFO, // WARNING, // ERROR // } // } // Path: heartbeat-pin/src/main/java/com/heartbeat/pin/PinReader.java import com.heartbeat.log.Logger; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; package com.heartbeat.pin; /** * A high performance reader class which opens a {@link FileChannel} to the pin. * It uses {@link ByteBuffer} with the size 1 and reuses it for every read. * Also reads the value and converts to boolean. */ public class PinReader { private static final String TAG = PinReader.class.getName(); private final Pin pin; private ByteBuffer VALUE = ByteBuffer.wrap("0".getBytes()); private final FileChannel fch; /** * Creates a Reader with {@link FileChannel} for the pin. * * @param pin * @throws IOException */ public PinReader(Pin pin) throws IOException { this.pin = pin; fch = FileChannel.open(pin.getPath().toPath()); } /** * Reads the pin and converts its value to boolean * If value of pin is "1" returns true if it is "0" returns false. * * @return * @throws IOException */ public boolean read() throws IOException { VALUE.position(0); fch.read(VALUE); fch.position(0); return VALUE.get(0) == '1'; } /** * Closes reader , releases file channel. */ public void close() { if (fch != null && fch.isOpen()) { try { fch.close(); } catch (IOException e) {
Logger.error(TAG, "Can not close Reader %s", e, pin.getCode());
serayuzgur/heartbeat
heartbeat-pin/src/test/java/com/heartbeat/pin/PinTest.java
// Path: heartbeat-common/src/main/java/com/heartbeat/common/board/OperatingSystem.java // public final class OperatingSystem { // private OperatingSystem() { // } // // private static Type os; // // /** // * Detect the operating system from the os.name System property // * // * @returns - the operating system // */ // public static Type getType() { // return getType(false); // } // // /** // * Detect the operating system from the os.name System property // * // * @returns - the operating system // */ // public static Type getType(boolean force) { // if (force || os == null) { // String osName = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); // if (osName.contains("nux")) { // OperatingSystem.os = Type.LINUX; // } else if (osName.contains("win")) { // OperatingSystem.os = Type.WINDOWS; // } else if (osName.contains("mac")) { // OperatingSystem.os = Type.MAC_OS; // } else { // OperatingSystem.os = Type.OTHER; // } // } // return os; // } // // // /** // * Types of Operating Systems and some default values. // */ // public enum Type { // WINDOWS(new String[]{"cmd.exe", "/c"}), // MAC_OS(new String[]{"bash", "-c"}), // LINUX(new String[]{"bash", "-c"}), // OTHER(new String[]{"bash", "-c"}); // hope they are linux :D // // private final String[] cmdPrefix; // // Type(String[] cmdPrefix) { // this.cmdPrefix = cmdPrefix; // } // // /** // * returns the pre commands of the OS command line // * // * @return // */ // public String[] getCmdPrefix() { // return Arrays.copyOf(cmdPrefix, 2); // } // } // } // // Path: heartbeat-pin/src/main/java/com/heartbeat/pin/command/PinCommandException.java // public class PinCommandException extends PinException { // // public PinCommandException(String message) { // super(message); // } // // public PinCommandException() { // } // // public PinCommandException(String message, Throwable cause) { // super(message, cause); // } // // public PinCommandException(Throwable cause) { // super(cause); // } // // public PinCommandException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // }
import com.heartbeat.common.board.OperatingSystem; import com.heartbeat.pin.command.PinCommandException; import org.junit.Test; import java.io.File;
package com.heartbeat.pin; public class PinTest { @Test public void testSettersGetters() throws Exception { Pin a = new Pin("P1", new File("/sys/class/gpio/gpio/P1/value"), Pin.Mode.IN, new TestPinCommand() { @Override
// Path: heartbeat-common/src/main/java/com/heartbeat/common/board/OperatingSystem.java // public final class OperatingSystem { // private OperatingSystem() { // } // // private static Type os; // // /** // * Detect the operating system from the os.name System property // * // * @returns - the operating system // */ // public static Type getType() { // return getType(false); // } // // /** // * Detect the operating system from the os.name System property // * // * @returns - the operating system // */ // public static Type getType(boolean force) { // if (force || os == null) { // String osName = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); // if (osName.contains("nux")) { // OperatingSystem.os = Type.LINUX; // } else if (osName.contains("win")) { // OperatingSystem.os = Type.WINDOWS; // } else if (osName.contains("mac")) { // OperatingSystem.os = Type.MAC_OS; // } else { // OperatingSystem.os = Type.OTHER; // } // } // return os; // } // // // /** // * Types of Operating Systems and some default values. // */ // public enum Type { // WINDOWS(new String[]{"cmd.exe", "/c"}), // MAC_OS(new String[]{"bash", "-c"}), // LINUX(new String[]{"bash", "-c"}), // OTHER(new String[]{"bash", "-c"}); // hope they are linux :D // // private final String[] cmdPrefix; // // Type(String[] cmdPrefix) { // this.cmdPrefix = cmdPrefix; // } // // /** // * returns the pre commands of the OS command line // * // * @return // */ // public String[] getCmdPrefix() { // return Arrays.copyOf(cmdPrefix, 2); // } // } // } // // Path: heartbeat-pin/src/main/java/com/heartbeat/pin/command/PinCommandException.java // public class PinCommandException extends PinException { // // public PinCommandException(String message) { // super(message); // } // // public PinCommandException() { // } // // public PinCommandException(String message, Throwable cause) { // super(message, cause); // } // // public PinCommandException(Throwable cause) { // super(cause); // } // // public PinCommandException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: heartbeat-pin/src/test/java/com/heartbeat/pin/PinTest.java import com.heartbeat.common.board.OperatingSystem; import com.heartbeat.pin.command.PinCommandException; import org.junit.Test; import java.io.File; package com.heartbeat.pin; public class PinTest { @Test public void testSettersGetters() throws Exception { Pin a = new Pin("P1", new File("/sys/class/gpio/gpio/P1/value"), Pin.Mode.IN, new TestPinCommand() { @Override
public Pin.Mode getMode(Pin pin) throws PinCommandException {
serayuzgur/heartbeat
heartbeat-pin/src/test/java/com/heartbeat/pin/PinTest.java
// Path: heartbeat-common/src/main/java/com/heartbeat/common/board/OperatingSystem.java // public final class OperatingSystem { // private OperatingSystem() { // } // // private static Type os; // // /** // * Detect the operating system from the os.name System property // * // * @returns - the operating system // */ // public static Type getType() { // return getType(false); // } // // /** // * Detect the operating system from the os.name System property // * // * @returns - the operating system // */ // public static Type getType(boolean force) { // if (force || os == null) { // String osName = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); // if (osName.contains("nux")) { // OperatingSystem.os = Type.LINUX; // } else if (osName.contains("win")) { // OperatingSystem.os = Type.WINDOWS; // } else if (osName.contains("mac")) { // OperatingSystem.os = Type.MAC_OS; // } else { // OperatingSystem.os = Type.OTHER; // } // } // return os; // } // // // /** // * Types of Operating Systems and some default values. // */ // public enum Type { // WINDOWS(new String[]{"cmd.exe", "/c"}), // MAC_OS(new String[]{"bash", "-c"}), // LINUX(new String[]{"bash", "-c"}), // OTHER(new String[]{"bash", "-c"}); // hope they are linux :D // // private final String[] cmdPrefix; // // Type(String[] cmdPrefix) { // this.cmdPrefix = cmdPrefix; // } // // /** // * returns the pre commands of the OS command line // * // * @return // */ // public String[] getCmdPrefix() { // return Arrays.copyOf(cmdPrefix, 2); // } // } // } // // Path: heartbeat-pin/src/main/java/com/heartbeat/pin/command/PinCommandException.java // public class PinCommandException extends PinException { // // public PinCommandException(String message) { // super(message); // } // // public PinCommandException() { // } // // public PinCommandException(String message, Throwable cause) { // super(message, cause); // } // // public PinCommandException(Throwable cause) { // super(cause); // } // // public PinCommandException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // }
import com.heartbeat.common.board.OperatingSystem; import com.heartbeat.pin.command.PinCommandException; import org.junit.Test; import java.io.File;
}); Pin b = new Pin("P1", new File("/sys/class/gpio/gpio/P1/value"), Pin.Mode.IN, new TestPinCommand() { @Override public Pin.Mode getMode(Pin pin) throws PinCommandException { return Pin.Mode.IN; } @Override public boolean read(Pin pin) throws PinCommandException { return true; } }); assert a.hashCode() == b.hashCode(); } @Test public void testToString() throws Exception { Pin a = new Pin("P1", new TestPinCommand() { @Override public Pin.Mode getMode(Pin pin) throws PinCommandException { return Pin.Mode.IN; } @Override public boolean read(Pin pin) throws PinCommandException { return true; } }); String expectedStr = "Pin{code='P1', path=/sample/P1, mode=IN, enabled=true}";
// Path: heartbeat-common/src/main/java/com/heartbeat/common/board/OperatingSystem.java // public final class OperatingSystem { // private OperatingSystem() { // } // // private static Type os; // // /** // * Detect the operating system from the os.name System property // * // * @returns - the operating system // */ // public static Type getType() { // return getType(false); // } // // /** // * Detect the operating system from the os.name System property // * // * @returns - the operating system // */ // public static Type getType(boolean force) { // if (force || os == null) { // String osName = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); // if (osName.contains("nux")) { // OperatingSystem.os = Type.LINUX; // } else if (osName.contains("win")) { // OperatingSystem.os = Type.WINDOWS; // } else if (osName.contains("mac")) { // OperatingSystem.os = Type.MAC_OS; // } else { // OperatingSystem.os = Type.OTHER; // } // } // return os; // } // // // /** // * Types of Operating Systems and some default values. // */ // public enum Type { // WINDOWS(new String[]{"cmd.exe", "/c"}), // MAC_OS(new String[]{"bash", "-c"}), // LINUX(new String[]{"bash", "-c"}), // OTHER(new String[]{"bash", "-c"}); // hope they are linux :D // // private final String[] cmdPrefix; // // Type(String[] cmdPrefix) { // this.cmdPrefix = cmdPrefix; // } // // /** // * returns the pre commands of the OS command line // * // * @return // */ // public String[] getCmdPrefix() { // return Arrays.copyOf(cmdPrefix, 2); // } // } // } // // Path: heartbeat-pin/src/main/java/com/heartbeat/pin/command/PinCommandException.java // public class PinCommandException extends PinException { // // public PinCommandException(String message) { // super(message); // } // // public PinCommandException() { // } // // public PinCommandException(String message, Throwable cause) { // super(message, cause); // } // // public PinCommandException(Throwable cause) { // super(cause); // } // // public PinCommandException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: heartbeat-pin/src/test/java/com/heartbeat/pin/PinTest.java import com.heartbeat.common.board.OperatingSystem; import com.heartbeat.pin.command.PinCommandException; import org.junit.Test; import java.io.File; }); Pin b = new Pin("P1", new File("/sys/class/gpio/gpio/P1/value"), Pin.Mode.IN, new TestPinCommand() { @Override public Pin.Mode getMode(Pin pin) throws PinCommandException { return Pin.Mode.IN; } @Override public boolean read(Pin pin) throws PinCommandException { return true; } }); assert a.hashCode() == b.hashCode(); } @Test public void testToString() throws Exception { Pin a = new Pin("P1", new TestPinCommand() { @Override public Pin.Mode getMode(Pin pin) throws PinCommandException { return Pin.Mode.IN; } @Override public boolean read(Pin pin) throws PinCommandException { return true; } }); String expectedStr = "Pin{code='P1', path=/sample/P1, mode=IN, enabled=true}";
if (OperatingSystem.getType() == OperatingSystem.Type.WINDOWS) {
in28minutes/MockitoTutorialForBeginners
src/test/java/com/clarity/business/ClientBOTest.java
// Path: src/main/java/com/in28minutes/junit/business/ClientBO.java // public interface ClientBO { // // Amount getClientProductsSum(List<Product> products) // throws DifferentCurrenciesException; // // } // // Path: src/main/java/com/in28minutes/junit/business/ClientBOImpl.java // public class ClientBOImpl implements ClientBO { // // public Amount getClientProductsSum(List<Product> products) // throws DifferentCurrenciesException { // // if (products.size() == 0) // return new AmountImpl(BigDecimal.ZERO, Currency.EURO); // // if (!isCurrencySameForAllProducts(products)) { // throw new DifferentCurrenciesException(); // } // // BigDecimal productSum = calculateProductSum(products); // // Currency firstProductCurrency = products.get(0).getAmount() // .getCurrency(); // // return new AmountImpl(productSum, firstProductCurrency); // } // // private BigDecimal calculateProductSum(List<Product> products) { // BigDecimal sum = BigDecimal.ZERO; // // Calculate Sum of Products // for (Product product : products) { // sum = sum.add(product.getAmount().getValue()); // } // return sum; // } // // private boolean isCurrencySameForAllProducts(List<Product> products) // throws DifferentCurrenciesException { // // Currency firstProductCurrency = products.get(0).getAmount() // .getCurrency(); // // for (Product product : products) { // boolean currencySameAsFirstProduct = product.getAmount() // .getCurrency().equals(firstProductCurrency); // if (!currencySameAsFirstProduct) { // return false; // } // } // // return true; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Amount.java // public interface Amount { // BigDecimal getValue(); // // Currency getCurrency(); // } // // Path: src/main/java/com/in28minutes/junit/model/Currency.java // public enum Currency { // // EURO("EUR"), UNITED_STATES_DOLLAR("USD"), INDIAN_RUPEE("INR"); // // private final String textValue; // // Currency(final String textValue) { // this.textValue = textValue; // } // // @Override // public String toString() { // return textValue; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Product.java // public interface Product { // // long getId(); // // String getName(); // // ProductType getType(); // // Amount getAmount(); // } // // Path: src/main/java/com/in28minutes/junit/model/ProductImpl.java // public class ProductImpl implements Product { // // private long id; // // private String name; // // private ProductType type; // // private Amount amount; // // public ProductImpl(long id, String name, ProductType type, Amount amount) { // super(); // this.id = id; // this.name = name; // this.type = type; // this.amount = amount; // } // // @Override // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // @Override // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public ProductType getType() { // return type; // } // // public void setType(ProductType type) { // this.type = type; // } // // @Override // public Amount getAmount() { // return amount; // } // // public void setAmount(Amount amount) { // this.amount = amount; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.in28minutes.junit.business.ClientBO; import com.in28minutes.junit.business.ClientBOImpl; import com.in28minutes.junit.business.exception.DifferentCurrenciesException; import com.in28minutes.junit.model.Amount; import com.in28minutes.junit.model.AmountImpl; import com.in28minutes.junit.model.Currency; import com.in28minutes.junit.model.Product; import com.in28minutes.junit.model.ProductImpl; import com.in28minutes.junit.model.ProductType;
package com.clarity.business; public class ClientBOTest { private ClientBO clientBO = new ClientBOImpl(); @Test public void testClientProductSum() throws DifferentCurrenciesException {
// Path: src/main/java/com/in28minutes/junit/business/ClientBO.java // public interface ClientBO { // // Amount getClientProductsSum(List<Product> products) // throws DifferentCurrenciesException; // // } // // Path: src/main/java/com/in28minutes/junit/business/ClientBOImpl.java // public class ClientBOImpl implements ClientBO { // // public Amount getClientProductsSum(List<Product> products) // throws DifferentCurrenciesException { // // if (products.size() == 0) // return new AmountImpl(BigDecimal.ZERO, Currency.EURO); // // if (!isCurrencySameForAllProducts(products)) { // throw new DifferentCurrenciesException(); // } // // BigDecimal productSum = calculateProductSum(products); // // Currency firstProductCurrency = products.get(0).getAmount() // .getCurrency(); // // return new AmountImpl(productSum, firstProductCurrency); // } // // private BigDecimal calculateProductSum(List<Product> products) { // BigDecimal sum = BigDecimal.ZERO; // // Calculate Sum of Products // for (Product product : products) { // sum = sum.add(product.getAmount().getValue()); // } // return sum; // } // // private boolean isCurrencySameForAllProducts(List<Product> products) // throws DifferentCurrenciesException { // // Currency firstProductCurrency = products.get(0).getAmount() // .getCurrency(); // // for (Product product : products) { // boolean currencySameAsFirstProduct = product.getAmount() // .getCurrency().equals(firstProductCurrency); // if (!currencySameAsFirstProduct) { // return false; // } // } // // return true; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Amount.java // public interface Amount { // BigDecimal getValue(); // // Currency getCurrency(); // } // // Path: src/main/java/com/in28minutes/junit/model/Currency.java // public enum Currency { // // EURO("EUR"), UNITED_STATES_DOLLAR("USD"), INDIAN_RUPEE("INR"); // // private final String textValue; // // Currency(final String textValue) { // this.textValue = textValue; // } // // @Override // public String toString() { // return textValue; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Product.java // public interface Product { // // long getId(); // // String getName(); // // ProductType getType(); // // Amount getAmount(); // } // // Path: src/main/java/com/in28minutes/junit/model/ProductImpl.java // public class ProductImpl implements Product { // // private long id; // // private String name; // // private ProductType type; // // private Amount amount; // // public ProductImpl(long id, String name, ProductType type, Amount amount) { // super(); // this.id = id; // this.name = name; // this.type = type; // this.amount = amount; // } // // @Override // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // @Override // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public ProductType getType() { // return type; // } // // public void setType(ProductType type) { // this.type = type; // } // // @Override // public Amount getAmount() { // return amount; // } // // public void setAmount(Amount amount) { // this.amount = amount; // } // } // Path: src/test/java/com/clarity/business/ClientBOTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.in28minutes.junit.business.ClientBO; import com.in28minutes.junit.business.ClientBOImpl; import com.in28minutes.junit.business.exception.DifferentCurrenciesException; import com.in28minutes.junit.model.Amount; import com.in28minutes.junit.model.AmountImpl; import com.in28minutes.junit.model.Currency; import com.in28minutes.junit.model.Product; import com.in28minutes.junit.model.ProductImpl; import com.in28minutes.junit.model.ProductType; package com.clarity.business; public class ClientBOTest { private ClientBO clientBO = new ClientBOImpl(); @Test public void testClientProductSum() throws DifferentCurrenciesException {
List<Product> products = new ArrayList<Product>();
in28minutes/MockitoTutorialForBeginners
src/test/java/com/clarity/business/ClientBOTest.java
// Path: src/main/java/com/in28minutes/junit/business/ClientBO.java // public interface ClientBO { // // Amount getClientProductsSum(List<Product> products) // throws DifferentCurrenciesException; // // } // // Path: src/main/java/com/in28minutes/junit/business/ClientBOImpl.java // public class ClientBOImpl implements ClientBO { // // public Amount getClientProductsSum(List<Product> products) // throws DifferentCurrenciesException { // // if (products.size() == 0) // return new AmountImpl(BigDecimal.ZERO, Currency.EURO); // // if (!isCurrencySameForAllProducts(products)) { // throw new DifferentCurrenciesException(); // } // // BigDecimal productSum = calculateProductSum(products); // // Currency firstProductCurrency = products.get(0).getAmount() // .getCurrency(); // // return new AmountImpl(productSum, firstProductCurrency); // } // // private BigDecimal calculateProductSum(List<Product> products) { // BigDecimal sum = BigDecimal.ZERO; // // Calculate Sum of Products // for (Product product : products) { // sum = sum.add(product.getAmount().getValue()); // } // return sum; // } // // private boolean isCurrencySameForAllProducts(List<Product> products) // throws DifferentCurrenciesException { // // Currency firstProductCurrency = products.get(0).getAmount() // .getCurrency(); // // for (Product product : products) { // boolean currencySameAsFirstProduct = product.getAmount() // .getCurrency().equals(firstProductCurrency); // if (!currencySameAsFirstProduct) { // return false; // } // } // // return true; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Amount.java // public interface Amount { // BigDecimal getValue(); // // Currency getCurrency(); // } // // Path: src/main/java/com/in28minutes/junit/model/Currency.java // public enum Currency { // // EURO("EUR"), UNITED_STATES_DOLLAR("USD"), INDIAN_RUPEE("INR"); // // private final String textValue; // // Currency(final String textValue) { // this.textValue = textValue; // } // // @Override // public String toString() { // return textValue; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Product.java // public interface Product { // // long getId(); // // String getName(); // // ProductType getType(); // // Amount getAmount(); // } // // Path: src/main/java/com/in28minutes/junit/model/ProductImpl.java // public class ProductImpl implements Product { // // private long id; // // private String name; // // private ProductType type; // // private Amount amount; // // public ProductImpl(long id, String name, ProductType type, Amount amount) { // super(); // this.id = id; // this.name = name; // this.type = type; // this.amount = amount; // } // // @Override // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // @Override // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public ProductType getType() { // return type; // } // // public void setType(ProductType type) { // this.type = type; // } // // @Override // public Amount getAmount() { // return amount; // } // // public void setAmount(Amount amount) { // this.amount = amount; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.in28minutes.junit.business.ClientBO; import com.in28minutes.junit.business.ClientBOImpl; import com.in28minutes.junit.business.exception.DifferentCurrenciesException; import com.in28minutes.junit.model.Amount; import com.in28minutes.junit.model.AmountImpl; import com.in28minutes.junit.model.Currency; import com.in28minutes.junit.model.Product; import com.in28minutes.junit.model.ProductImpl; import com.in28minutes.junit.model.ProductType;
package com.clarity.business; public class ClientBOTest { private ClientBO clientBO = new ClientBOImpl(); @Test public void testClientProductSum() throws DifferentCurrenciesException { List<Product> products = new ArrayList<Product>();
// Path: src/main/java/com/in28minutes/junit/business/ClientBO.java // public interface ClientBO { // // Amount getClientProductsSum(List<Product> products) // throws DifferentCurrenciesException; // // } // // Path: src/main/java/com/in28minutes/junit/business/ClientBOImpl.java // public class ClientBOImpl implements ClientBO { // // public Amount getClientProductsSum(List<Product> products) // throws DifferentCurrenciesException { // // if (products.size() == 0) // return new AmountImpl(BigDecimal.ZERO, Currency.EURO); // // if (!isCurrencySameForAllProducts(products)) { // throw new DifferentCurrenciesException(); // } // // BigDecimal productSum = calculateProductSum(products); // // Currency firstProductCurrency = products.get(0).getAmount() // .getCurrency(); // // return new AmountImpl(productSum, firstProductCurrency); // } // // private BigDecimal calculateProductSum(List<Product> products) { // BigDecimal sum = BigDecimal.ZERO; // // Calculate Sum of Products // for (Product product : products) { // sum = sum.add(product.getAmount().getValue()); // } // return sum; // } // // private boolean isCurrencySameForAllProducts(List<Product> products) // throws DifferentCurrenciesException { // // Currency firstProductCurrency = products.get(0).getAmount() // .getCurrency(); // // for (Product product : products) { // boolean currencySameAsFirstProduct = product.getAmount() // .getCurrency().equals(firstProductCurrency); // if (!currencySameAsFirstProduct) { // return false; // } // } // // return true; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Amount.java // public interface Amount { // BigDecimal getValue(); // // Currency getCurrency(); // } // // Path: src/main/java/com/in28minutes/junit/model/Currency.java // public enum Currency { // // EURO("EUR"), UNITED_STATES_DOLLAR("USD"), INDIAN_RUPEE("INR"); // // private final String textValue; // // Currency(final String textValue) { // this.textValue = textValue; // } // // @Override // public String toString() { // return textValue; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Product.java // public interface Product { // // long getId(); // // String getName(); // // ProductType getType(); // // Amount getAmount(); // } // // Path: src/main/java/com/in28minutes/junit/model/ProductImpl.java // public class ProductImpl implements Product { // // private long id; // // private String name; // // private ProductType type; // // private Amount amount; // // public ProductImpl(long id, String name, ProductType type, Amount amount) { // super(); // this.id = id; // this.name = name; // this.type = type; // this.amount = amount; // } // // @Override // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // @Override // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public ProductType getType() { // return type; // } // // public void setType(ProductType type) { // this.type = type; // } // // @Override // public Amount getAmount() { // return amount; // } // // public void setAmount(Amount amount) { // this.amount = amount; // } // } // Path: src/test/java/com/clarity/business/ClientBOTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.in28minutes.junit.business.ClientBO; import com.in28minutes.junit.business.ClientBOImpl; import com.in28minutes.junit.business.exception.DifferentCurrenciesException; import com.in28minutes.junit.model.Amount; import com.in28minutes.junit.model.AmountImpl; import com.in28minutes.junit.model.Currency; import com.in28minutes.junit.model.Product; import com.in28minutes.junit.model.ProductImpl; import com.in28minutes.junit.model.ProductType; package com.clarity.business; public class ClientBOTest { private ClientBO clientBO = new ClientBOImpl(); @Test public void testClientProductSum() throws DifferentCurrenciesException { List<Product> products = new ArrayList<Product>();
products.add(new ProductImpl(100, "Product 15",
in28minutes/MockitoTutorialForBeginners
src/test/java/com/clarity/business/ClientBOTest.java
// Path: src/main/java/com/in28minutes/junit/business/ClientBO.java // public interface ClientBO { // // Amount getClientProductsSum(List<Product> products) // throws DifferentCurrenciesException; // // } // // Path: src/main/java/com/in28minutes/junit/business/ClientBOImpl.java // public class ClientBOImpl implements ClientBO { // // public Amount getClientProductsSum(List<Product> products) // throws DifferentCurrenciesException { // // if (products.size() == 0) // return new AmountImpl(BigDecimal.ZERO, Currency.EURO); // // if (!isCurrencySameForAllProducts(products)) { // throw new DifferentCurrenciesException(); // } // // BigDecimal productSum = calculateProductSum(products); // // Currency firstProductCurrency = products.get(0).getAmount() // .getCurrency(); // // return new AmountImpl(productSum, firstProductCurrency); // } // // private BigDecimal calculateProductSum(List<Product> products) { // BigDecimal sum = BigDecimal.ZERO; // // Calculate Sum of Products // for (Product product : products) { // sum = sum.add(product.getAmount().getValue()); // } // return sum; // } // // private boolean isCurrencySameForAllProducts(List<Product> products) // throws DifferentCurrenciesException { // // Currency firstProductCurrency = products.get(0).getAmount() // .getCurrency(); // // for (Product product : products) { // boolean currencySameAsFirstProduct = product.getAmount() // .getCurrency().equals(firstProductCurrency); // if (!currencySameAsFirstProduct) { // return false; // } // } // // return true; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Amount.java // public interface Amount { // BigDecimal getValue(); // // Currency getCurrency(); // } // // Path: src/main/java/com/in28minutes/junit/model/Currency.java // public enum Currency { // // EURO("EUR"), UNITED_STATES_DOLLAR("USD"), INDIAN_RUPEE("INR"); // // private final String textValue; // // Currency(final String textValue) { // this.textValue = textValue; // } // // @Override // public String toString() { // return textValue; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Product.java // public interface Product { // // long getId(); // // String getName(); // // ProductType getType(); // // Amount getAmount(); // } // // Path: src/main/java/com/in28minutes/junit/model/ProductImpl.java // public class ProductImpl implements Product { // // private long id; // // private String name; // // private ProductType type; // // private Amount amount; // // public ProductImpl(long id, String name, ProductType type, Amount amount) { // super(); // this.id = id; // this.name = name; // this.type = type; // this.amount = amount; // } // // @Override // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // @Override // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public ProductType getType() { // return type; // } // // public void setType(ProductType type) { // this.type = type; // } // // @Override // public Amount getAmount() { // return amount; // } // // public void setAmount(Amount amount) { // this.amount = amount; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.in28minutes.junit.business.ClientBO; import com.in28minutes.junit.business.ClientBOImpl; import com.in28minutes.junit.business.exception.DifferentCurrenciesException; import com.in28minutes.junit.model.Amount; import com.in28minutes.junit.model.AmountImpl; import com.in28minutes.junit.model.Currency; import com.in28minutes.junit.model.Product; import com.in28minutes.junit.model.ProductImpl; import com.in28minutes.junit.model.ProductType;
package com.clarity.business; public class ClientBOTest { private ClientBO clientBO = new ClientBOImpl(); @Test public void testClientProductSum() throws DifferentCurrenciesException { List<Product> products = new ArrayList<Product>(); products.add(new ProductImpl(100, "Product 15", ProductType.BANK_GUARANTEE, new AmountImpl(
// Path: src/main/java/com/in28minutes/junit/business/ClientBO.java // public interface ClientBO { // // Amount getClientProductsSum(List<Product> products) // throws DifferentCurrenciesException; // // } // // Path: src/main/java/com/in28minutes/junit/business/ClientBOImpl.java // public class ClientBOImpl implements ClientBO { // // public Amount getClientProductsSum(List<Product> products) // throws DifferentCurrenciesException { // // if (products.size() == 0) // return new AmountImpl(BigDecimal.ZERO, Currency.EURO); // // if (!isCurrencySameForAllProducts(products)) { // throw new DifferentCurrenciesException(); // } // // BigDecimal productSum = calculateProductSum(products); // // Currency firstProductCurrency = products.get(0).getAmount() // .getCurrency(); // // return new AmountImpl(productSum, firstProductCurrency); // } // // private BigDecimal calculateProductSum(List<Product> products) { // BigDecimal sum = BigDecimal.ZERO; // // Calculate Sum of Products // for (Product product : products) { // sum = sum.add(product.getAmount().getValue()); // } // return sum; // } // // private boolean isCurrencySameForAllProducts(List<Product> products) // throws DifferentCurrenciesException { // // Currency firstProductCurrency = products.get(0).getAmount() // .getCurrency(); // // for (Product product : products) { // boolean currencySameAsFirstProduct = product.getAmount() // .getCurrency().equals(firstProductCurrency); // if (!currencySameAsFirstProduct) { // return false; // } // } // // return true; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Amount.java // public interface Amount { // BigDecimal getValue(); // // Currency getCurrency(); // } // // Path: src/main/java/com/in28minutes/junit/model/Currency.java // public enum Currency { // // EURO("EUR"), UNITED_STATES_DOLLAR("USD"), INDIAN_RUPEE("INR"); // // private final String textValue; // // Currency(final String textValue) { // this.textValue = textValue; // } // // @Override // public String toString() { // return textValue; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Product.java // public interface Product { // // long getId(); // // String getName(); // // ProductType getType(); // // Amount getAmount(); // } // // Path: src/main/java/com/in28minutes/junit/model/ProductImpl.java // public class ProductImpl implements Product { // // private long id; // // private String name; // // private ProductType type; // // private Amount amount; // // public ProductImpl(long id, String name, ProductType type, Amount amount) { // super(); // this.id = id; // this.name = name; // this.type = type; // this.amount = amount; // } // // @Override // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // @Override // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public ProductType getType() { // return type; // } // // public void setType(ProductType type) { // this.type = type; // } // // @Override // public Amount getAmount() { // return amount; // } // // public void setAmount(Amount amount) { // this.amount = amount; // } // } // Path: src/test/java/com/clarity/business/ClientBOTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.in28minutes.junit.business.ClientBO; import com.in28minutes.junit.business.ClientBOImpl; import com.in28minutes.junit.business.exception.DifferentCurrenciesException; import com.in28minutes.junit.model.Amount; import com.in28minutes.junit.model.AmountImpl; import com.in28minutes.junit.model.Currency; import com.in28minutes.junit.model.Product; import com.in28minutes.junit.model.ProductImpl; import com.in28minutes.junit.model.ProductType; package com.clarity.business; public class ClientBOTest { private ClientBO clientBO = new ClientBOImpl(); @Test public void testClientProductSum() throws DifferentCurrenciesException { List<Product> products = new ArrayList<Product>(); products.add(new ProductImpl(100, "Product 15", ProductType.BANK_GUARANTEE, new AmountImpl(
new BigDecimal("5.0"), Currency.EURO)));
in28minutes/MockitoTutorialForBeginners
src/test/java/com/clarity/business/ClientBOTest.java
// Path: src/main/java/com/in28minutes/junit/business/ClientBO.java // public interface ClientBO { // // Amount getClientProductsSum(List<Product> products) // throws DifferentCurrenciesException; // // } // // Path: src/main/java/com/in28minutes/junit/business/ClientBOImpl.java // public class ClientBOImpl implements ClientBO { // // public Amount getClientProductsSum(List<Product> products) // throws DifferentCurrenciesException { // // if (products.size() == 0) // return new AmountImpl(BigDecimal.ZERO, Currency.EURO); // // if (!isCurrencySameForAllProducts(products)) { // throw new DifferentCurrenciesException(); // } // // BigDecimal productSum = calculateProductSum(products); // // Currency firstProductCurrency = products.get(0).getAmount() // .getCurrency(); // // return new AmountImpl(productSum, firstProductCurrency); // } // // private BigDecimal calculateProductSum(List<Product> products) { // BigDecimal sum = BigDecimal.ZERO; // // Calculate Sum of Products // for (Product product : products) { // sum = sum.add(product.getAmount().getValue()); // } // return sum; // } // // private boolean isCurrencySameForAllProducts(List<Product> products) // throws DifferentCurrenciesException { // // Currency firstProductCurrency = products.get(0).getAmount() // .getCurrency(); // // for (Product product : products) { // boolean currencySameAsFirstProduct = product.getAmount() // .getCurrency().equals(firstProductCurrency); // if (!currencySameAsFirstProduct) { // return false; // } // } // // return true; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Amount.java // public interface Amount { // BigDecimal getValue(); // // Currency getCurrency(); // } // // Path: src/main/java/com/in28minutes/junit/model/Currency.java // public enum Currency { // // EURO("EUR"), UNITED_STATES_DOLLAR("USD"), INDIAN_RUPEE("INR"); // // private final String textValue; // // Currency(final String textValue) { // this.textValue = textValue; // } // // @Override // public String toString() { // return textValue; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Product.java // public interface Product { // // long getId(); // // String getName(); // // ProductType getType(); // // Amount getAmount(); // } // // Path: src/main/java/com/in28minutes/junit/model/ProductImpl.java // public class ProductImpl implements Product { // // private long id; // // private String name; // // private ProductType type; // // private Amount amount; // // public ProductImpl(long id, String name, ProductType type, Amount amount) { // super(); // this.id = id; // this.name = name; // this.type = type; // this.amount = amount; // } // // @Override // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // @Override // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public ProductType getType() { // return type; // } // // public void setType(ProductType type) { // this.type = type; // } // // @Override // public Amount getAmount() { // return amount; // } // // public void setAmount(Amount amount) { // this.amount = amount; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.in28minutes.junit.business.ClientBO; import com.in28minutes.junit.business.ClientBOImpl; import com.in28minutes.junit.business.exception.DifferentCurrenciesException; import com.in28minutes.junit.model.Amount; import com.in28minutes.junit.model.AmountImpl; import com.in28minutes.junit.model.Currency; import com.in28minutes.junit.model.Product; import com.in28minutes.junit.model.ProductImpl; import com.in28minutes.junit.model.ProductType;
package com.clarity.business; public class ClientBOTest { private ClientBO clientBO = new ClientBOImpl(); @Test public void testClientProductSum() throws DifferentCurrenciesException { List<Product> products = new ArrayList<Product>(); products.add(new ProductImpl(100, "Product 15", ProductType.BANK_GUARANTEE, new AmountImpl( new BigDecimal("5.0"), Currency.EURO))); products.add(new ProductImpl(120, "Product 20", ProductType.BANK_GUARANTEE, new AmountImpl( new BigDecimal("6.0"), Currency.EURO)));
// Path: src/main/java/com/in28minutes/junit/business/ClientBO.java // public interface ClientBO { // // Amount getClientProductsSum(List<Product> products) // throws DifferentCurrenciesException; // // } // // Path: src/main/java/com/in28minutes/junit/business/ClientBOImpl.java // public class ClientBOImpl implements ClientBO { // // public Amount getClientProductsSum(List<Product> products) // throws DifferentCurrenciesException { // // if (products.size() == 0) // return new AmountImpl(BigDecimal.ZERO, Currency.EURO); // // if (!isCurrencySameForAllProducts(products)) { // throw new DifferentCurrenciesException(); // } // // BigDecimal productSum = calculateProductSum(products); // // Currency firstProductCurrency = products.get(0).getAmount() // .getCurrency(); // // return new AmountImpl(productSum, firstProductCurrency); // } // // private BigDecimal calculateProductSum(List<Product> products) { // BigDecimal sum = BigDecimal.ZERO; // // Calculate Sum of Products // for (Product product : products) { // sum = sum.add(product.getAmount().getValue()); // } // return sum; // } // // private boolean isCurrencySameForAllProducts(List<Product> products) // throws DifferentCurrenciesException { // // Currency firstProductCurrency = products.get(0).getAmount() // .getCurrency(); // // for (Product product : products) { // boolean currencySameAsFirstProduct = product.getAmount() // .getCurrency().equals(firstProductCurrency); // if (!currencySameAsFirstProduct) { // return false; // } // } // // return true; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Amount.java // public interface Amount { // BigDecimal getValue(); // // Currency getCurrency(); // } // // Path: src/main/java/com/in28minutes/junit/model/Currency.java // public enum Currency { // // EURO("EUR"), UNITED_STATES_DOLLAR("USD"), INDIAN_RUPEE("INR"); // // private final String textValue; // // Currency(final String textValue) { // this.textValue = textValue; // } // // @Override // public String toString() { // return textValue; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Product.java // public interface Product { // // long getId(); // // String getName(); // // ProductType getType(); // // Amount getAmount(); // } // // Path: src/main/java/com/in28minutes/junit/model/ProductImpl.java // public class ProductImpl implements Product { // // private long id; // // private String name; // // private ProductType type; // // private Amount amount; // // public ProductImpl(long id, String name, ProductType type, Amount amount) { // super(); // this.id = id; // this.name = name; // this.type = type; // this.amount = amount; // } // // @Override // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // @Override // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public ProductType getType() { // return type; // } // // public void setType(ProductType type) { // this.type = type; // } // // @Override // public Amount getAmount() { // return amount; // } // // public void setAmount(Amount amount) { // this.amount = amount; // } // } // Path: src/test/java/com/clarity/business/ClientBOTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.in28minutes.junit.business.ClientBO; import com.in28minutes.junit.business.ClientBOImpl; import com.in28minutes.junit.business.exception.DifferentCurrenciesException; import com.in28minutes.junit.model.Amount; import com.in28minutes.junit.model.AmountImpl; import com.in28minutes.junit.model.Currency; import com.in28minutes.junit.model.Product; import com.in28minutes.junit.model.ProductImpl; import com.in28minutes.junit.model.ProductType; package com.clarity.business; public class ClientBOTest { private ClientBO clientBO = new ClientBOImpl(); @Test public void testClientProductSum() throws DifferentCurrenciesException { List<Product> products = new ArrayList<Product>(); products.add(new ProductImpl(100, "Product 15", ProductType.BANK_GUARANTEE, new AmountImpl( new BigDecimal("5.0"), Currency.EURO))); products.add(new ProductImpl(120, "Product 20", ProductType.BANK_GUARANTEE, new AmountImpl( new BigDecimal("6.0"), Currency.EURO)));
Amount temp = clientBO.getClientProductsSum(products);
in28minutes/MockitoTutorialForBeginners
src/test/java/com/in28minutes/business/TodoBusinessImplMockitoTest.java
// Path: src/main/java/com/in28minutes/data/api/TodoService.java // public interface TodoService { // // public List<String> retrieveTodos(String user); // // void deleteTodo(String todo); // // }
import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import com.in28minutes.data.api.TodoService;
package com.in28minutes.business; public class TodoBusinessImplMockitoTest { @Test public void usingMockito() {
// Path: src/main/java/com/in28minutes/data/api/TodoService.java // public interface TodoService { // // public List<String> retrieveTodos(String user); // // void deleteTodo(String todo); // // } // Path: src/test/java/com/in28minutes/business/TodoBusinessImplMockitoTest.java import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import com.in28minutes.data.api.TodoService; package com.in28minutes.business; public class TodoBusinessImplMockitoTest { @Test public void usingMockito() {
TodoService todoService = mock(TodoService.class);
in28minutes/MockitoTutorialForBeginners
src/main/java/com/in28minutes/junit/business/ClientBOImpl.java
// Path: src/main/java/com/in28minutes/junit/model/Amount.java // public interface Amount { // BigDecimal getValue(); // // Currency getCurrency(); // } // // Path: src/main/java/com/in28minutes/junit/model/Currency.java // public enum Currency { // // EURO("EUR"), UNITED_STATES_DOLLAR("USD"), INDIAN_RUPEE("INR"); // // private final String textValue; // // Currency(final String textValue) { // this.textValue = textValue; // } // // @Override // public String toString() { // return textValue; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Product.java // public interface Product { // // long getId(); // // String getName(); // // ProductType getType(); // // Amount getAmount(); // }
import java.math.BigDecimal; import java.util.List; import com.in28minutes.junit.business.exception.DifferentCurrenciesException; import com.in28minutes.junit.model.Amount; import com.in28minutes.junit.model.AmountImpl; import com.in28minutes.junit.model.Currency; import com.in28minutes.junit.model.Product;
package com.in28minutes.junit.business; public class ClientBOImpl implements ClientBO { public Amount getClientProductsSum(List<Product> products) throws DifferentCurrenciesException { if (products.size() == 0)
// Path: src/main/java/com/in28minutes/junit/model/Amount.java // public interface Amount { // BigDecimal getValue(); // // Currency getCurrency(); // } // // Path: src/main/java/com/in28minutes/junit/model/Currency.java // public enum Currency { // // EURO("EUR"), UNITED_STATES_DOLLAR("USD"), INDIAN_RUPEE("INR"); // // private final String textValue; // // Currency(final String textValue) { // this.textValue = textValue; // } // // @Override // public String toString() { // return textValue; // } // } // // Path: src/main/java/com/in28minutes/junit/model/Product.java // public interface Product { // // long getId(); // // String getName(); // // ProductType getType(); // // Amount getAmount(); // } // Path: src/main/java/com/in28minutes/junit/business/ClientBOImpl.java import java.math.BigDecimal; import java.util.List; import com.in28minutes.junit.business.exception.DifferentCurrenciesException; import com.in28minutes.junit.model.Amount; import com.in28minutes.junit.model.AmountImpl; import com.in28minutes.junit.model.Currency; import com.in28minutes.junit.model.Product; package com.in28minutes.junit.business; public class ClientBOImpl implements ClientBO { public Amount getClientProductsSum(List<Product> products) throws DifferentCurrenciesException { if (products.size() == 0)
return new AmountImpl(BigDecimal.ZERO, Currency.EURO);
qubole/presto-kinesis
src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java
// Path: src/main/java/com/qubole/presto/kinesis/decoder/csv/CsvKinesisDecoderModule.java // public class CsvKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, CsvKinesisRowDecoder.class); // // bindFieldDecoder(binder, CsvKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/dummy/DummyKinesisDecoderModule.java // public class DummyKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, DummyKinesisRowDecoder.class); // // bindFieldDecoder(binder, DummyKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/json/JsonKinesisDecoderModule.java // public class JsonKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, JsonKinesisRowDecoder.class); // // bindFieldDecoder(binder, JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, RFC2822JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, ISO8601JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, SecondsSinceEpochJsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, MillisecondsSinceEpochJsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, CustomDateTimeJsonKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/raw/RawKinesisDecoderModule.java // public class RawKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // KinesisDecoderModule.bindRowDecoder(binder, RawKinesisRowDecoder.class); // KinesisDecoderModule.bindFieldDecoder(binder, RawKinesisFieldDecoder.class); // } // }
import com.qubole.presto.kinesis.decoder.csv.CsvKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.dummy.DummyKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.json.JsonKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.raw.RawKinesisDecoderModule; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; import com.google.inject.multibindings.Multibinder;
/* * 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.qubole.presto.kinesis.decoder; /** * * Kinesis Decoder implementation of Injection Module interface. Binds all the Row and column decoder modules. * */ public class KinesisDecoderModule implements Module { @Override public void configure(Binder binder) { binder.bind(KinesisDecoderRegistry.class).in(Scopes.SINGLETON);
// Path: src/main/java/com/qubole/presto/kinesis/decoder/csv/CsvKinesisDecoderModule.java // public class CsvKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, CsvKinesisRowDecoder.class); // // bindFieldDecoder(binder, CsvKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/dummy/DummyKinesisDecoderModule.java // public class DummyKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, DummyKinesisRowDecoder.class); // // bindFieldDecoder(binder, DummyKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/json/JsonKinesisDecoderModule.java // public class JsonKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, JsonKinesisRowDecoder.class); // // bindFieldDecoder(binder, JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, RFC2822JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, ISO8601JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, SecondsSinceEpochJsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, MillisecondsSinceEpochJsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, CustomDateTimeJsonKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/raw/RawKinesisDecoderModule.java // public class RawKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // KinesisDecoderModule.bindRowDecoder(binder, RawKinesisRowDecoder.class); // KinesisDecoderModule.bindFieldDecoder(binder, RawKinesisFieldDecoder.class); // } // } // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java import com.qubole.presto.kinesis.decoder.csv.CsvKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.dummy.DummyKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.json.JsonKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.raw.RawKinesisDecoderModule; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; import com.google.inject.multibindings.Multibinder; /* * 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.qubole.presto.kinesis.decoder; /** * * Kinesis Decoder implementation of Injection Module interface. Binds all the Row and column decoder modules. * */ public class KinesisDecoderModule implements Module { @Override public void configure(Binder binder) { binder.bind(KinesisDecoderRegistry.class).in(Scopes.SINGLETON);
binder.install(new DummyKinesisDecoderModule());
qubole/presto-kinesis
src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java
// Path: src/main/java/com/qubole/presto/kinesis/decoder/csv/CsvKinesisDecoderModule.java // public class CsvKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, CsvKinesisRowDecoder.class); // // bindFieldDecoder(binder, CsvKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/dummy/DummyKinesisDecoderModule.java // public class DummyKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, DummyKinesisRowDecoder.class); // // bindFieldDecoder(binder, DummyKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/json/JsonKinesisDecoderModule.java // public class JsonKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, JsonKinesisRowDecoder.class); // // bindFieldDecoder(binder, JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, RFC2822JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, ISO8601JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, SecondsSinceEpochJsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, MillisecondsSinceEpochJsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, CustomDateTimeJsonKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/raw/RawKinesisDecoderModule.java // public class RawKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // KinesisDecoderModule.bindRowDecoder(binder, RawKinesisRowDecoder.class); // KinesisDecoderModule.bindFieldDecoder(binder, RawKinesisFieldDecoder.class); // } // }
import com.qubole.presto.kinesis.decoder.csv.CsvKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.dummy.DummyKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.json.JsonKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.raw.RawKinesisDecoderModule; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; import com.google.inject.multibindings.Multibinder;
/* * 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.qubole.presto.kinesis.decoder; /** * * Kinesis Decoder implementation of Injection Module interface. Binds all the Row and column decoder modules. * */ public class KinesisDecoderModule implements Module { @Override public void configure(Binder binder) { binder.bind(KinesisDecoderRegistry.class).in(Scopes.SINGLETON); binder.install(new DummyKinesisDecoderModule());
// Path: src/main/java/com/qubole/presto/kinesis/decoder/csv/CsvKinesisDecoderModule.java // public class CsvKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, CsvKinesisRowDecoder.class); // // bindFieldDecoder(binder, CsvKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/dummy/DummyKinesisDecoderModule.java // public class DummyKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, DummyKinesisRowDecoder.class); // // bindFieldDecoder(binder, DummyKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/json/JsonKinesisDecoderModule.java // public class JsonKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, JsonKinesisRowDecoder.class); // // bindFieldDecoder(binder, JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, RFC2822JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, ISO8601JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, SecondsSinceEpochJsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, MillisecondsSinceEpochJsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, CustomDateTimeJsonKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/raw/RawKinesisDecoderModule.java // public class RawKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // KinesisDecoderModule.bindRowDecoder(binder, RawKinesisRowDecoder.class); // KinesisDecoderModule.bindFieldDecoder(binder, RawKinesisFieldDecoder.class); // } // } // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java import com.qubole.presto.kinesis.decoder.csv.CsvKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.dummy.DummyKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.json.JsonKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.raw.RawKinesisDecoderModule; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; import com.google.inject.multibindings.Multibinder; /* * 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.qubole.presto.kinesis.decoder; /** * * Kinesis Decoder implementation of Injection Module interface. Binds all the Row and column decoder modules. * */ public class KinesisDecoderModule implements Module { @Override public void configure(Binder binder) { binder.bind(KinesisDecoderRegistry.class).in(Scopes.SINGLETON); binder.install(new DummyKinesisDecoderModule());
binder.install(new CsvKinesisDecoderModule());
qubole/presto-kinesis
src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java
// Path: src/main/java/com/qubole/presto/kinesis/decoder/csv/CsvKinesisDecoderModule.java // public class CsvKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, CsvKinesisRowDecoder.class); // // bindFieldDecoder(binder, CsvKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/dummy/DummyKinesisDecoderModule.java // public class DummyKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, DummyKinesisRowDecoder.class); // // bindFieldDecoder(binder, DummyKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/json/JsonKinesisDecoderModule.java // public class JsonKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, JsonKinesisRowDecoder.class); // // bindFieldDecoder(binder, JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, RFC2822JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, ISO8601JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, SecondsSinceEpochJsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, MillisecondsSinceEpochJsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, CustomDateTimeJsonKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/raw/RawKinesisDecoderModule.java // public class RawKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // KinesisDecoderModule.bindRowDecoder(binder, RawKinesisRowDecoder.class); // KinesisDecoderModule.bindFieldDecoder(binder, RawKinesisFieldDecoder.class); // } // }
import com.qubole.presto.kinesis.decoder.csv.CsvKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.dummy.DummyKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.json.JsonKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.raw.RawKinesisDecoderModule; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; import com.google.inject.multibindings.Multibinder;
/* * 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.qubole.presto.kinesis.decoder; /** * * Kinesis Decoder implementation of Injection Module interface. Binds all the Row and column decoder modules. * */ public class KinesisDecoderModule implements Module { @Override public void configure(Binder binder) { binder.bind(KinesisDecoderRegistry.class).in(Scopes.SINGLETON); binder.install(new DummyKinesisDecoderModule()); binder.install(new CsvKinesisDecoderModule());
// Path: src/main/java/com/qubole/presto/kinesis/decoder/csv/CsvKinesisDecoderModule.java // public class CsvKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, CsvKinesisRowDecoder.class); // // bindFieldDecoder(binder, CsvKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/dummy/DummyKinesisDecoderModule.java // public class DummyKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, DummyKinesisRowDecoder.class); // // bindFieldDecoder(binder, DummyKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/json/JsonKinesisDecoderModule.java // public class JsonKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, JsonKinesisRowDecoder.class); // // bindFieldDecoder(binder, JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, RFC2822JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, ISO8601JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, SecondsSinceEpochJsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, MillisecondsSinceEpochJsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, CustomDateTimeJsonKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/raw/RawKinesisDecoderModule.java // public class RawKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // KinesisDecoderModule.bindRowDecoder(binder, RawKinesisRowDecoder.class); // KinesisDecoderModule.bindFieldDecoder(binder, RawKinesisFieldDecoder.class); // } // } // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java import com.qubole.presto.kinesis.decoder.csv.CsvKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.dummy.DummyKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.json.JsonKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.raw.RawKinesisDecoderModule; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; import com.google.inject.multibindings.Multibinder; /* * 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.qubole.presto.kinesis.decoder; /** * * Kinesis Decoder implementation of Injection Module interface. Binds all the Row and column decoder modules. * */ public class KinesisDecoderModule implements Module { @Override public void configure(Binder binder) { binder.bind(KinesisDecoderRegistry.class).in(Scopes.SINGLETON); binder.install(new DummyKinesisDecoderModule()); binder.install(new CsvKinesisDecoderModule());
binder.install(new JsonKinesisDecoderModule());
qubole/presto-kinesis
src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java
// Path: src/main/java/com/qubole/presto/kinesis/decoder/csv/CsvKinesisDecoderModule.java // public class CsvKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, CsvKinesisRowDecoder.class); // // bindFieldDecoder(binder, CsvKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/dummy/DummyKinesisDecoderModule.java // public class DummyKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, DummyKinesisRowDecoder.class); // // bindFieldDecoder(binder, DummyKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/json/JsonKinesisDecoderModule.java // public class JsonKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, JsonKinesisRowDecoder.class); // // bindFieldDecoder(binder, JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, RFC2822JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, ISO8601JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, SecondsSinceEpochJsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, MillisecondsSinceEpochJsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, CustomDateTimeJsonKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/raw/RawKinesisDecoderModule.java // public class RawKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // KinesisDecoderModule.bindRowDecoder(binder, RawKinesisRowDecoder.class); // KinesisDecoderModule.bindFieldDecoder(binder, RawKinesisFieldDecoder.class); // } // }
import com.qubole.presto.kinesis.decoder.csv.CsvKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.dummy.DummyKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.json.JsonKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.raw.RawKinesisDecoderModule; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; import com.google.inject.multibindings.Multibinder;
/* * 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.qubole.presto.kinesis.decoder; /** * * Kinesis Decoder implementation of Injection Module interface. Binds all the Row and column decoder modules. * */ public class KinesisDecoderModule implements Module { @Override public void configure(Binder binder) { binder.bind(KinesisDecoderRegistry.class).in(Scopes.SINGLETON); binder.install(new DummyKinesisDecoderModule()); binder.install(new CsvKinesisDecoderModule()); binder.install(new JsonKinesisDecoderModule());
// Path: src/main/java/com/qubole/presto/kinesis/decoder/csv/CsvKinesisDecoderModule.java // public class CsvKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, CsvKinesisRowDecoder.class); // // bindFieldDecoder(binder, CsvKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/dummy/DummyKinesisDecoderModule.java // public class DummyKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, DummyKinesisRowDecoder.class); // // bindFieldDecoder(binder, DummyKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/json/JsonKinesisDecoderModule.java // public class JsonKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // bindRowDecoder(binder, JsonKinesisRowDecoder.class); // // bindFieldDecoder(binder, JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, RFC2822JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, ISO8601JsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, SecondsSinceEpochJsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, MillisecondsSinceEpochJsonKinesisFieldDecoder.class); // bindFieldDecoder(binder, CustomDateTimeJsonKinesisFieldDecoder.class); // } // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/raw/RawKinesisDecoderModule.java // public class RawKinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // KinesisDecoderModule.bindRowDecoder(binder, RawKinesisRowDecoder.class); // KinesisDecoderModule.bindFieldDecoder(binder, RawKinesisFieldDecoder.class); // } // } // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java import com.qubole.presto.kinesis.decoder.csv.CsvKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.dummy.DummyKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.json.JsonKinesisDecoderModule; import com.qubole.presto.kinesis.decoder.raw.RawKinesisDecoderModule; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; import com.google.inject.multibindings.Multibinder; /* * 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.qubole.presto.kinesis.decoder; /** * * Kinesis Decoder implementation of Injection Module interface. Binds all the Row and column decoder modules. * */ public class KinesisDecoderModule implements Module { @Override public void configure(Binder binder) { binder.bind(KinesisDecoderRegistry.class).in(Scopes.SINGLETON); binder.install(new DummyKinesisDecoderModule()); binder.install(new CsvKinesisDecoderModule()); binder.install(new JsonKinesisDecoderModule());
binder.install(new RawKinesisDecoderModule());
qubole/presto-kinesis
src/main/java/com/qubole/presto/kinesis/decoder/json/JsonKinesisDecoderModule.java
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindFieldDecoder(Binder binder, Class<? extends KinesisFieldDecoder<?>> decoderClass) // { // Multibinder<KinesisFieldDecoder<?>> fieldDecoderBinder = Multibinder.newSetBinder(binder, new TypeLiteral<KinesisFieldDecoder<?>>() {}); // fieldDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindRowDecoder(Binder binder, Class<? extends KinesisRowDecoder> decoderClass) // { // Multibinder<KinesisRowDecoder> rowDecoderBinder = Multibinder.newSetBinder(binder, KinesisRowDecoder.class); // rowDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // }
import com.google.inject.Module; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindFieldDecoder; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindRowDecoder; import com.google.inject.Binder;
/* * 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.qubole.presto.kinesis.decoder.json; /** * Guice module for the Json decoder module. This is the most mature (best tested) topic decoder. * Besides the default field decoder for all the values, it also supports a number of decoders for * timestamp specific information. These decoders can be selected with the <tt>dataFormat</tt> field. * <ul> * <li><tt>iso8601</tt> - decode the value of a json string field as an ISO8601 timestamp; returns a long value which can be mapped to a presto TIMESTAMP.</li> * <li><tt>rfc2822</tt> - decode the value of a json string field as an RFC 2822 compliant timestamp; returns a long value which can be mapped to a presto TIMESTAMP * (the twitter sample feed contains timestamps in this format).</li> * <li><tt>milliseconds-since-epoch</tt> - Interpret the value of a json string or number field as a long containing milliseconds since the beginning of the epoch.</li> * <li><tt>seconds-since-epoch</tt> - Interpret the value of a json string or number field as a long containing seconds since the beginning of the epoch.</li> * <li><tt>custom-date-time</tt> - Interpret the value of a json string field according to the {@link org.joda.time.format.DateTimeFormatter} formatting rules * given using the <tt>formatHint</tt> field.</li> * </ul> */ public class JsonKinesisDecoderModule implements Module { @Override public void configure(Binder binder) {
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindFieldDecoder(Binder binder, Class<? extends KinesisFieldDecoder<?>> decoderClass) // { // Multibinder<KinesisFieldDecoder<?>> fieldDecoderBinder = Multibinder.newSetBinder(binder, new TypeLiteral<KinesisFieldDecoder<?>>() {}); // fieldDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindRowDecoder(Binder binder, Class<? extends KinesisRowDecoder> decoderClass) // { // Multibinder<KinesisRowDecoder> rowDecoderBinder = Multibinder.newSetBinder(binder, KinesisRowDecoder.class); // rowDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // Path: src/main/java/com/qubole/presto/kinesis/decoder/json/JsonKinesisDecoderModule.java import com.google.inject.Module; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindFieldDecoder; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindRowDecoder; import com.google.inject.Binder; /* * 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.qubole.presto.kinesis.decoder.json; /** * Guice module for the Json decoder module. This is the most mature (best tested) topic decoder. * Besides the default field decoder for all the values, it also supports a number of decoders for * timestamp specific information. These decoders can be selected with the <tt>dataFormat</tt> field. * <ul> * <li><tt>iso8601</tt> - decode the value of a json string field as an ISO8601 timestamp; returns a long value which can be mapped to a presto TIMESTAMP.</li> * <li><tt>rfc2822</tt> - decode the value of a json string field as an RFC 2822 compliant timestamp; returns a long value which can be mapped to a presto TIMESTAMP * (the twitter sample feed contains timestamps in this format).</li> * <li><tt>milliseconds-since-epoch</tt> - Interpret the value of a json string or number field as a long containing milliseconds since the beginning of the epoch.</li> * <li><tt>seconds-since-epoch</tt> - Interpret the value of a json string or number field as a long containing seconds since the beginning of the epoch.</li> * <li><tt>custom-date-time</tt> - Interpret the value of a json string field according to the {@link org.joda.time.format.DateTimeFormatter} formatting rules * given using the <tt>formatHint</tt> field.</li> * </ul> */ public class JsonKinesisDecoderModule implements Module { @Override public void configure(Binder binder) {
bindRowDecoder(binder, JsonKinesisRowDecoder.class);
qubole/presto-kinesis
src/main/java/com/qubole/presto/kinesis/decoder/json/JsonKinesisDecoderModule.java
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindFieldDecoder(Binder binder, Class<? extends KinesisFieldDecoder<?>> decoderClass) // { // Multibinder<KinesisFieldDecoder<?>> fieldDecoderBinder = Multibinder.newSetBinder(binder, new TypeLiteral<KinesisFieldDecoder<?>>() {}); // fieldDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindRowDecoder(Binder binder, Class<? extends KinesisRowDecoder> decoderClass) // { // Multibinder<KinesisRowDecoder> rowDecoderBinder = Multibinder.newSetBinder(binder, KinesisRowDecoder.class); // rowDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // }
import com.google.inject.Module; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindFieldDecoder; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindRowDecoder; import com.google.inject.Binder;
/* * 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.qubole.presto.kinesis.decoder.json; /** * Guice module for the Json decoder module. This is the most mature (best tested) topic decoder. * Besides the default field decoder for all the values, it also supports a number of decoders for * timestamp specific information. These decoders can be selected with the <tt>dataFormat</tt> field. * <ul> * <li><tt>iso8601</tt> - decode the value of a json string field as an ISO8601 timestamp; returns a long value which can be mapped to a presto TIMESTAMP.</li> * <li><tt>rfc2822</tt> - decode the value of a json string field as an RFC 2822 compliant timestamp; returns a long value which can be mapped to a presto TIMESTAMP * (the twitter sample feed contains timestamps in this format).</li> * <li><tt>milliseconds-since-epoch</tt> - Interpret the value of a json string or number field as a long containing milliseconds since the beginning of the epoch.</li> * <li><tt>seconds-since-epoch</tt> - Interpret the value of a json string or number field as a long containing seconds since the beginning of the epoch.</li> * <li><tt>custom-date-time</tt> - Interpret the value of a json string field according to the {@link org.joda.time.format.DateTimeFormatter} formatting rules * given using the <tt>formatHint</tt> field.</li> * </ul> */ public class JsonKinesisDecoderModule implements Module { @Override public void configure(Binder binder) { bindRowDecoder(binder, JsonKinesisRowDecoder.class);
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindFieldDecoder(Binder binder, Class<? extends KinesisFieldDecoder<?>> decoderClass) // { // Multibinder<KinesisFieldDecoder<?>> fieldDecoderBinder = Multibinder.newSetBinder(binder, new TypeLiteral<KinesisFieldDecoder<?>>() {}); // fieldDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindRowDecoder(Binder binder, Class<? extends KinesisRowDecoder> decoderClass) // { // Multibinder<KinesisRowDecoder> rowDecoderBinder = Multibinder.newSetBinder(binder, KinesisRowDecoder.class); // rowDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // Path: src/main/java/com/qubole/presto/kinesis/decoder/json/JsonKinesisDecoderModule.java import com.google.inject.Module; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindFieldDecoder; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindRowDecoder; import com.google.inject.Binder; /* * 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.qubole.presto.kinesis.decoder.json; /** * Guice module for the Json decoder module. This is the most mature (best tested) topic decoder. * Besides the default field decoder for all the values, it also supports a number of decoders for * timestamp specific information. These decoders can be selected with the <tt>dataFormat</tt> field. * <ul> * <li><tt>iso8601</tt> - decode the value of a json string field as an ISO8601 timestamp; returns a long value which can be mapped to a presto TIMESTAMP.</li> * <li><tt>rfc2822</tt> - decode the value of a json string field as an RFC 2822 compliant timestamp; returns a long value which can be mapped to a presto TIMESTAMP * (the twitter sample feed contains timestamps in this format).</li> * <li><tt>milliseconds-since-epoch</tt> - Interpret the value of a json string or number field as a long containing milliseconds since the beginning of the epoch.</li> * <li><tt>seconds-since-epoch</tt> - Interpret the value of a json string or number field as a long containing seconds since the beginning of the epoch.</li> * <li><tt>custom-date-time</tt> - Interpret the value of a json string field according to the {@link org.joda.time.format.DateTimeFormatter} formatting rules * given using the <tt>formatHint</tt> field.</li> * </ul> */ public class JsonKinesisDecoderModule implements Module { @Override public void configure(Binder binder) { bindRowDecoder(binder, JsonKinesisRowDecoder.class);
bindFieldDecoder(binder, JsonKinesisFieldDecoder.class);
qubole/presto-kinesis
src/main/java/com/qubole/presto/kinesis/decoder/dummy/DummyKinesisDecoderModule.java
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindRowDecoder(Binder binder, Class<? extends KinesisRowDecoder> decoderClass) // { // Multibinder<KinesisRowDecoder> rowDecoderBinder = Multibinder.newSetBinder(binder, KinesisRowDecoder.class); // rowDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindFieldDecoder(Binder binder, Class<? extends KinesisFieldDecoder<?>> decoderClass) // { // Multibinder<KinesisFieldDecoder<?>> fieldDecoderBinder = Multibinder.newSetBinder(binder, new TypeLiteral<KinesisFieldDecoder<?>>() {}); // fieldDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // }
import com.google.inject.Module; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindRowDecoder; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindFieldDecoder; import com.google.inject.Binder;
/* * 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.qubole.presto.kinesis.decoder.dummy; public class DummyKinesisDecoderModule implements Module { @Override public void configure(Binder binder) {
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindRowDecoder(Binder binder, Class<? extends KinesisRowDecoder> decoderClass) // { // Multibinder<KinesisRowDecoder> rowDecoderBinder = Multibinder.newSetBinder(binder, KinesisRowDecoder.class); // rowDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindFieldDecoder(Binder binder, Class<? extends KinesisFieldDecoder<?>> decoderClass) // { // Multibinder<KinesisFieldDecoder<?>> fieldDecoderBinder = Multibinder.newSetBinder(binder, new TypeLiteral<KinesisFieldDecoder<?>>() {}); // fieldDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // Path: src/main/java/com/qubole/presto/kinesis/decoder/dummy/DummyKinesisDecoderModule.java import com.google.inject.Module; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindRowDecoder; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindFieldDecoder; import com.google.inject.Binder; /* * 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.qubole.presto.kinesis.decoder.dummy; public class DummyKinesisDecoderModule implements Module { @Override public void configure(Binder binder) {
bindRowDecoder(binder, DummyKinesisRowDecoder.class);
qubole/presto-kinesis
src/main/java/com/qubole/presto/kinesis/decoder/dummy/DummyKinesisDecoderModule.java
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindRowDecoder(Binder binder, Class<? extends KinesisRowDecoder> decoderClass) // { // Multibinder<KinesisRowDecoder> rowDecoderBinder = Multibinder.newSetBinder(binder, KinesisRowDecoder.class); // rowDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindFieldDecoder(Binder binder, Class<? extends KinesisFieldDecoder<?>> decoderClass) // { // Multibinder<KinesisFieldDecoder<?>> fieldDecoderBinder = Multibinder.newSetBinder(binder, new TypeLiteral<KinesisFieldDecoder<?>>() {}); // fieldDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // }
import com.google.inject.Module; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindRowDecoder; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindFieldDecoder; import com.google.inject.Binder;
/* * 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.qubole.presto.kinesis.decoder.dummy; public class DummyKinesisDecoderModule implements Module { @Override public void configure(Binder binder) { bindRowDecoder(binder, DummyKinesisRowDecoder.class);
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindRowDecoder(Binder binder, Class<? extends KinesisRowDecoder> decoderClass) // { // Multibinder<KinesisRowDecoder> rowDecoderBinder = Multibinder.newSetBinder(binder, KinesisRowDecoder.class); // rowDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindFieldDecoder(Binder binder, Class<? extends KinesisFieldDecoder<?>> decoderClass) // { // Multibinder<KinesisFieldDecoder<?>> fieldDecoderBinder = Multibinder.newSetBinder(binder, new TypeLiteral<KinesisFieldDecoder<?>>() {}); // fieldDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // Path: src/main/java/com/qubole/presto/kinesis/decoder/dummy/DummyKinesisDecoderModule.java import com.google.inject.Module; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindRowDecoder; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindFieldDecoder; import com.google.inject.Binder; /* * 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.qubole.presto.kinesis.decoder.dummy; public class DummyKinesisDecoderModule implements Module { @Override public void configure(Binder binder) { bindRowDecoder(binder, DummyKinesisRowDecoder.class);
bindFieldDecoder(binder, DummyKinesisFieldDecoder.class);
qubole/presto-kinesis
src/main/java/com/qubole/presto/kinesis/KinesisRecordSet.java
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisFieldDecoder.java // public interface KinesisFieldDecoder<T> // { // /** // * Default name. Each decoder type *must* have a default decoder as fallback. // */ // String DEFAULT_FIELD_DECODER_NAME = "_default"; // // /** // * Returns the types which the field decoder can process. // * // * @return Returns the types which the field decoder can process // */ // Set<Class<?>> getJavaTypes(); // // /** // * Returns the name of the row decoder to which this field decoder belongs. // * // * @return Returns the name of the row decoder to which this field decoder belongs // */ // String getRowDecoderName(); // // /** // * Returns the field decoder specific name. This name will be selected with the stream description value. // * // * @return Returns the field decoder specific name. // */ // String getFieldDecoderName(); // // /** // * Decode a value for the given column handle. // * // * @param value The raw value as generated by the row decoder. // * @param columnHandle The column for which the value is decoded. // * @return A {@link KinesisFieldDecoder} instance which returns a captured value for this specific column. // */ // KinesisFieldValueProvider decode(T value, KinesisColumnHandle columnHandle); // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisRowDecoder.java // public interface KinesisRowDecoder // { // /** // * Returns the row decoder specific name. // * // * @return Return the row decoder specific name // */ // String getName(); // // /** // * Decodes a given set of bytes into field values. // * // * @param data The row data (Kinesis message) to decode. // * @param fieldValueProviders Must be a mutable set. Any field value provider created by this row decoder is put into this set. // * @param columnHandles List of column handles for which field values are required. // * @param fieldDecoders Map from column handles to decoders. This map should be used to look up the field decoder that generates the field value provider for a given column handle. // * @return true if the row was decoded successfully, false if it could not be decoded (was corrupt). TODO - reverse this boolean. // */ // boolean decodeRow( // byte[] data, // Set<KinesisFieldValueProvider> fieldValueProviders, // List<KinesisColumnHandle> columnHandles, // Map<KinesisColumnHandle, KinesisFieldDecoder<?>> fieldDecoders); // }
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.qubole.presto.kinesis.decoder.KinesisFieldDecoder; import com.qubole.presto.kinesis.decoder.KinesisRowDecoder; import io.airlift.log.Logger; import io.airlift.slice.Slice; import io.airlift.slice.Slices; import java.nio.ByteBuffer; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.kinesis.model.GetRecordsRequest; import com.amazonaws.services.kinesis.model.GetRecordsResult; import com.amazonaws.services.kinesis.model.GetShardIteratorRequest; import com.amazonaws.services.kinesis.model.GetShardIteratorResult; import com.amazonaws.services.kinesis.model.Record; import com.amazonaws.services.kinesis.model.ResourceNotFoundException; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.RecordCursor; import com.facebook.presto.spi.RecordSet; import com.facebook.presto.spi.type.Type; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet;
/* * 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.qubole.presto.kinesis; public class KinesisRecordSet implements RecordSet { /** Indicates how close to current we want to be before stopping the fetch of records in a query. */ public static final int MILLIS_BEHIND_LIMIT = 10000; private static final Logger log = Logger.get(KinesisRecordSet.class); private static final byte [] EMPTY_BYTE_ARRAY = new byte [0]; private final KinesisSplit split; private final ConnectorSession session; private final KinesisClientProvider clientManager; private final KinesisConnectorConfig kinesisConnectorConfig;
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisFieldDecoder.java // public interface KinesisFieldDecoder<T> // { // /** // * Default name. Each decoder type *must* have a default decoder as fallback. // */ // String DEFAULT_FIELD_DECODER_NAME = "_default"; // // /** // * Returns the types which the field decoder can process. // * // * @return Returns the types which the field decoder can process // */ // Set<Class<?>> getJavaTypes(); // // /** // * Returns the name of the row decoder to which this field decoder belongs. // * // * @return Returns the name of the row decoder to which this field decoder belongs // */ // String getRowDecoderName(); // // /** // * Returns the field decoder specific name. This name will be selected with the stream description value. // * // * @return Returns the field decoder specific name. // */ // String getFieldDecoderName(); // // /** // * Decode a value for the given column handle. // * // * @param value The raw value as generated by the row decoder. // * @param columnHandle The column for which the value is decoded. // * @return A {@link KinesisFieldDecoder} instance which returns a captured value for this specific column. // */ // KinesisFieldValueProvider decode(T value, KinesisColumnHandle columnHandle); // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisRowDecoder.java // public interface KinesisRowDecoder // { // /** // * Returns the row decoder specific name. // * // * @return Return the row decoder specific name // */ // String getName(); // // /** // * Decodes a given set of bytes into field values. // * // * @param data The row data (Kinesis message) to decode. // * @param fieldValueProviders Must be a mutable set. Any field value provider created by this row decoder is put into this set. // * @param columnHandles List of column handles for which field values are required. // * @param fieldDecoders Map from column handles to decoders. This map should be used to look up the field decoder that generates the field value provider for a given column handle. // * @return true if the row was decoded successfully, false if it could not be decoded (was corrupt). TODO - reverse this boolean. // */ // boolean decodeRow( // byte[] data, // Set<KinesisFieldValueProvider> fieldValueProviders, // List<KinesisColumnHandle> columnHandles, // Map<KinesisColumnHandle, KinesisFieldDecoder<?>> fieldDecoders); // } // Path: src/main/java/com/qubole/presto/kinesis/KinesisRecordSet.java import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.qubole.presto.kinesis.decoder.KinesisFieldDecoder; import com.qubole.presto.kinesis.decoder.KinesisRowDecoder; import io.airlift.log.Logger; import io.airlift.slice.Slice; import io.airlift.slice.Slices; import java.nio.ByteBuffer; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.kinesis.model.GetRecordsRequest; import com.amazonaws.services.kinesis.model.GetRecordsResult; import com.amazonaws.services.kinesis.model.GetShardIteratorRequest; import com.amazonaws.services.kinesis.model.GetShardIteratorResult; import com.amazonaws.services.kinesis.model.Record; import com.amazonaws.services.kinesis.model.ResourceNotFoundException; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.RecordCursor; import com.facebook.presto.spi.RecordSet; import com.facebook.presto.spi.type.Type; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; /* * 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.qubole.presto.kinesis; public class KinesisRecordSet implements RecordSet { /** Indicates how close to current we want to be before stopping the fetch of records in a query. */ public static final int MILLIS_BEHIND_LIMIT = 10000; private static final Logger log = Logger.get(KinesisRecordSet.class); private static final byte [] EMPTY_BYTE_ARRAY = new byte [0]; private final KinesisSplit split; private final ConnectorSession session; private final KinesisClientProvider clientManager; private final KinesisConnectorConfig kinesisConnectorConfig;
private final KinesisRowDecoder messageDecoder;
qubole/presto-kinesis
src/main/java/com/qubole/presto/kinesis/KinesisRecordSet.java
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisFieldDecoder.java // public interface KinesisFieldDecoder<T> // { // /** // * Default name. Each decoder type *must* have a default decoder as fallback. // */ // String DEFAULT_FIELD_DECODER_NAME = "_default"; // // /** // * Returns the types which the field decoder can process. // * // * @return Returns the types which the field decoder can process // */ // Set<Class<?>> getJavaTypes(); // // /** // * Returns the name of the row decoder to which this field decoder belongs. // * // * @return Returns the name of the row decoder to which this field decoder belongs // */ // String getRowDecoderName(); // // /** // * Returns the field decoder specific name. This name will be selected with the stream description value. // * // * @return Returns the field decoder specific name. // */ // String getFieldDecoderName(); // // /** // * Decode a value for the given column handle. // * // * @param value The raw value as generated by the row decoder. // * @param columnHandle The column for which the value is decoded. // * @return A {@link KinesisFieldDecoder} instance which returns a captured value for this specific column. // */ // KinesisFieldValueProvider decode(T value, KinesisColumnHandle columnHandle); // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisRowDecoder.java // public interface KinesisRowDecoder // { // /** // * Returns the row decoder specific name. // * // * @return Return the row decoder specific name // */ // String getName(); // // /** // * Decodes a given set of bytes into field values. // * // * @param data The row data (Kinesis message) to decode. // * @param fieldValueProviders Must be a mutable set. Any field value provider created by this row decoder is put into this set. // * @param columnHandles List of column handles for which field values are required. // * @param fieldDecoders Map from column handles to decoders. This map should be used to look up the field decoder that generates the field value provider for a given column handle. // * @return true if the row was decoded successfully, false if it could not be decoded (was corrupt). TODO - reverse this boolean. // */ // boolean decodeRow( // byte[] data, // Set<KinesisFieldValueProvider> fieldValueProviders, // List<KinesisColumnHandle> columnHandles, // Map<KinesisColumnHandle, KinesisFieldDecoder<?>> fieldDecoders); // }
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.qubole.presto.kinesis.decoder.KinesisFieldDecoder; import com.qubole.presto.kinesis.decoder.KinesisRowDecoder; import io.airlift.log.Logger; import io.airlift.slice.Slice; import io.airlift.slice.Slices; import java.nio.ByteBuffer; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.kinesis.model.GetRecordsRequest; import com.amazonaws.services.kinesis.model.GetRecordsResult; import com.amazonaws.services.kinesis.model.GetShardIteratorRequest; import com.amazonaws.services.kinesis.model.GetShardIteratorResult; import com.amazonaws.services.kinesis.model.Record; import com.amazonaws.services.kinesis.model.ResourceNotFoundException; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.RecordCursor; import com.facebook.presto.spi.RecordSet; import com.facebook.presto.spi.type.Type; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet;
/* * 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.qubole.presto.kinesis; public class KinesisRecordSet implements RecordSet { /** Indicates how close to current we want to be before stopping the fetch of records in a query. */ public static final int MILLIS_BEHIND_LIMIT = 10000; private static final Logger log = Logger.get(KinesisRecordSet.class); private static final byte [] EMPTY_BYTE_ARRAY = new byte [0]; private final KinesisSplit split; private final ConnectorSession session; private final KinesisClientProvider clientManager; private final KinesisConnectorConfig kinesisConnectorConfig; private final KinesisRowDecoder messageDecoder;
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisFieldDecoder.java // public interface KinesisFieldDecoder<T> // { // /** // * Default name. Each decoder type *must* have a default decoder as fallback. // */ // String DEFAULT_FIELD_DECODER_NAME = "_default"; // // /** // * Returns the types which the field decoder can process. // * // * @return Returns the types which the field decoder can process // */ // Set<Class<?>> getJavaTypes(); // // /** // * Returns the name of the row decoder to which this field decoder belongs. // * // * @return Returns the name of the row decoder to which this field decoder belongs // */ // String getRowDecoderName(); // // /** // * Returns the field decoder specific name. This name will be selected with the stream description value. // * // * @return Returns the field decoder specific name. // */ // String getFieldDecoderName(); // // /** // * Decode a value for the given column handle. // * // * @param value The raw value as generated by the row decoder. // * @param columnHandle The column for which the value is decoded. // * @return A {@link KinesisFieldDecoder} instance which returns a captured value for this specific column. // */ // KinesisFieldValueProvider decode(T value, KinesisColumnHandle columnHandle); // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisRowDecoder.java // public interface KinesisRowDecoder // { // /** // * Returns the row decoder specific name. // * // * @return Return the row decoder specific name // */ // String getName(); // // /** // * Decodes a given set of bytes into field values. // * // * @param data The row data (Kinesis message) to decode. // * @param fieldValueProviders Must be a mutable set. Any field value provider created by this row decoder is put into this set. // * @param columnHandles List of column handles for which field values are required. // * @param fieldDecoders Map from column handles to decoders. This map should be used to look up the field decoder that generates the field value provider for a given column handle. // * @return true if the row was decoded successfully, false if it could not be decoded (was corrupt). TODO - reverse this boolean. // */ // boolean decodeRow( // byte[] data, // Set<KinesisFieldValueProvider> fieldValueProviders, // List<KinesisColumnHandle> columnHandles, // Map<KinesisColumnHandle, KinesisFieldDecoder<?>> fieldDecoders); // } // Path: src/main/java/com/qubole/presto/kinesis/KinesisRecordSet.java import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.qubole.presto.kinesis.decoder.KinesisFieldDecoder; import com.qubole.presto.kinesis.decoder.KinesisRowDecoder; import io.airlift.log.Logger; import io.airlift.slice.Slice; import io.airlift.slice.Slices; import java.nio.ByteBuffer; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.kinesis.model.GetRecordsRequest; import com.amazonaws.services.kinesis.model.GetRecordsResult; import com.amazonaws.services.kinesis.model.GetShardIteratorRequest; import com.amazonaws.services.kinesis.model.GetShardIteratorResult; import com.amazonaws.services.kinesis.model.Record; import com.amazonaws.services.kinesis.model.ResourceNotFoundException; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.RecordCursor; import com.facebook.presto.spi.RecordSet; import com.facebook.presto.spi.type.Type; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; /* * 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.qubole.presto.kinesis; public class KinesisRecordSet implements RecordSet { /** Indicates how close to current we want to be before stopping the fetch of records in a query. */ public static final int MILLIS_BEHIND_LIMIT = 10000; private static final Logger log = Logger.get(KinesisRecordSet.class); private static final byte [] EMPTY_BYTE_ARRAY = new byte [0]; private final KinesisSplit split; private final ConnectorSession session; private final KinesisClientProvider clientManager; private final KinesisConnectorConfig kinesisConnectorConfig; private final KinesisRowDecoder messageDecoder;
private final Map<KinesisColumnHandle, KinesisFieldDecoder<?>> messageFieldDecoders;
qubole/presto-kinesis
src/main/java/com/qubole/presto/kinesis/KinesisMetadata.java
// Path: src/main/java/com/qubole/presto/kinesis/decoder/dummy/DummyKinesisRowDecoder.java // public class DummyKinesisRowDecoder // implements KinesisRowDecoder // { // public static final String NAME = "dummy"; // // @Override // public String getName() // { // return NAME; // } // // @Override // public boolean decodeRow(byte[] data, // Set<KinesisFieldValueProvider> fieldValueProviders, // List<KinesisColumnHandle> columnHandles, // Map<KinesisColumnHandle, KinesisFieldDecoder<?>> fieldDecoders) // { // return true; // } // }
import static com.google.common.base.Preconditions.checkNotNull; import com.facebook.presto.spi.ColumnHandle; import com.facebook.presto.spi.ColumnMetadata; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.ConnectorTableMetadata; import com.facebook.presto.spi.Constraint; import com.facebook.presto.spi.SchemaTableName; import com.facebook.presto.spi.SchemaTablePrefix; import com.facebook.presto.spi.TableNotFoundException; import com.facebook.presto.spi.ConnectorTableLayoutResult; import com.facebook.presto.spi.ConnectorTableHandle; import com.facebook.presto.spi.ConnectorTableLayout; import com.facebook.presto.spi.ConnectorTableLayoutHandle; import io.airlift.log.Logger; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import com.qubole.presto.kinesis.decoder.dummy.DummyKinesisRowDecoder; import com.facebook.presto.spi.connector.ConnectorMetadata; import com.google.common.annotations.VisibleForTesting; import java.util.function.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.inject.Inject; import com.google.inject.name.Named;
} @Override public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix) { checkNotNull(prefix, "prefix is null"); log.debug("Called listTableColumns on %s.%s", prefix.getSchemaName(), prefix.getTableName()); ImmutableMap.Builder<SchemaTableName, List<ColumnMetadata>> columns = ImmutableMap.builder(); // NOTE: prefix.getTableName or prefix.getSchemaName can be null List<SchemaTableName> tableNames; if (prefix.getSchemaName() != null && prefix.getTableName() != null) { tableNames = ImmutableList.of(new SchemaTableName(prefix.getSchemaName(), prefix.getTableName())); } else { tableNames = listTables(session, (String) null); } for (SchemaTableName tableName : tableNames) { ConnectorTableMetadata tableMetadata = getTableMetadata(tableName); if (tableMetadata != null) { columns.put(tableName, tableMetadata.getColumns()); } } return columns.build(); } private static String getDataFormat(KinesisStreamFieldGroup fieldGroup) {
// Path: src/main/java/com/qubole/presto/kinesis/decoder/dummy/DummyKinesisRowDecoder.java // public class DummyKinesisRowDecoder // implements KinesisRowDecoder // { // public static final String NAME = "dummy"; // // @Override // public String getName() // { // return NAME; // } // // @Override // public boolean decodeRow(byte[] data, // Set<KinesisFieldValueProvider> fieldValueProviders, // List<KinesisColumnHandle> columnHandles, // Map<KinesisColumnHandle, KinesisFieldDecoder<?>> fieldDecoders) // { // return true; // } // } // Path: src/main/java/com/qubole/presto/kinesis/KinesisMetadata.java import static com.google.common.base.Preconditions.checkNotNull; import com.facebook.presto.spi.ColumnHandle; import com.facebook.presto.spi.ColumnMetadata; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.ConnectorTableMetadata; import com.facebook.presto.spi.Constraint; import com.facebook.presto.spi.SchemaTableName; import com.facebook.presto.spi.SchemaTablePrefix; import com.facebook.presto.spi.TableNotFoundException; import com.facebook.presto.spi.ConnectorTableLayoutResult; import com.facebook.presto.spi.ConnectorTableHandle; import com.facebook.presto.spi.ConnectorTableLayout; import com.facebook.presto.spi.ConnectorTableLayoutHandle; import io.airlift.log.Logger; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import com.qubole.presto.kinesis.decoder.dummy.DummyKinesisRowDecoder; import com.facebook.presto.spi.connector.ConnectorMetadata; import com.google.common.annotations.VisibleForTesting; import java.util.function.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.inject.Inject; import com.google.inject.name.Named; } @Override public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix) { checkNotNull(prefix, "prefix is null"); log.debug("Called listTableColumns on %s.%s", prefix.getSchemaName(), prefix.getTableName()); ImmutableMap.Builder<SchemaTableName, List<ColumnMetadata>> columns = ImmutableMap.builder(); // NOTE: prefix.getTableName or prefix.getSchemaName can be null List<SchemaTableName> tableNames; if (prefix.getSchemaName() != null && prefix.getTableName() != null) { tableNames = ImmutableList.of(new SchemaTableName(prefix.getSchemaName(), prefix.getTableName())); } else { tableNames = listTables(session, (String) null); } for (SchemaTableName tableName : tableNames) { ConnectorTableMetadata tableMetadata = getTableMetadata(tableName); if (tableMetadata != null) { columns.put(tableName, tableMetadata.getColumns()); } } return columns.build(); } private static String getDataFormat(KinesisStreamFieldGroup fieldGroup) {
return (fieldGroup == null) ? DummyKinesisRowDecoder.NAME : fieldGroup.getDataFormat();
qubole/presto-kinesis
src/test/java/com/qubole/presto/kinesis/util/EmbeddedKinesisStream.java
// Path: src/main/java/com/qubole/presto/kinesis/KinesisAwsCredentials.java // public class KinesisAwsCredentials // implements AWSCredentials // { // private String accessKeyId; // private String secretKey; // // @Inject // public KinesisAwsCredentials(String accessKeyId, String secretKey) // { // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // } // // @Override // public String getAWSAccessKeyId() // { // return accessKeyId; // } // // @Override // public String getAWSSecretKey() // { // return secretKey; // } // }
import static java.util.concurrent.TimeUnit.MILLISECONDS; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import com.amazonaws.services.kinesis.AmazonKinesisClient; import com.amazonaws.services.kinesis.model.CreateStreamRequest; import com.amazonaws.services.kinesis.model.DeleteStreamRequest; import com.amazonaws.services.kinesis.model.DescribeStreamRequest; import com.amazonaws.services.kinesis.model.StreamDescription; import com.qubole.presto.kinesis.KinesisAwsCredentials;
/* * 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.qubole.presto.kinesis.util; public class EmbeddedKinesisStream implements Closeable {
// Path: src/main/java/com/qubole/presto/kinesis/KinesisAwsCredentials.java // public class KinesisAwsCredentials // implements AWSCredentials // { // private String accessKeyId; // private String secretKey; // // @Inject // public KinesisAwsCredentials(String accessKeyId, String secretKey) // { // this.accessKeyId = accessKeyId; // this.secretKey = secretKey; // } // // @Override // public String getAWSAccessKeyId() // { // return accessKeyId; // } // // @Override // public String getAWSSecretKey() // { // return secretKey; // } // } // Path: src/test/java/com/qubole/presto/kinesis/util/EmbeddedKinesisStream.java import static java.util.concurrent.TimeUnit.MILLISECONDS; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import com.amazonaws.services.kinesis.AmazonKinesisClient; import com.amazonaws.services.kinesis.model.CreateStreamRequest; import com.amazonaws.services.kinesis.model.DeleteStreamRequest; import com.amazonaws.services.kinesis.model.DescribeStreamRequest; import com.amazonaws.services.kinesis.model.StreamDescription; import com.qubole.presto.kinesis.KinesisAwsCredentials; /* * 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.qubole.presto.kinesis.util; public class EmbeddedKinesisStream implements Closeable {
private KinesisAwsCredentials awsCredentials;
qubole/presto-kinesis
src/main/java/com/qubole/presto/kinesis/decoder/csv/CsvKinesisDecoderModule.java
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindFieldDecoder(Binder binder, Class<? extends KinesisFieldDecoder<?>> decoderClass) // { // Multibinder<KinesisFieldDecoder<?>> fieldDecoderBinder = Multibinder.newSetBinder(binder, new TypeLiteral<KinesisFieldDecoder<?>>() {}); // fieldDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindRowDecoder(Binder binder, Class<? extends KinesisRowDecoder> decoderClass) // { // Multibinder<KinesisRowDecoder> rowDecoderBinder = Multibinder.newSetBinder(binder, KinesisRowDecoder.class); // rowDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // }
import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindRowDecoder; import com.google.inject.Binder; import com.google.inject.Module; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindFieldDecoder;
/* * 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.qubole.presto.kinesis.decoder.csv; public class CsvKinesisDecoderModule implements Module { @Override public void configure(Binder binder) {
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindFieldDecoder(Binder binder, Class<? extends KinesisFieldDecoder<?>> decoderClass) // { // Multibinder<KinesisFieldDecoder<?>> fieldDecoderBinder = Multibinder.newSetBinder(binder, new TypeLiteral<KinesisFieldDecoder<?>>() {}); // fieldDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindRowDecoder(Binder binder, Class<? extends KinesisRowDecoder> decoderClass) // { // Multibinder<KinesisRowDecoder> rowDecoderBinder = Multibinder.newSetBinder(binder, KinesisRowDecoder.class); // rowDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // Path: src/main/java/com/qubole/presto/kinesis/decoder/csv/CsvKinesisDecoderModule.java import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindRowDecoder; import com.google.inject.Binder; import com.google.inject.Module; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindFieldDecoder; /* * 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.qubole.presto.kinesis.decoder.csv; public class CsvKinesisDecoderModule implements Module { @Override public void configure(Binder binder) {
bindRowDecoder(binder, CsvKinesisRowDecoder.class);
qubole/presto-kinesis
src/main/java/com/qubole/presto/kinesis/decoder/csv/CsvKinesisDecoderModule.java
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindFieldDecoder(Binder binder, Class<? extends KinesisFieldDecoder<?>> decoderClass) // { // Multibinder<KinesisFieldDecoder<?>> fieldDecoderBinder = Multibinder.newSetBinder(binder, new TypeLiteral<KinesisFieldDecoder<?>>() {}); // fieldDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindRowDecoder(Binder binder, Class<? extends KinesisRowDecoder> decoderClass) // { // Multibinder<KinesisRowDecoder> rowDecoderBinder = Multibinder.newSetBinder(binder, KinesisRowDecoder.class); // rowDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // }
import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindRowDecoder; import com.google.inject.Binder; import com.google.inject.Module; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindFieldDecoder;
/* * 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.qubole.presto.kinesis.decoder.csv; public class CsvKinesisDecoderModule implements Module { @Override public void configure(Binder binder) { bindRowDecoder(binder, CsvKinesisRowDecoder.class);
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindFieldDecoder(Binder binder, Class<? extends KinesisFieldDecoder<?>> decoderClass) // { // Multibinder<KinesisFieldDecoder<?>> fieldDecoderBinder = Multibinder.newSetBinder(binder, new TypeLiteral<KinesisFieldDecoder<?>>() {}); // fieldDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // // Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public static void bindRowDecoder(Binder binder, Class<? extends KinesisRowDecoder> decoderClass) // { // Multibinder<KinesisRowDecoder> rowDecoderBinder = Multibinder.newSetBinder(binder, KinesisRowDecoder.class); // rowDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // Path: src/main/java/com/qubole/presto/kinesis/decoder/csv/CsvKinesisDecoderModule.java import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindRowDecoder; import com.google.inject.Binder; import com.google.inject.Module; import static com.qubole.presto.kinesis.decoder.KinesisDecoderModule.bindFieldDecoder; /* * 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.qubole.presto.kinesis.decoder.csv; public class CsvKinesisDecoderModule implements Module { @Override public void configure(Binder binder) { bindRowDecoder(binder, CsvKinesisRowDecoder.class);
bindFieldDecoder(binder, CsvKinesisFieldDecoder.class);
qubole/presto-kinesis
src/main/java/com/qubole/presto/kinesis/decoder/raw/RawKinesisDecoderModule.java
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public class KinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // binder.bind(KinesisDecoderRegistry.class).in(Scopes.SINGLETON); // // binder.install(new DummyKinesisDecoderModule()); // binder.install(new CsvKinesisDecoderModule()); // binder.install(new JsonKinesisDecoderModule()); // binder.install(new RawKinesisDecoderModule()); // } // // public static void bindRowDecoder(Binder binder, Class<? extends KinesisRowDecoder> decoderClass) // { // Multibinder<KinesisRowDecoder> rowDecoderBinder = Multibinder.newSetBinder(binder, KinesisRowDecoder.class); // rowDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // // public static void bindFieldDecoder(Binder binder, Class<? extends KinesisFieldDecoder<?>> decoderClass) // { // Multibinder<KinesisFieldDecoder<?>> fieldDecoderBinder = Multibinder.newSetBinder(binder, new TypeLiteral<KinesisFieldDecoder<?>>() {}); // fieldDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // }
import com.google.inject.Module; import com.qubole.presto.kinesis.decoder.KinesisDecoderModule; import com.google.inject.Binder;
/* * 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.qubole.presto.kinesis.decoder.raw; public class RawKinesisDecoderModule implements Module { @Override public void configure(Binder binder) {
// Path: src/main/java/com/qubole/presto/kinesis/decoder/KinesisDecoderModule.java // public class KinesisDecoderModule // implements Module // { // @Override // public void configure(Binder binder) // { // binder.bind(KinesisDecoderRegistry.class).in(Scopes.SINGLETON); // // binder.install(new DummyKinesisDecoderModule()); // binder.install(new CsvKinesisDecoderModule()); // binder.install(new JsonKinesisDecoderModule()); // binder.install(new RawKinesisDecoderModule()); // } // // public static void bindRowDecoder(Binder binder, Class<? extends KinesisRowDecoder> decoderClass) // { // Multibinder<KinesisRowDecoder> rowDecoderBinder = Multibinder.newSetBinder(binder, KinesisRowDecoder.class); // rowDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // // public static void bindFieldDecoder(Binder binder, Class<? extends KinesisFieldDecoder<?>> decoderClass) // { // Multibinder<KinesisFieldDecoder<?>> fieldDecoderBinder = Multibinder.newSetBinder(binder, new TypeLiteral<KinesisFieldDecoder<?>>() {}); // fieldDecoderBinder.addBinding().to(decoderClass).in(Scopes.SINGLETON); // } // } // Path: src/main/java/com/qubole/presto/kinesis/decoder/raw/RawKinesisDecoderModule.java import com.google.inject.Module; import com.qubole.presto.kinesis.decoder.KinesisDecoderModule; import com.google.inject.Binder; /* * 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.qubole.presto.kinesis.decoder.raw; public class RawKinesisDecoderModule implements Module { @Override public void configure(Binder binder) {
KinesisDecoderModule.bindRowDecoder(binder, RawKinesisRowDecoder.class);
kgilmer/knapsack
org/knapsack/KnapsackLogger.java
// Path: org/knapsack/shell/StringConstants.java // public final class StringConstants { // // /** // * The system character or characters to signify a new line. // */ // public static final String CRLF = System.getProperty("line.separator"); // // /** // * Character for tab. // */ // public static final String TAB = " \t"; // // // // }
import org.osgi.service.log.LogListener; import org.osgi.service.log.LogReaderService; import java.io.PrintWriter; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.knapsack.shell.StringConstants; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.service.log.LogEntry;
if (enabled) doKnapsackLog(bundle, sr, level, msg, throwable); } /* (non-Javadoc) * @see org.apache.felix.framework.Logger#setSystemBundleContext(org.osgi.framework.BundleContext) */ protected void setSystemBundleContext(BundleContext context) { super.setSystemBundleContext(context); } /** * Print a log entry in the knapsack style. * @param bundle * @param sr * @param level * @param msg * @param throwable */ public static void doKnapsackLog(Bundle bundle, ServiceReference sr, int level, String msg, Throwable throwable) { if (dateFormatter == null) dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); StringBuilder sb = new StringBuilder(); sb.append(dateFormatter.format(new Date(System.currentTimeMillis()))); sb.append(' '); getLevelLabel(level, sb); sb.append(' '); sb.append(msg);
// Path: org/knapsack/shell/StringConstants.java // public final class StringConstants { // // /** // * The system character or characters to signify a new line. // */ // public static final String CRLF = System.getProperty("line.separator"); // // /** // * Character for tab. // */ // public static final String TAB = " \t"; // // // // } // Path: org/knapsack/KnapsackLogger.java import org.osgi.service.log.LogListener; import org.osgi.service.log.LogReaderService; import java.io.PrintWriter; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.knapsack.shell.StringConstants; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.service.log.LogEntry; if (enabled) doKnapsackLog(bundle, sr, level, msg, throwable); } /* (non-Javadoc) * @see org.apache.felix.framework.Logger#setSystemBundleContext(org.osgi.framework.BundleContext) */ protected void setSystemBundleContext(BundleContext context) { super.setSystemBundleContext(context); } /** * Print a log entry in the knapsack style. * @param bundle * @param sr * @param level * @param msg * @param throwable */ public static void doKnapsackLog(Bundle bundle, ServiceReference sr, int level, String msg, Throwable throwable) { if (dateFormatter == null) dateFormatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT); StringBuilder sb = new StringBuilder(); sb.append(dateFormatter.format(new Date(System.currentTimeMillis()))); sb.append(' '); getLevelLabel(level, sb); sb.append(' '); sb.append(msg);
sb.append(StringConstants.TAB);
kgilmer/knapsack
org/knapsack/shell/commands/LogCommand.java
// Path: org/knapsack/shell/StringConstants.java // public final class StringConstants { // // /** // * The system character or characters to signify a new line. // */ // public static final String CRLF = System.getProperty("line.separator"); // // /** // * Character for tab. // */ // public static final String TAB = " \t"; // // // // }
import java.io.PrintWriter; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import org.knapsack.shell.StringConstants; import org.osgi.framework.ServiceReference; import org.osgi.service.log.LogEntry; import org.osgi.service.log.LogReaderService;
return sb.toString(); } @Override public String getCommandName() { return "log"; } @Override public String getUsage() { return "[-b (brief)]"; } @Override public String getDescription() { return "Print OSGi log."; } private String formatDateTime(long time) { return dateFormatter.format(new Date(time)); } private void addLogEntry(LogEntry entry, StringBuilder sb, boolean verbose) { if (verbose) { sb.append(formatDateTime(entry.getTime())); sb.append(' '); sb.append(getLevelLabel(entry.getLevel())); sb.append(' '); sb.append(entry.getMessage());
// Path: org/knapsack/shell/StringConstants.java // public final class StringConstants { // // /** // * The system character or characters to signify a new line. // */ // public static final String CRLF = System.getProperty("line.separator"); // // /** // * Character for tab. // */ // public static final String TAB = " \t"; // // // // } // Path: org/knapsack/shell/commands/LogCommand.java import java.io.PrintWriter; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import org.knapsack.shell.StringConstants; import org.osgi.framework.ServiceReference; import org.osgi.service.log.LogEntry; import org.osgi.service.log.LogReaderService; return sb.toString(); } @Override public String getCommandName() { return "log"; } @Override public String getUsage() { return "[-b (brief)]"; } @Override public String getDescription() { return "Print OSGi log."; } private String formatDateTime(long time) { return dateFormatter.format(new Date(time)); } private void addLogEntry(LogEntry entry, StringBuilder sb, boolean verbose) { if (verbose) { sb.append(formatDateTime(entry.getTime())); sb.append(' '); sb.append(getLevelLabel(entry.getLevel())); sb.append(' '); sb.append(entry.getMessage());
sb.append(StringConstants.TAB);
kgilmer/knapsack
org/knapsack/init/BundleJarWrapper.java
// Path: org/knapsack/shell/commands/BundlesCommand.java // public class BundlesCommand extends AbstractKnapsackCommand { // // @Override // public String execute() throws Exception { // final StringBuilder sb = new StringBuilder(1024 * 8); // // Applier.map( // context.getBundles(), // new PrintBundleFunction(sb, arguments.contains("-v"))); // // return sb.toString(); // } // // @Override // public String getCommandName() { // return "bundles"; // } // // @Override // public String getUsage() { // return "[-v (verbose)]"; // } // // @Override // public String getDescription() { // return "Get list of OSGi bundles installed in the framework."; // } // // public static void appendId(StringBuilder sb, long id) { // sb.append("["); // if (id < 10) // sb.append(" "); // sb.append(id); // sb.append("]"); // } // // /** // * @param b // * @return The location on filesystem of bundle // */ // public static String getBundleLocation(Bundle b) { // //Remove "file://" prefix // StringBuilder sb = new StringBuilder(); // sb.append(b.getLocation().substring(7)); // // return sb.toString(); // } // // /** // * @param b // * @return The bundle version as defined in the manifest. // */ // public static String getBundleVersion(Bundle b) { // if (b == null) // return ""; // // String version = (String) b.getHeaders().get("Bundle-Version"); // // if (version == null) { // version = ""; // } // // StringBuilder sb = new StringBuilder(); // sb.append(version); // // return sb.toString(); // } // // public static String getBundleLabel(Bundle b) { // if (b == null) // return ""; // // StringBuilder sb = new StringBuilder(); // // BundlesCommand.appendId(sb, b.getBundleId()); // sb.append(getBundleName(b)); // sb.append(" ("); // sb.append(BundlesCommand.getBundleVersion(b)); // sb.append(")"); // // return sb.toString(); // } // // public static String getBundleName(Bundle b) { // if (b == null) // return "[null]"; // // String name = (String) b.getHeaders().get("Bundle-SymbolicName"); // // if (name == null) { // name = (String) b.getHeaders().get("Bundle-Name"); // } // // if (name == null) { // name = "Undefined"; // } // // if (name.indexOf(";") > -1) // name = name.split(";")[0]; // // StringBuilder sb = new StringBuilder(); // sb.append(name); // // return sb.toString(); // } // // /** // * Return state label as defined in OSGi spec. // * // * @param state // * @return // */ // public static void getStateName(int state, StringBuilder sb) { // String l = null; // switch (state) { // case 0x00000001: // l = "UNINS"; // break; // case 0x00000002: // l = "INSTL"; // break; // case 0x00000004: // l = "RESOL"; // break; // case 0x00000008: // l = "START"; // break; // case 0x00000010: // l = " STOP"; // break; // case 0x00000020: // l = "ACTIV"; // break; // default: // l = "[UNKNOWN STATE: " + state + "]"; // break; // } // // sb.append(l); // } // }
import java.io.File; import org.knapsack.shell.commands.BundlesCommand; import org.osgi.framework.Bundle;
/* * Copyright 2011 Ken Gilmer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.knapsack.init; /** * Wrap a Bundle and the file Jar that it started from. * * @author kgilmer * */ class BundleJarWrapper { private final File jar; private final Bundle bundle; /** * @param jar * @param bundle */ public BundleJarWrapper(File jar, Bundle bundle) { this.jar = jar; this.bundle = bundle; } /** * @return jar of bundle */ public File getJar() { return jar; } /** * @return bundle reference */ public Bundle getBundle() { return bundle; } @Override public String toString() {
// Path: org/knapsack/shell/commands/BundlesCommand.java // public class BundlesCommand extends AbstractKnapsackCommand { // // @Override // public String execute() throws Exception { // final StringBuilder sb = new StringBuilder(1024 * 8); // // Applier.map( // context.getBundles(), // new PrintBundleFunction(sb, arguments.contains("-v"))); // // return sb.toString(); // } // // @Override // public String getCommandName() { // return "bundles"; // } // // @Override // public String getUsage() { // return "[-v (verbose)]"; // } // // @Override // public String getDescription() { // return "Get list of OSGi bundles installed in the framework."; // } // // public static void appendId(StringBuilder sb, long id) { // sb.append("["); // if (id < 10) // sb.append(" "); // sb.append(id); // sb.append("]"); // } // // /** // * @param b // * @return The location on filesystem of bundle // */ // public static String getBundleLocation(Bundle b) { // //Remove "file://" prefix // StringBuilder sb = new StringBuilder(); // sb.append(b.getLocation().substring(7)); // // return sb.toString(); // } // // /** // * @param b // * @return The bundle version as defined in the manifest. // */ // public static String getBundleVersion(Bundle b) { // if (b == null) // return ""; // // String version = (String) b.getHeaders().get("Bundle-Version"); // // if (version == null) { // version = ""; // } // // StringBuilder sb = new StringBuilder(); // sb.append(version); // // return sb.toString(); // } // // public static String getBundleLabel(Bundle b) { // if (b == null) // return ""; // // StringBuilder sb = new StringBuilder(); // // BundlesCommand.appendId(sb, b.getBundleId()); // sb.append(getBundleName(b)); // sb.append(" ("); // sb.append(BundlesCommand.getBundleVersion(b)); // sb.append(")"); // // return sb.toString(); // } // // public static String getBundleName(Bundle b) { // if (b == null) // return "[null]"; // // String name = (String) b.getHeaders().get("Bundle-SymbolicName"); // // if (name == null) { // name = (String) b.getHeaders().get("Bundle-Name"); // } // // if (name == null) { // name = "Undefined"; // } // // if (name.indexOf(";") > -1) // name = name.split(";")[0]; // // StringBuilder sb = new StringBuilder(); // sb.append(name); // // return sb.toString(); // } // // /** // * Return state label as defined in OSGi spec. // * // * @param state // * @return // */ // public static void getStateName(int state, StringBuilder sb) { // String l = null; // switch (state) { // case 0x00000001: // l = "UNINS"; // break; // case 0x00000002: // l = "INSTL"; // break; // case 0x00000004: // l = "RESOL"; // break; // case 0x00000008: // l = "START"; // break; // case 0x00000010: // l = " STOP"; // break; // case 0x00000020: // l = "ACTIV"; // break; // default: // l = "[UNKNOWN STATE: " + state + "]"; // break; // } // // sb.append(l); // } // } // Path: org/knapsack/init/BundleJarWrapper.java import java.io.File; import org.knapsack.shell.commands.BundlesCommand; import org.osgi.framework.Bundle; /* * Copyright 2011 Ken Gilmer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.knapsack.init; /** * Wrap a Bundle and the file Jar that it started from. * * @author kgilmer * */ class BundleJarWrapper { private final File jar; private final Bundle bundle; /** * @param jar * @param bundle */ public BundleJarWrapper(File jar, Bundle bundle) { this.jar = jar; this.bundle = bundle; } /** * @return jar of bundle */ public File getJar() { return jar; } /** * @return bundle reference */ public Bundle getBundle() { return bundle; } @Override public String toString() {
return BundlesCommand.getBundleName(bundle);
kgilmer/knapsack
org/knapsack/shell/CommandExecutor.java
// Path: org/knapsack/shell/pub/IKnapsackCommand.java // public interface IKnapsackCommand { // /** // * Command initialization. // * // * @param arguments list of arguments passed to command. Command name not included. // * @param context BundleContext // */ // public void initialize(List<String> arguments, BundleContext context); // // /** // * @return List of arguments passed to command. // */ // public List<String> getArguments(); // // /** // * Execute the command // * // * @throws Exception // */ // public String execute() throws Exception; // // /** // * @return true if the command and parameters are valid. // */ // public boolean isValid(); // // /** // * @return Name of command. // */ // public String getName(); // // /** // * @return A short textual description of command usage. // */ // public String getUsage(); // // /** // * @return A description of what the command does. // */ // public String getDescription(); // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import org.knapsack.shell.pub.IKnapsackCommand; import org.osgi.framework.BundleException;
/* * Copyright 2011 Ken Gilmer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.knapsack.shell; /** * Given an input String, find command to execute, execute, and return results. * * @author kgilmer * */ public class CommandExecutor { private final CommandParser parser; protected CommandExecutor(CommandParser parser) { this.parser = parser; } /** * Executes the command entered by user. * * @param line * @param justCrlf * @param pwErr * @throws IOException */ public String executeCommand(String line) throws IOException { if (line == null) { // JVM is being shutdown return ""; } else if (line.length() > 0) {
// Path: org/knapsack/shell/pub/IKnapsackCommand.java // public interface IKnapsackCommand { // /** // * Command initialization. // * // * @param arguments list of arguments passed to command. Command name not included. // * @param context BundleContext // */ // public void initialize(List<String> arguments, BundleContext context); // // /** // * @return List of arguments passed to command. // */ // public List<String> getArguments(); // // /** // * Execute the command // * // * @throws Exception // */ // public String execute() throws Exception; // // /** // * @return true if the command and parameters are valid. // */ // public boolean isValid(); // // /** // * @return Name of command. // */ // public String getName(); // // /** // * @return A short textual description of command usage. // */ // public String getUsage(); // // /** // * @return A description of what the command does. // */ // public String getDescription(); // } // Path: org/knapsack/shell/CommandExecutor.java import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import org.knapsack.shell.pub.IKnapsackCommand; import org.osgi.framework.BundleException; /* * Copyright 2011 Ken Gilmer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.knapsack.shell; /** * Given an input String, find command to execute, execute, and return results. * * @author kgilmer * */ public class CommandExecutor { private final CommandParser parser; protected CommandExecutor(CommandParser parser) { this.parser = parser; } /** * Executes the command entered by user. * * @param line * @param justCrlf * @param pwErr * @throws IOException */ public String executeCommand(String line) throws IOException { if (line == null) { // JVM is being shutdown return ""; } else if (line.length() > 0) {
IKnapsackCommand cmd = parser.parse(line);
kgilmer/knapsack
org/knapsack/FSHelper.java
// Path: org/knapsack/shell/StringConstants.java // public final class StringConstants { // // /** // * The system character or characters to signify a new line. // */ // public static final String CRLF = System.getProperty("line.separator"); // // /** // * Character for tab. // */ // public static final String TAB = " \t"; // // // // }
import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.URISyntaxException; import java.util.Arrays; import org.knapsack.shell.StringConstants; import org.osgi.service.log.LogService;
if (istream == null) throw new IOException("Jar resource is not present: " + resourceFilename); FileOutputStream fos = new FileOutputStream(outFile); copy(istream, fos); closeQuietly(fos); return true; } /** * Copy shell scripts from the Jar into the deployment directory. * @param scriptDir * @param shellPort * @param command * @throws IOException * @throws URISyntaxException */ public static void copyScripts(File scriptDir, int shellPort, String command) throws IOException, URISyntaxException { if (!scriptDir.exists()) if (!scriptDir.mkdirs()) throw new IOException("Unable to create directories: " + scriptDir); File baseScriptFile = new File(scriptDir, ConfigurationConstants.BASE_SCRIPT_FILENAME); if (!baseScriptFile.exists()) { StringBuilder sb = new StringBuilder(); sb.append("#!/bin/sh");
// Path: org/knapsack/shell/StringConstants.java // public final class StringConstants { // // /** // * The system character or characters to signify a new line. // */ // public static final String CRLF = System.getProperty("line.separator"); // // /** // * Character for tab. // */ // public static final String TAB = " \t"; // // // // } // Path: org/knapsack/FSHelper.java import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.URISyntaxException; import java.util.Arrays; import org.knapsack.shell.StringConstants; import org.osgi.service.log.LogService; if (istream == null) throw new IOException("Jar resource is not present: " + resourceFilename); FileOutputStream fos = new FileOutputStream(outFile); copy(istream, fos); closeQuietly(fos); return true; } /** * Copy shell scripts from the Jar into the deployment directory. * @param scriptDir * @param shellPort * @param command * @throws IOException * @throws URISyntaxException */ public static void copyScripts(File scriptDir, int shellPort, String command) throws IOException, URISyntaxException { if (!scriptDir.exists()) if (!scriptDir.mkdirs()) throw new IOException("Unable to create directories: " + scriptDir); File baseScriptFile = new File(scriptDir, ConfigurationConstants.BASE_SCRIPT_FILENAME); if (!baseScriptFile.exists()) { StringBuilder sb = new StringBuilder(); sb.append("#!/bin/sh");
sb.append(StringConstants.CRLF);
s3curitybug/similarity-uniform-fuzzy-hash
src/test/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHashTest.java
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java // public enum SimilarityTypes { // // /** // * Similarity of a hash to other hashes. // */ // SIMILARITY("Similarity"), // // /** // * Similarity of other hashes to a hash. // */ // REVERSE_SIMILARITY("Reverse"), // // /** // * Maximum similarity between Similarity and Reverse. // */ // MAXIMUM("Maximum"), // // /** // * Minimum similarity between Similarity and Reverse. // */ // MINIMUM("Minimum"), // // /** // * Arithmetic mean between Similarity and Reverse, (Similarity * Reverse) / 2. // */ // ARITHMETIC_MEAN("ArithMean"), // // /** // * Geometric mean between Similarity and Reverse, sqrt(Similarity * Reverse). // */ // GEOMETRIC_MEAN("GeomMean"); // // /** // * Similarity type name. // */ // private String name; // // /** // * Constructor. // * // * @param name Similarity type name. // */ // SimilarityTypes( // String name) { // // this.name = name; // // } // // /** // * @return The similarity type name. // */ // public String getName() { // // return name; // // } // // /** // * @return A list with all the similarity types names. // */ // public static List<String> names() { // // SimilarityTypes[] similarityTypes = SimilarityTypes.values(); // List<String> similarityTypesNames = new ArrayList<>(similarityTypes.length); // // for (SimilarityTypes similarityType : similarityTypes) { // similarityTypesNames.add(similarityType.name); // } // // return similarityTypesNames; // // } // // }
import org.junit.Assert; import org.junit.Test; import com.github.s3curitybug.similarityuniformfuzzyhash.UniformFuzzyHash.SimilarityTypes; import java.io.File; import java.io.IOException;
Assert.assertTrue(hash.equals(rebuiltHash)); Assert.assertTrue(hashString.equals(rebuiltHashString)); } /** * Similarity test. * Tests all the similarity types between two hashes computed over two test resource files. * * @throws IOException In case an exception occurs reading a test resource file. */ @Test public void similarityTest() throws IOException { final int factor = 50001; final File file1 = TestResourcesUtils.getTestResourceFile("InsideDoc/Lenna.png"); final File file2 = TestResourcesUtils.getTestResourceFile("InsideDoc/Doc_Lenna.docx"); final boolean printHashes = true; UniformFuzzyHash hash1 = new UniformFuzzyHash(file1, factor); UniformFuzzyHash hash2 = new UniformFuzzyHash(file2, factor); if (printHashes) { System.out.println(hash1); System.out.println(hash2); System.out.println(); }
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHash.java // public enum SimilarityTypes { // // /** // * Similarity of a hash to other hashes. // */ // SIMILARITY("Similarity"), // // /** // * Similarity of other hashes to a hash. // */ // REVERSE_SIMILARITY("Reverse"), // // /** // * Maximum similarity between Similarity and Reverse. // */ // MAXIMUM("Maximum"), // // /** // * Minimum similarity between Similarity and Reverse. // */ // MINIMUM("Minimum"), // // /** // * Arithmetic mean between Similarity and Reverse, (Similarity * Reverse) / 2. // */ // ARITHMETIC_MEAN("ArithMean"), // // /** // * Geometric mean between Similarity and Reverse, sqrt(Similarity * Reverse). // */ // GEOMETRIC_MEAN("GeomMean"); // // /** // * Similarity type name. // */ // private String name; // // /** // * Constructor. // * // * @param name Similarity type name. // */ // SimilarityTypes( // String name) { // // this.name = name; // // } // // /** // * @return The similarity type name. // */ // public String getName() { // // return name; // // } // // /** // * @return A list with all the similarity types names. // */ // public static List<String> names() { // // SimilarityTypes[] similarityTypes = SimilarityTypes.values(); // List<String> similarityTypesNames = new ArrayList<>(similarityTypes.length); // // for (SimilarityTypes similarityType : similarityTypes) { // similarityTypesNames.add(similarityType.name); // } // // return similarityTypesNames; // // } // // } // Path: src/test/java/com/github/s3curitybug/similarityuniformfuzzyhash/UniformFuzzyHashTest.java import org.junit.Assert; import org.junit.Test; import com.github.s3curitybug.similarityuniformfuzzyhash.UniformFuzzyHash.SimilarityTypes; import java.io.File; import java.io.IOException; Assert.assertTrue(hash.equals(rebuiltHash)); Assert.assertTrue(hashString.equals(rebuiltHashString)); } /** * Similarity test. * Tests all the similarity types between two hashes computed over two test resource files. * * @throws IOException In case an exception occurs reading a test resource file. */ @Test public void similarityTest() throws IOException { final int factor = 50001; final File file1 = TestResourcesUtils.getTestResourceFile("InsideDoc/Lenna.png"); final File file2 = TestResourcesUtils.getTestResourceFile("InsideDoc/Doc_Lenna.docx"); final boolean printHashes = true; UniformFuzzyHash hash1 = new UniformFuzzyHash(file1, factor); UniformFuzzyHash hash2 = new UniformFuzzyHash(file2, factor); if (printHashes) { System.out.println(hash1); System.out.println(hash2); System.out.println(); }
for (SimilarityTypes similarityType : SimilarityTypes.values()) {
s3curitybug/similarity-uniform-fuzzy-hash
src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/VisualRepresentation.java
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char ANSI_CODE_COLOR_END = 'm'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final DecimalFormatSymbols DECIMALS_FORMAT_SYMBOLS = // DecimalFormatSymbols.getInstance(Locale.ROOT); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char UNICODE_CTRL = '\u001b'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static String spaces( // int n) { // // return repeatString(" ", n); // // } // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected enum AnsiCodeColors { // // /** // * Red font color. // */ // RED_FONT(31), // // /** // * Green font color. // */ // GREEN_FONT(32), // // /** // * Blue font color. // */ // BLUE_FONT(34), // // /** // * Reset color. // */ // RESET(0); // // /** // * Color number. // */ // private int number; // // /** // * Color code. // */ // private String code; // // /** // * Constructor. // * // * @param number Color number. // */ // AnsiCodeColors( // int number) { // // this.number = number; // this.code = Character.toString(UNICODE_CTRL) // + Character.toString(ANSI_CODE_START) // + Integer.toString(number) // + Character.toString(ANSI_CODE_COLOR_END); // // } // // /** // * @return The color number. // */ // protected int getNumber() { // return number; // } // // /** // * @return The color code. // */ // protected String getCode() { // return code; // } // // /** // * Removes all ANSI code colors from a string. // * // * @param string A string. // * @return The string without any ANSI code colors. // */ // protected static String remove( // String string) { // // return ANSI_CODE_COLOR_PATTERN.matcher(string).replaceAll(""); // // } // // }
import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.ANSI_CODE_COLOR_END; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.DECIMALS_FORMAT_SYMBOLS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.UNICODE_CTRL; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.spaces; import org.apache.commons.io.IOUtils; import org.fusesource.jansi.AnsiConsole; import com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.AnsiCodeColors; import java.io.PrintStream; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set;
package com.github.s3curitybug.similarityuniformfuzzyhash; /** * This class provides utility static methods to represent and compare Uniform Fuzzy Hashes in * visual way. * * @author s3curitybug@gmail.com * */ public final class VisualRepresentation { /** * Charset in which bases are encoded. */ public static final Charset BASES_ENCODING = StandardCharsets.UTF_8; /** * Printable ASCII base. */ public static final char[] PRINTABLE_ASCII_BASE = readBaseFromResources("printableAscii.base"); /** * Default base. */ public static final char[] DEFAULT_BASE = PRINTABLE_ASCII_BASE; /** * Default factor divisor. */ public static final int DEFAULT_FACTOR_DIVISOR = 3; /** * Default line wrap. */ public static final int DEFAULT_LINE_WRAP = 60; /** * Bases path inside resources. */ private static final String RESOURCES_BASES_PATH = "/VisualPrint/"; /** * Format in which accumulated wrap length per line will be formatted during a string wrap. */ private static final String ACCUMULATED_WRAP_FORMAT = "%5s %s"; /** * Format in which percent accumulated wrap length per line will be formatted during a string * wrap. */ private static final DecimalFormat ACCUMULATED_WRAP_DECIMAL_FORMAT =
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char ANSI_CODE_COLOR_END = 'm'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final DecimalFormatSymbols DECIMALS_FORMAT_SYMBOLS = // DecimalFormatSymbols.getInstance(Locale.ROOT); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char UNICODE_CTRL = '\u001b'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static String spaces( // int n) { // // return repeatString(" ", n); // // } // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected enum AnsiCodeColors { // // /** // * Red font color. // */ // RED_FONT(31), // // /** // * Green font color. // */ // GREEN_FONT(32), // // /** // * Blue font color. // */ // BLUE_FONT(34), // // /** // * Reset color. // */ // RESET(0); // // /** // * Color number. // */ // private int number; // // /** // * Color code. // */ // private String code; // // /** // * Constructor. // * // * @param number Color number. // */ // AnsiCodeColors( // int number) { // // this.number = number; // this.code = Character.toString(UNICODE_CTRL) // + Character.toString(ANSI_CODE_START) // + Integer.toString(number) // + Character.toString(ANSI_CODE_COLOR_END); // // } // // /** // * @return The color number. // */ // protected int getNumber() { // return number; // } // // /** // * @return The color code. // */ // protected String getCode() { // return code; // } // // /** // * Removes all ANSI code colors from a string. // * // * @param string A string. // * @return The string without any ANSI code colors. // */ // protected static String remove( // String string) { // // return ANSI_CODE_COLOR_PATTERN.matcher(string).replaceAll(""); // // } // // } // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/VisualRepresentation.java import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.ANSI_CODE_COLOR_END; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.DECIMALS_FORMAT_SYMBOLS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.UNICODE_CTRL; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.spaces; import org.apache.commons.io.IOUtils; import org.fusesource.jansi.AnsiConsole; import com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.AnsiCodeColors; import java.io.PrintStream; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; package com.github.s3curitybug.similarityuniformfuzzyhash; /** * This class provides utility static methods to represent and compare Uniform Fuzzy Hashes in * visual way. * * @author s3curitybug@gmail.com * */ public final class VisualRepresentation { /** * Charset in which bases are encoded. */ public static final Charset BASES_ENCODING = StandardCharsets.UTF_8; /** * Printable ASCII base. */ public static final char[] PRINTABLE_ASCII_BASE = readBaseFromResources("printableAscii.base"); /** * Default base. */ public static final char[] DEFAULT_BASE = PRINTABLE_ASCII_BASE; /** * Default factor divisor. */ public static final int DEFAULT_FACTOR_DIVISOR = 3; /** * Default line wrap. */ public static final int DEFAULT_LINE_WRAP = 60; /** * Bases path inside resources. */ private static final String RESOURCES_BASES_PATH = "/VisualPrint/"; /** * Format in which accumulated wrap length per line will be formatted during a string wrap. */ private static final String ACCUMULATED_WRAP_FORMAT = "%5s %s"; /** * Format in which percent accumulated wrap length per line will be formatted during a string * wrap. */ private static final DecimalFormat ACCUMULATED_WRAP_DECIMAL_FORMAT =
new DecimalFormat("0.0", DECIMALS_FORMAT_SYMBOLS);
s3curitybug/similarity-uniform-fuzzy-hash
src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/VisualRepresentation.java
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char ANSI_CODE_COLOR_END = 'm'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final DecimalFormatSymbols DECIMALS_FORMAT_SYMBOLS = // DecimalFormatSymbols.getInstance(Locale.ROOT); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char UNICODE_CTRL = '\u001b'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static String spaces( // int n) { // // return repeatString(" ", n); // // } // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected enum AnsiCodeColors { // // /** // * Red font color. // */ // RED_FONT(31), // // /** // * Green font color. // */ // GREEN_FONT(32), // // /** // * Blue font color. // */ // BLUE_FONT(34), // // /** // * Reset color. // */ // RESET(0); // // /** // * Color number. // */ // private int number; // // /** // * Color code. // */ // private String code; // // /** // * Constructor. // * // * @param number Color number. // */ // AnsiCodeColors( // int number) { // // this.number = number; // this.code = Character.toString(UNICODE_CTRL) // + Character.toString(ANSI_CODE_START) // + Integer.toString(number) // + Character.toString(ANSI_CODE_COLOR_END); // // } // // /** // * @return The color number. // */ // protected int getNumber() { // return number; // } // // /** // * @return The color code. // */ // protected String getCode() { // return code; // } // // /** // * Removes all ANSI code colors from a string. // * // * @param string A string. // * @return The string without any ANSI code colors. // */ // protected static String remove( // String string) { // // return ANSI_CODE_COLOR_PATTERN.matcher(string).replaceAll(""); // // } // // }
import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.ANSI_CODE_COLOR_END; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.DECIMALS_FORMAT_SYMBOLS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.UNICODE_CTRL; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.spaces; import org.apache.commons.io.IOUtils; import org.fusesource.jansi.AnsiConsole; import com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.AnsiCodeColors; import java.io.PrintStream; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set;
package com.github.s3curitybug.similarityuniformfuzzyhash; /** * This class provides utility static methods to represent and compare Uniform Fuzzy Hashes in * visual way. * * @author s3curitybug@gmail.com * */ public final class VisualRepresentation { /** * Charset in which bases are encoded. */ public static final Charset BASES_ENCODING = StandardCharsets.UTF_8; /** * Printable ASCII base. */ public static final char[] PRINTABLE_ASCII_BASE = readBaseFromResources("printableAscii.base"); /** * Default base. */ public static final char[] DEFAULT_BASE = PRINTABLE_ASCII_BASE; /** * Default factor divisor. */ public static final int DEFAULT_FACTOR_DIVISOR = 3; /** * Default line wrap. */ public static final int DEFAULT_LINE_WRAP = 60; /** * Bases path inside resources. */ private static final String RESOURCES_BASES_PATH = "/VisualPrint/"; /** * Format in which accumulated wrap length per line will be formatted during a string wrap. */ private static final String ACCUMULATED_WRAP_FORMAT = "%5s %s"; /** * Format in which percent accumulated wrap length per line will be formatted during a string * wrap. */ private static final DecimalFormat ACCUMULATED_WRAP_DECIMAL_FORMAT = new DecimalFormat("0.0", DECIMALS_FORMAT_SYMBOLS); /** * ANSI format which will be used to visually represent the blocks which are only present in the * first hash in a comparison. */ private static final String BLOCK_IN_FIRST_HASH_ANSI_CODE_FORMAT =
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char ANSI_CODE_COLOR_END = 'm'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final DecimalFormatSymbols DECIMALS_FORMAT_SYMBOLS = // DecimalFormatSymbols.getInstance(Locale.ROOT); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char UNICODE_CTRL = '\u001b'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static String spaces( // int n) { // // return repeatString(" ", n); // // } // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected enum AnsiCodeColors { // // /** // * Red font color. // */ // RED_FONT(31), // // /** // * Green font color. // */ // GREEN_FONT(32), // // /** // * Blue font color. // */ // BLUE_FONT(34), // // /** // * Reset color. // */ // RESET(0); // // /** // * Color number. // */ // private int number; // // /** // * Color code. // */ // private String code; // // /** // * Constructor. // * // * @param number Color number. // */ // AnsiCodeColors( // int number) { // // this.number = number; // this.code = Character.toString(UNICODE_CTRL) // + Character.toString(ANSI_CODE_START) // + Integer.toString(number) // + Character.toString(ANSI_CODE_COLOR_END); // // } // // /** // * @return The color number. // */ // protected int getNumber() { // return number; // } // // /** // * @return The color code. // */ // protected String getCode() { // return code; // } // // /** // * Removes all ANSI code colors from a string. // * // * @param string A string. // * @return The string without any ANSI code colors. // */ // protected static String remove( // String string) { // // return ANSI_CODE_COLOR_PATTERN.matcher(string).replaceAll(""); // // } // // } // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/VisualRepresentation.java import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.ANSI_CODE_COLOR_END; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.DECIMALS_FORMAT_SYMBOLS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.UNICODE_CTRL; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.spaces; import org.apache.commons.io.IOUtils; import org.fusesource.jansi.AnsiConsole; import com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.AnsiCodeColors; import java.io.PrintStream; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; package com.github.s3curitybug.similarityuniformfuzzyhash; /** * This class provides utility static methods to represent and compare Uniform Fuzzy Hashes in * visual way. * * @author s3curitybug@gmail.com * */ public final class VisualRepresentation { /** * Charset in which bases are encoded. */ public static final Charset BASES_ENCODING = StandardCharsets.UTF_8; /** * Printable ASCII base. */ public static final char[] PRINTABLE_ASCII_BASE = readBaseFromResources("printableAscii.base"); /** * Default base. */ public static final char[] DEFAULT_BASE = PRINTABLE_ASCII_BASE; /** * Default factor divisor. */ public static final int DEFAULT_FACTOR_DIVISOR = 3; /** * Default line wrap. */ public static final int DEFAULT_LINE_WRAP = 60; /** * Bases path inside resources. */ private static final String RESOURCES_BASES_PATH = "/VisualPrint/"; /** * Format in which accumulated wrap length per line will be formatted during a string wrap. */ private static final String ACCUMULATED_WRAP_FORMAT = "%5s %s"; /** * Format in which percent accumulated wrap length per line will be formatted during a string * wrap. */ private static final DecimalFormat ACCUMULATED_WRAP_DECIMAL_FORMAT = new DecimalFormat("0.0", DECIMALS_FORMAT_SYMBOLS); /** * ANSI format which will be used to visually represent the blocks which are only present in the * first hash in a comparison. */ private static final String BLOCK_IN_FIRST_HASH_ANSI_CODE_FORMAT =
AnsiCodeColors.GREEN_FONT.getCode();
s3curitybug/similarity-uniform-fuzzy-hash
src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/VisualRepresentation.java
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char ANSI_CODE_COLOR_END = 'm'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final DecimalFormatSymbols DECIMALS_FORMAT_SYMBOLS = // DecimalFormatSymbols.getInstance(Locale.ROOT); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char UNICODE_CTRL = '\u001b'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static String spaces( // int n) { // // return repeatString(" ", n); // // } // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected enum AnsiCodeColors { // // /** // * Red font color. // */ // RED_FONT(31), // // /** // * Green font color. // */ // GREEN_FONT(32), // // /** // * Blue font color. // */ // BLUE_FONT(34), // // /** // * Reset color. // */ // RESET(0); // // /** // * Color number. // */ // private int number; // // /** // * Color code. // */ // private String code; // // /** // * Constructor. // * // * @param number Color number. // */ // AnsiCodeColors( // int number) { // // this.number = number; // this.code = Character.toString(UNICODE_CTRL) // + Character.toString(ANSI_CODE_START) // + Integer.toString(number) // + Character.toString(ANSI_CODE_COLOR_END); // // } // // /** // * @return The color number. // */ // protected int getNumber() { // return number; // } // // /** // * @return The color code. // */ // protected String getCode() { // return code; // } // // /** // * Removes all ANSI code colors from a string. // * // * @param string A string. // * @return The string without any ANSI code colors. // */ // protected static String remove( // String string) { // // return ANSI_CODE_COLOR_PATTERN.matcher(string).replaceAll(""); // // } // // }
import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.ANSI_CODE_COLOR_END; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.DECIMALS_FORMAT_SYMBOLS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.UNICODE_CTRL; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.spaces; import org.apache.commons.io.IOUtils; import org.fusesource.jansi.AnsiConsole; import com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.AnsiCodeColors; import java.io.PrintStream; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set;
* Uniform Fuzzy Hash with a different color to the ones which are not. * * @param hash1 The Uniform Fuzzy Hash. * @param hash2 The Uniform Fuzzy Hash to which the first one will be compared. * @param base The characters base which will be used to represent the blocks. * @param factorDivisor Amount of characters per factor size for each block. * @param lineWrap Amount of characters per line. If this argument is lower than 1, no line wrap * is performed and the full representation is printed in one line. * @param concatenatePercent In case line wrap is performed, true to concatenate to each line * its relative percent to the total length. */ public static void printCompared( UniformFuzzyHash hash1, UniformFuzzyHash hash2, char[] base, int factorDivisor, int lineWrap, boolean concatenatePercent) { // Representations. String representation1 = representCompared(hash1, hash2, base, factorDivisor); String representation2 = representCompared(hash2, hash1, base, factorDivisor).replace( BLOCK_IN_FIRST_HASH_ANSI_CODE_FORMAT, BLOCK_IN_SECOND_HASH_ANSI_CODE_FORMAT); List<String> wrappedRepresentation1 = wrapStringRespectingAnsiCodeFormat(representation1, lineWrap, concatenatePercent); List<String> wrappedRepresentation2 = wrapStringRespectingAnsiCodeFormat(representation2, lineWrap, concatenatePercent); String wrapLengthSpaces = concatenatePercent
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char ANSI_CODE_COLOR_END = 'm'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final DecimalFormatSymbols DECIMALS_FORMAT_SYMBOLS = // DecimalFormatSymbols.getInstance(Locale.ROOT); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char UNICODE_CTRL = '\u001b'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static String spaces( // int n) { // // return repeatString(" ", n); // // } // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected enum AnsiCodeColors { // // /** // * Red font color. // */ // RED_FONT(31), // // /** // * Green font color. // */ // GREEN_FONT(32), // // /** // * Blue font color. // */ // BLUE_FONT(34), // // /** // * Reset color. // */ // RESET(0); // // /** // * Color number. // */ // private int number; // // /** // * Color code. // */ // private String code; // // /** // * Constructor. // * // * @param number Color number. // */ // AnsiCodeColors( // int number) { // // this.number = number; // this.code = Character.toString(UNICODE_CTRL) // + Character.toString(ANSI_CODE_START) // + Integer.toString(number) // + Character.toString(ANSI_CODE_COLOR_END); // // } // // /** // * @return The color number. // */ // protected int getNumber() { // return number; // } // // /** // * @return The color code. // */ // protected String getCode() { // return code; // } // // /** // * Removes all ANSI code colors from a string. // * // * @param string A string. // * @return The string without any ANSI code colors. // */ // protected static String remove( // String string) { // // return ANSI_CODE_COLOR_PATTERN.matcher(string).replaceAll(""); // // } // // } // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/VisualRepresentation.java import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.ANSI_CODE_COLOR_END; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.DECIMALS_FORMAT_SYMBOLS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.UNICODE_CTRL; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.spaces; import org.apache.commons.io.IOUtils; import org.fusesource.jansi.AnsiConsole; import com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.AnsiCodeColors; import java.io.PrintStream; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; * Uniform Fuzzy Hash with a different color to the ones which are not. * * @param hash1 The Uniform Fuzzy Hash. * @param hash2 The Uniform Fuzzy Hash to which the first one will be compared. * @param base The characters base which will be used to represent the blocks. * @param factorDivisor Amount of characters per factor size for each block. * @param lineWrap Amount of characters per line. If this argument is lower than 1, no line wrap * is performed and the full representation is printed in one line. * @param concatenatePercent In case line wrap is performed, true to concatenate to each line * its relative percent to the total length. */ public static void printCompared( UniformFuzzyHash hash1, UniformFuzzyHash hash2, char[] base, int factorDivisor, int lineWrap, boolean concatenatePercent) { // Representations. String representation1 = representCompared(hash1, hash2, base, factorDivisor); String representation2 = representCompared(hash2, hash1, base, factorDivisor).replace( BLOCK_IN_FIRST_HASH_ANSI_CODE_FORMAT, BLOCK_IN_SECOND_HASH_ANSI_CODE_FORMAT); List<String> wrappedRepresentation1 = wrapStringRespectingAnsiCodeFormat(representation1, lineWrap, concatenatePercent); List<String> wrappedRepresentation2 = wrapStringRespectingAnsiCodeFormat(representation2, lineWrap, concatenatePercent); String wrapLengthSpaces = concatenatePercent
? spaces(lineWrap + formatAccumulatedWrapLength("", 0).length())
s3curitybug/similarity-uniform-fuzzy-hash
src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/VisualRepresentation.java
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char ANSI_CODE_COLOR_END = 'm'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final DecimalFormatSymbols DECIMALS_FORMAT_SYMBOLS = // DecimalFormatSymbols.getInstance(Locale.ROOT); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char UNICODE_CTRL = '\u001b'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static String spaces( // int n) { // // return repeatString(" ", n); // // } // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected enum AnsiCodeColors { // // /** // * Red font color. // */ // RED_FONT(31), // // /** // * Green font color. // */ // GREEN_FONT(32), // // /** // * Blue font color. // */ // BLUE_FONT(34), // // /** // * Reset color. // */ // RESET(0); // // /** // * Color number. // */ // private int number; // // /** // * Color code. // */ // private String code; // // /** // * Constructor. // * // * @param number Color number. // */ // AnsiCodeColors( // int number) { // // this.number = number; // this.code = Character.toString(UNICODE_CTRL) // + Character.toString(ANSI_CODE_START) // + Integer.toString(number) // + Character.toString(ANSI_CODE_COLOR_END); // // } // // /** // * @return The color number. // */ // protected int getNumber() { // return number; // } // // /** // * @return The color code. // */ // protected String getCode() { // return code; // } // // /** // * Removes all ANSI code colors from a string. // * // * @param string A string. // * @return The string without any ANSI code colors. // */ // protected static String remove( // String string) { // // return ANSI_CODE_COLOR_PATTERN.matcher(string).replaceAll(""); // // } // // }
import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.ANSI_CODE_COLOR_END; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.DECIMALS_FORMAT_SYMBOLS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.UNICODE_CTRL; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.spaces; import org.apache.commons.io.IOUtils; import org.fusesource.jansi.AnsiConsole; import com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.AnsiCodeColors; import java.io.PrintStream; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set;
* @return A List of strings containing the substrings, or a List of strings containing the * introduced string if wrapLength is lower than 1. */ private static List<String> wrapStringRespectingAnsiCodeFormat( String string, int wrapLength, boolean concatenatePercent) { if (string == null) { throw new NullPointerException("String is null."); } List<String> wrappedString = new LinkedList<>(); double relativeWrapLength = (double) wrapLength / AnsiCodeColors.remove(string).length(); double accumulatedWrapLength = 0; if (wrapLength < 1) { wrappedString.add(string); } else { StringBuilder substring = new StringBuilder(wrapLength * 2); StringBuilder ansiCodeFormat = new StringBuilder(); int substringChars = 0; for (int i = 0; i < string.length(); i++) { char ch = string.charAt(i);
// Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char ANSI_CODE_COLOR_END = 'm'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static final DecimalFormatSymbols DECIMALS_FORMAT_SYMBOLS = // DecimalFormatSymbols.getInstance(Locale.ROOT); // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected static final char UNICODE_CTRL = '\u001b'; // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // public static String spaces( // int n) { // // return repeatString(" ", n); // // } // // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/ToStringUtils.java // protected enum AnsiCodeColors { // // /** // * Red font color. // */ // RED_FONT(31), // // /** // * Green font color. // */ // GREEN_FONT(32), // // /** // * Blue font color. // */ // BLUE_FONT(34), // // /** // * Reset color. // */ // RESET(0); // // /** // * Color number. // */ // private int number; // // /** // * Color code. // */ // private String code; // // /** // * Constructor. // * // * @param number Color number. // */ // AnsiCodeColors( // int number) { // // this.number = number; // this.code = Character.toString(UNICODE_CTRL) // + Character.toString(ANSI_CODE_START) // + Integer.toString(number) // + Character.toString(ANSI_CODE_COLOR_END); // // } // // /** // * @return The color number. // */ // protected int getNumber() { // return number; // } // // /** // * @return The color code. // */ // protected String getCode() { // return code; // } // // /** // * Removes all ANSI code colors from a string. // * // * @param string A string. // * @return The string without any ANSI code colors. // */ // protected static String remove( // String string) { // // return ANSI_CODE_COLOR_PATTERN.matcher(string).replaceAll(""); // // } // // } // Path: src/main/java/com/github/s3curitybug/similarityuniformfuzzyhash/VisualRepresentation.java import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.ANSI_CODE_COLOR_END; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.DECIMALS_FORMAT_SYMBOLS; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.UNICODE_CTRL; import static com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.spaces; import org.apache.commons.io.IOUtils; import org.fusesource.jansi.AnsiConsole; import com.github.s3curitybug.similarityuniformfuzzyhash.ToStringUtils.AnsiCodeColors; import java.io.PrintStream; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; * @return A List of strings containing the substrings, or a List of strings containing the * introduced string if wrapLength is lower than 1. */ private static List<String> wrapStringRespectingAnsiCodeFormat( String string, int wrapLength, boolean concatenatePercent) { if (string == null) { throw new NullPointerException("String is null."); } List<String> wrappedString = new LinkedList<>(); double relativeWrapLength = (double) wrapLength / AnsiCodeColors.remove(string).length(); double accumulatedWrapLength = 0; if (wrapLength < 1) { wrappedString.add(string); } else { StringBuilder substring = new StringBuilder(wrapLength * 2); StringBuilder ansiCodeFormat = new StringBuilder(); int substringChars = 0; for (int i = 0; i < string.length(); i++) { char ch = string.charAt(i);
if (ch == UNICODE_CTRL) {