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 |
|---|---|---|---|---|---|---|
w3c/epubcheck | src/test/java/com/adobe/epubcheck/util/SourceSetTest.java | // Path: src/main/java/com/adobe/epubcheck/util/SourceSet.java
// public interface ErrorHandler
// {
// public void error(ParseError error, int position);
// }
//
// Path: src/main/java/com/adobe/epubcheck/util/SourceSet.java
// public static enum ParseError
// {
// NULL_OR_EMPTY,
// EMPTY_START,
// EMPTY_MIDDLE,
// DESCRIPTOR_MIX_WIDTH_DENSITY,
// DESCRIPTOR_DENSITY_MORE_THAN_ONCE,
// DESCRIPTOR_DENSITY_NEGATIVE,
// DESCRIPTOR_DENSITY_NOT_FLOAT,
// DESCRIPTOR_WIDTH_MORE_THAN_ONCE,
// DESCRIPTOR_WIDTH_SIGNED,
// DESCRIPTOR_WIDTH_NOT_INT,
// DESCRIPTOR_WIDTH_ZERO,
// DESCRIPTOR_FUTURE_H_ZERO,
// DESCRIPTOR_FUTURE_H_MORE_THAN_ONCE,
// DESCRIPTOR_FUTURE_H_NOT_INT,
// DESCRIPTOR_FUTURE_H_WITHOUT_WIDTH,
// DESCRIPTOR_FUTURE_H_WITH_DENSITY,
// DESCRIPTOR_UNKNOWN_SUFFIX,
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.adobe.epubcheck.util.SourceSet.ErrorHandler;
import com.adobe.epubcheck.util.SourceSet.ParseError; | package com.adobe.epubcheck.util;
public class SourceSetTest
{
private static class TestErrorHandler implements ErrorHandler
{ | // Path: src/main/java/com/adobe/epubcheck/util/SourceSet.java
// public interface ErrorHandler
// {
// public void error(ParseError error, int position);
// }
//
// Path: src/main/java/com/adobe/epubcheck/util/SourceSet.java
// public static enum ParseError
// {
// NULL_OR_EMPTY,
// EMPTY_START,
// EMPTY_MIDDLE,
// DESCRIPTOR_MIX_WIDTH_DENSITY,
// DESCRIPTOR_DENSITY_MORE_THAN_ONCE,
// DESCRIPTOR_DENSITY_NEGATIVE,
// DESCRIPTOR_DENSITY_NOT_FLOAT,
// DESCRIPTOR_WIDTH_MORE_THAN_ONCE,
// DESCRIPTOR_WIDTH_SIGNED,
// DESCRIPTOR_WIDTH_NOT_INT,
// DESCRIPTOR_WIDTH_ZERO,
// DESCRIPTOR_FUTURE_H_ZERO,
// DESCRIPTOR_FUTURE_H_MORE_THAN_ONCE,
// DESCRIPTOR_FUTURE_H_NOT_INT,
// DESCRIPTOR_FUTURE_H_WITHOUT_WIDTH,
// DESCRIPTOR_FUTURE_H_WITH_DENSITY,
// DESCRIPTOR_UNKNOWN_SUFFIX,
// }
// Path: src/test/java/com/adobe/epubcheck/util/SourceSetTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.adobe.epubcheck.util.SourceSet.ErrorHandler;
import com.adobe.epubcheck.util.SourceSet.ParseError;
package com.adobe.epubcheck.util;
public class SourceSetTest
{
private static class TestErrorHandler implements ErrorHandler
{ | private List<ParseError> errors = new LinkedList<>(); |
w3c/epubcheck | src/main/java/com/adobe/epubcheck/opf/OPFItem.java | // Path: src/main/java/com/adobe/epubcheck/vocab/PackageVocabs.java
// public final class PackageVocabs
// {
//
// public static final String ITEM_VOCAB_URI = "http://idpf.org/epub/vocab/package/item/#";
// public static final String ITEMREF_VOCAB_URI = "http://idpf.org/epub/vocab/package/itemref/#";
// public static final String LINK_VOCAB_URI = "http://idpf.org/epub/vocab/package/link/#";
// public static final String META_VOCAB_URI = "http://idpf.org/epub/vocab/package/meta/#";
//
// public static EnumVocab<META_PROPERTIES> META_VOCAB = new EnumVocab<META_PROPERTIES>(
// META_PROPERTIES.class, META_VOCAB_URI);
//
// public static enum META_PROPERTIES
// {
// ALTERNATE_SCRIPT,
// AUTHORITY,
// BELONGS_TO_COLLECTION,
// COLLECTION_TYPE,
// DISPLAY_SEQ,
// DICTIONARY_TYPE, // DICT
// FILE_AS,
// GROUP_POSITION,
// IDENTIFIER_TYPE,
// META_AUTH,
// ROLE,
// SOURCE_LANGUAGE, // DICT
// SOURCE_OF,
// TARGET_LANGUAGE, // DICT
// TERM,
// TITLE_TYPE
// }
//
// public static EnumVocab<ITEM_PROPERTIES> ITEM_VOCAB = new EnumVocab<ITEM_PROPERTIES>(
// ITEM_PROPERTIES.class, ITEM_VOCAB_URI);
//
// public static enum ITEM_PROPERTIES
// {
// COVER_IMAGE("image/gif", "image/jpeg", "image/png", "image/svg+xml"),
// DATA_NAV("application/xhtml+xml"),
// DICTIONARY("application/vnd.epub.search-key-map+xml"),
// GLOSSARY("application/vnd.epub.search-key-map+xml", "application/xhtml+xml"),
// INDEX("application/xhtml+xml"),
// MATHML("application/xhtml+xml", "image/svg+xml"),
// NAV("application/xhtml+xml"),
// REMOTE_RESOURCES("application/xhtml+xml", "application/smil+xml", "image/svg+xml", "text/css"),
// SCRIPTED("application/xhtml+xml", "image/svg+xml"),
// SEARCH_KEY_MAP("application/vnd.epub.search-key-map+xml"),
// SVG("application/xhtml+xml"),
// SWITCH("application/xhtml+xml", "image/svg+xml");
//
// private final Set<String> types;
//
// private ITEM_PROPERTIES(String... types)
// {
// this.types = new ImmutableSet.Builder<String>().add(types).build();
// }
//
// public Set<String> allowedOnTypes()
// {
// return types;
// }
// }
//
// public static EnumVocab<ITEMREF_PROPERTIES> ITEMREF_VOCAB = new EnumVocab<ITEMREF_PROPERTIES>(
// ITEMREF_PROPERTIES.class, ITEMREF_VOCAB_URI);
//
// public static enum ITEMREF_PROPERTIES
// {
// PAGE_SPREAD_RIGHT,
// PAGE_SPREAD_LEFT
// }
//
// public static EnumVocab<LINKREL_PROPERTIES> LINKREL_VOCAB = new EnumVocab<LINKREL_PROPERTIES>(
// LINKREL_PROPERTIES.class, LINK_VOCAB_URI);
//
// public static enum LINKREL_PROPERTIES implements PropertyStatus
// {
// ACQUIRE,
// ALTERNATE,
// MARC21XML_RECORD(DEPRECATED),
// MODS_RECORD(DEPRECATED),
// ONIX_RECORD(DEPRECATED),
// RECORD,
// VOICING,
// XML_SIGNATURE(DEPRECATED),
// XMP_RECORD(DEPRECATED);
//
// private final PropertyStatus status;
//
// private LINKREL_PROPERTIES()
// {
// this(ALLOWED);
// }
//
// private LINKREL_PROPERTIES(PropertyStatus status)
// {
// this.status = Preconditions.checkNotNull(status);
// }
//
// @Override
// public boolean isAllowed(ValidationContext context)
// {
// return status.isAllowed(context);
// }
//
// @Override
// public boolean isDeprecated()
// {
// return status.isDeprecated();
// }
// }
//
// public static EnumVocab<LINK_PROPERTIES> LINK_VOCAB = new EnumVocab<LINK_PROPERTIES>(
// LINK_PROPERTIES.class, LINK_VOCAB_URI);
//
// public static enum LINK_PROPERTIES
// {
// ONIX,
// XMP;
// }
//
// private PackageVocabs()
// {
// }
// }
| import com.google.common.collect.ImmutableSet;
import java.util.Set;
import com.adobe.epubcheck.vocab.EpubCheckVocab;
import com.adobe.epubcheck.vocab.PackageVocabs;
import com.adobe.epubcheck.vocab.Property;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings; |
public Builder properties(Set<Property> properties)
{
if (properties != null)
{
this.propertiesBuilder.addAll(properties);
}
return this;
}
/**
* Builds a new immutable {@link OPFItem} from this builder.
*/
public OPFItem build()
{
if (spinePosition < 0 || !linear)
{
this.propertiesBuilder.add(EpubCheckVocab.VOCAB.get(EpubCheckVocab.PROPERTIES.NON_LINEAR));
}
if (fxl)
{
this.propertiesBuilder
.add(EpubCheckVocab.VOCAB.get(EpubCheckVocab.PROPERTIES.FIXED_LAYOUT));
}
Set<Property> properties = propertiesBuilder.build();
return new OPFItem(id, path, mimeType, lineNumber, columnNumber,
Optional.fromNullable(Strings.emptyToNull(Strings.nullToEmpty(fallback).trim())),
Optional.fromNullable(Strings.emptyToNull(Strings.nullToEmpty(fallbackStyle).trim())),
properties, ncx, spinePosition, | // Path: src/main/java/com/adobe/epubcheck/vocab/PackageVocabs.java
// public final class PackageVocabs
// {
//
// public static final String ITEM_VOCAB_URI = "http://idpf.org/epub/vocab/package/item/#";
// public static final String ITEMREF_VOCAB_URI = "http://idpf.org/epub/vocab/package/itemref/#";
// public static final String LINK_VOCAB_URI = "http://idpf.org/epub/vocab/package/link/#";
// public static final String META_VOCAB_URI = "http://idpf.org/epub/vocab/package/meta/#";
//
// public static EnumVocab<META_PROPERTIES> META_VOCAB = new EnumVocab<META_PROPERTIES>(
// META_PROPERTIES.class, META_VOCAB_URI);
//
// public static enum META_PROPERTIES
// {
// ALTERNATE_SCRIPT,
// AUTHORITY,
// BELONGS_TO_COLLECTION,
// COLLECTION_TYPE,
// DISPLAY_SEQ,
// DICTIONARY_TYPE, // DICT
// FILE_AS,
// GROUP_POSITION,
// IDENTIFIER_TYPE,
// META_AUTH,
// ROLE,
// SOURCE_LANGUAGE, // DICT
// SOURCE_OF,
// TARGET_LANGUAGE, // DICT
// TERM,
// TITLE_TYPE
// }
//
// public static EnumVocab<ITEM_PROPERTIES> ITEM_VOCAB = new EnumVocab<ITEM_PROPERTIES>(
// ITEM_PROPERTIES.class, ITEM_VOCAB_URI);
//
// public static enum ITEM_PROPERTIES
// {
// COVER_IMAGE("image/gif", "image/jpeg", "image/png", "image/svg+xml"),
// DATA_NAV("application/xhtml+xml"),
// DICTIONARY("application/vnd.epub.search-key-map+xml"),
// GLOSSARY("application/vnd.epub.search-key-map+xml", "application/xhtml+xml"),
// INDEX("application/xhtml+xml"),
// MATHML("application/xhtml+xml", "image/svg+xml"),
// NAV("application/xhtml+xml"),
// REMOTE_RESOURCES("application/xhtml+xml", "application/smil+xml", "image/svg+xml", "text/css"),
// SCRIPTED("application/xhtml+xml", "image/svg+xml"),
// SEARCH_KEY_MAP("application/vnd.epub.search-key-map+xml"),
// SVG("application/xhtml+xml"),
// SWITCH("application/xhtml+xml", "image/svg+xml");
//
// private final Set<String> types;
//
// private ITEM_PROPERTIES(String... types)
// {
// this.types = new ImmutableSet.Builder<String>().add(types).build();
// }
//
// public Set<String> allowedOnTypes()
// {
// return types;
// }
// }
//
// public static EnumVocab<ITEMREF_PROPERTIES> ITEMREF_VOCAB = new EnumVocab<ITEMREF_PROPERTIES>(
// ITEMREF_PROPERTIES.class, ITEMREF_VOCAB_URI);
//
// public static enum ITEMREF_PROPERTIES
// {
// PAGE_SPREAD_RIGHT,
// PAGE_SPREAD_LEFT
// }
//
// public static EnumVocab<LINKREL_PROPERTIES> LINKREL_VOCAB = new EnumVocab<LINKREL_PROPERTIES>(
// LINKREL_PROPERTIES.class, LINK_VOCAB_URI);
//
// public static enum LINKREL_PROPERTIES implements PropertyStatus
// {
// ACQUIRE,
// ALTERNATE,
// MARC21XML_RECORD(DEPRECATED),
// MODS_RECORD(DEPRECATED),
// ONIX_RECORD(DEPRECATED),
// RECORD,
// VOICING,
// XML_SIGNATURE(DEPRECATED),
// XMP_RECORD(DEPRECATED);
//
// private final PropertyStatus status;
//
// private LINKREL_PROPERTIES()
// {
// this(ALLOWED);
// }
//
// private LINKREL_PROPERTIES(PropertyStatus status)
// {
// this.status = Preconditions.checkNotNull(status);
// }
//
// @Override
// public boolean isAllowed(ValidationContext context)
// {
// return status.isAllowed(context);
// }
//
// @Override
// public boolean isDeprecated()
// {
// return status.isDeprecated();
// }
// }
//
// public static EnumVocab<LINK_PROPERTIES> LINK_VOCAB = new EnumVocab<LINK_PROPERTIES>(
// LINK_PROPERTIES.class, LINK_VOCAB_URI);
//
// public static enum LINK_PROPERTIES
// {
// ONIX,
// XMP;
// }
//
// private PackageVocabs()
// {
// }
// }
// Path: src/main/java/com/adobe/epubcheck/opf/OPFItem.java
import com.google.common.collect.ImmutableSet;
import java.util.Set;
import com.adobe.epubcheck.vocab.EpubCheckVocab;
import com.adobe.epubcheck.vocab.PackageVocabs;
import com.adobe.epubcheck.vocab.Property;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
public Builder properties(Set<Property> properties)
{
if (properties != null)
{
this.propertiesBuilder.addAll(properties);
}
return this;
}
/**
* Builds a new immutable {@link OPFItem} from this builder.
*/
public OPFItem build()
{
if (spinePosition < 0 || !linear)
{
this.propertiesBuilder.add(EpubCheckVocab.VOCAB.get(EpubCheckVocab.PROPERTIES.NON_LINEAR));
}
if (fxl)
{
this.propertiesBuilder
.add(EpubCheckVocab.VOCAB.get(EpubCheckVocab.PROPERTIES.FIXED_LAYOUT));
}
Set<Property> properties = propertiesBuilder.build();
return new OPFItem(id, path, mimeType, lineNumber, columnNumber,
Optional.fromNullable(Strings.emptyToNull(Strings.nullToEmpty(fallback).trim())),
Optional.fromNullable(Strings.emptyToNull(Strings.nullToEmpty(fallbackStyle).trim())),
properties, ncx, spinePosition, | properties.contains(PackageVocabs.ITEM_VOCAB.get(PackageVocabs.ITEM_PROPERTIES.NAV)), |
w3c/epubcheck | src/test/java/com/adobe/epubcheck/ocf/OCFFilenameCheckerTest.java | // Path: src/main/java/com/adobe/epubcheck/api/EPUBProfile.java
// public enum EPUBProfile
// {
// DEFAULT,
// IDX,
// DICT,
// EDUPUB,
// PREVIEW;
//
// /**
// * Checks a given validation profile against the dc:type(s) declared in an OPF
// * and returns a possibly overriden profile.
// * <p>
// * For instance, if the publication has a 'edupub' dc:type and the DEFAULT
// * validation profile is given, the EDUPUB profile will be returned instead.
// * </p>
// * <p>
// * If the given validation profile is modified, report an INFO message
// * OPF_064.
// * </p>
// *
// * @param profile
// * a validation profile.
// * @param opfData
// * the parsed OPF data (contains the publication's dc:type(s)).
// * @param path
// * the path to use for reporting messages.
// * @param report
// * the message report.
// * @return The given profile if it's compatible with the OPF dc:type(s), or
// * else a compatible non-null validation profile.
// */
// public static EPUBProfile makeOPFCompatible(EPUBProfile profile, OPFData opfData, String path,
// Report report)
// {
//
// Set<String> pubTypes = opfData != null ? opfData.getTypes() : ImmutableSet.<String> of();
// if (pubTypes.contains(OPFData.DC_TYPE_DICT) && profile != EPUBProfile.DICT)
// {
// report.message(MessageId.OPF_064, EPUBLocation.create(path), OPFData.DC_TYPE_DICT,
// EPUBProfile.DICT);
// return EPUBProfile.DICT;
// }
// else if (pubTypes.contains(OPFData.DC_TYPE_EDUPUB) && profile != EPUBProfile.EDUPUB)
// {
// report.message(MessageId.OPF_064, EPUBLocation.create(path), OPFData.DC_TYPE_EDUPUB,
// EPUBProfile.EDUPUB);
// return EPUBProfile.EDUPUB;
// }
// else if (pubTypes.contains(OPFData.DC_TYPE_INDEX) && profile != EPUBProfile.IDX)
// {
// report.message(MessageId.OPF_064, EPUBLocation.create(path), OPFData.DC_TYPE_INDEX,
// EPUBProfile.IDX);
// return EPUBProfile.IDX;
// }
// else if (pubTypes.contains(OPFData.DC_TYPE_PREVIEW) && profile != EPUBProfile.PREVIEW)
// {
// report.message(MessageId.OPF_064, EPUBLocation.create(path), OPFData.DC_TYPE_PREVIEW,
// EPUBProfile.PREVIEW);
// return EPUBProfile.PREVIEW;
// }
// else
// {
// return profile != null ? profile : EPUBProfile.DEFAULT;
// }
// }
// }
| import com.adobe.epubcheck.util.outWriter;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.adobe.epubcheck.api.EPUBProfile;
import com.adobe.epubcheck.util.EPUBVersion;
import com.adobe.epubcheck.util.Messages;
import com.adobe.epubcheck.util.ValidationReport; | /*
* Copyright (c) 2011 Adobe Systems Incorporated
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package com.adobe.epubcheck.ocf;
public class OCFFilenameCheckerTest
{
private ValidationReport testReport;
private boolean verbose = false;
private final Messages messages = Messages.getInstance();
/*
* TEST DEBUG FUNCTION
*/
public void testValidateDocument(String fileName, String expected,
EPUBVersion version, boolean verbose)
{
if (verbose)
{
this.verbose = verbose;
}
testValidateDocument(fileName, expected, version);
}
public void testValidateDocument(String fileName, String expected,
EPUBVersion version)
{
testReport = new ValidationReport(fileName, String.format( | // Path: src/main/java/com/adobe/epubcheck/api/EPUBProfile.java
// public enum EPUBProfile
// {
// DEFAULT,
// IDX,
// DICT,
// EDUPUB,
// PREVIEW;
//
// /**
// * Checks a given validation profile against the dc:type(s) declared in an OPF
// * and returns a possibly overriden profile.
// * <p>
// * For instance, if the publication has a 'edupub' dc:type and the DEFAULT
// * validation profile is given, the EDUPUB profile will be returned instead.
// * </p>
// * <p>
// * If the given validation profile is modified, report an INFO message
// * OPF_064.
// * </p>
// *
// * @param profile
// * a validation profile.
// * @param opfData
// * the parsed OPF data (contains the publication's dc:type(s)).
// * @param path
// * the path to use for reporting messages.
// * @param report
// * the message report.
// * @return The given profile if it's compatible with the OPF dc:type(s), or
// * else a compatible non-null validation profile.
// */
// public static EPUBProfile makeOPFCompatible(EPUBProfile profile, OPFData opfData, String path,
// Report report)
// {
//
// Set<String> pubTypes = opfData != null ? opfData.getTypes() : ImmutableSet.<String> of();
// if (pubTypes.contains(OPFData.DC_TYPE_DICT) && profile != EPUBProfile.DICT)
// {
// report.message(MessageId.OPF_064, EPUBLocation.create(path), OPFData.DC_TYPE_DICT,
// EPUBProfile.DICT);
// return EPUBProfile.DICT;
// }
// else if (pubTypes.contains(OPFData.DC_TYPE_EDUPUB) && profile != EPUBProfile.EDUPUB)
// {
// report.message(MessageId.OPF_064, EPUBLocation.create(path), OPFData.DC_TYPE_EDUPUB,
// EPUBProfile.EDUPUB);
// return EPUBProfile.EDUPUB;
// }
// else if (pubTypes.contains(OPFData.DC_TYPE_INDEX) && profile != EPUBProfile.IDX)
// {
// report.message(MessageId.OPF_064, EPUBLocation.create(path), OPFData.DC_TYPE_INDEX,
// EPUBProfile.IDX);
// return EPUBProfile.IDX;
// }
// else if (pubTypes.contains(OPFData.DC_TYPE_PREVIEW) && profile != EPUBProfile.PREVIEW)
// {
// report.message(MessageId.OPF_064, EPUBLocation.create(path), OPFData.DC_TYPE_PREVIEW,
// EPUBProfile.PREVIEW);
// return EPUBProfile.PREVIEW;
// }
// else
// {
// return profile != null ? profile : EPUBProfile.DEFAULT;
// }
// }
// }
// Path: src/test/java/com/adobe/epubcheck/ocf/OCFFilenameCheckerTest.java
import com.adobe.epubcheck.util.outWriter;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.adobe.epubcheck.api.EPUBProfile;
import com.adobe.epubcheck.util.EPUBVersion;
import com.adobe.epubcheck.util.Messages;
import com.adobe.epubcheck.util.ValidationReport;
/*
* Copyright (c) 2011 Adobe Systems Incorporated
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package com.adobe.epubcheck.ocf;
public class OCFFilenameCheckerTest
{
private ValidationReport testReport;
private boolean verbose = false;
private final Messages messages = Messages.getInstance();
/*
* TEST DEBUG FUNCTION
*/
public void testValidateDocument(String fileName, String expected,
EPUBVersion version, boolean verbose)
{
if (verbose)
{
this.verbose = verbose;
}
testValidateDocument(fileName, expected, version);
}
public void testValidateDocument(String fileName, String expected,
EPUBVersion version)
{
testReport = new ValidationReport(fileName, String.format( | messages.get("single_file"), "opf", version.toString(), EPUBProfile.DEFAULT)); |
lalithsuresh/rapid | rapid/src/test/java/com/vrg/rapid/StaticFailureDetector.java | // Path: rapid/src/main/java/com/vrg/rapid/monitoring/IEdgeFailureDetectorFactory.java
// @ExperimentalApi
// public interface IEdgeFailureDetectorFactory {
// Runnable createInstance(final Endpoint subject, final Runnable notifier);
// }
| import com.vrg.rapid.monitoring.IEdgeFailureDetectorFactory;
import java.util.Set;
import com.vrg.rapid.pb.Endpoint; | /*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Used for testing.
*/
class StaticFailureDetector implements Runnable {
private final Set<Endpoint> failedNodes;
private final Endpoint subject;
private final Runnable notifier;
private StaticFailureDetector(final Endpoint subject, final Runnable notifier,
final Set<Endpoint> blackList) {
this.subject = subject;
this.notifier = notifier;
this.failedNodes = blackList;
}
private boolean hasFailed() {
return failedNodes.contains(subject);
}
@Override
public void run() {
if (hasFailed()) {
notifier.run();
}
}
| // Path: rapid/src/main/java/com/vrg/rapid/monitoring/IEdgeFailureDetectorFactory.java
// @ExperimentalApi
// public interface IEdgeFailureDetectorFactory {
// Runnable createInstance(final Endpoint subject, final Runnable notifier);
// }
// Path: rapid/src/test/java/com/vrg/rapid/StaticFailureDetector.java
import com.vrg.rapid.monitoring.IEdgeFailureDetectorFactory;
import java.util.Set;
import com.vrg.rapid.pb.Endpoint;
/*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Used for testing.
*/
class StaticFailureDetector implements Runnable {
private final Set<Endpoint> failedNodes;
private final Endpoint subject;
private final Runnable notifier;
private StaticFailureDetector(final Endpoint subject, final Runnable notifier,
final Set<Endpoint> blackList) {
this.subject = subject;
this.notifier = notifier;
this.failedNodes = blackList;
}
private boolean hasFailed() {
return failedNodes.contains(subject);
}
@Override
public void run() {
if (hasFailed()) {
notifier.run();
}
}
| static class Factory implements IEdgeFailureDetectorFactory { |
lalithsuresh/rapid | rapid/src/test/java/com/vrg/rapid/PaxosTests.java | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
| import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.pb.ConsensusResponse;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.Phase1bMessage;
import com.vrg.rapid.pb.Rank;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import junitparams.naming.TestCaseName;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | final ArrayList<Object[]> params = new ArrayList<>();
params.addAll(coordinatorTestCases);
return params;
}
/**
* Creates a set of #numNodes Paxos instances, and prepares a single threaded executor that serializes
* messages to each instance (in line with how Rapid messages are serialized).
*/
private Map<Endpoint, FastPaxos> createNFastPaxosInstances(final int numNodes,
final Consumer<List<Endpoint>> onDecide) {
final Map<Endpoint, FastPaxos> instances = new ConcurrentHashMap<>();
final Map<Endpoint, ExecutorService> executorServiceMap = new ConcurrentHashMap<>();
final DirectMessagingClient messagingClient = new DirectMessagingClient(instances, executorServiceMap);
final DirectBroadcaster directBroadcaster = new DirectBroadcaster(instances, messagingClient);
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(numNodes);
final FastPaxos.ISettings settings = new Settings();
for (int i = 0; i < numNodes; i++) {
final Endpoint addr = Utils.hostFromParts("127.0.0.1", 1234 + i);
executorServiceMap.put(addr, Executors.newSingleThreadExecutor());
final FastPaxos paxos = new FastPaxos(addr, 1, numNodes, messagingClient, directBroadcaster,
scheduler, onDecide, settings);
instances.put(addr, paxos);
}
return instances;
}
/**
* Directly wires Paxos messages to the instances.
*/ | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
// Path: rapid/src/test/java/com/vrg/rapid/PaxosTests.java
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.pb.ConsensusResponse;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.Phase1bMessage;
import com.vrg.rapid.pb.Rank;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import junitparams.naming.TestCaseName;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
final ArrayList<Object[]> params = new ArrayList<>();
params.addAll(coordinatorTestCases);
return params;
}
/**
* Creates a set of #numNodes Paxos instances, and prepares a single threaded executor that serializes
* messages to each instance (in line with how Rapid messages are serialized).
*/
private Map<Endpoint, FastPaxos> createNFastPaxosInstances(final int numNodes,
final Consumer<List<Endpoint>> onDecide) {
final Map<Endpoint, FastPaxos> instances = new ConcurrentHashMap<>();
final Map<Endpoint, ExecutorService> executorServiceMap = new ConcurrentHashMap<>();
final DirectMessagingClient messagingClient = new DirectMessagingClient(instances, executorServiceMap);
final DirectBroadcaster directBroadcaster = new DirectBroadcaster(instances, messagingClient);
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(numNodes);
final FastPaxos.ISettings settings = new Settings();
for (int i = 0; i < numNodes; i++) {
final Endpoint addr = Utils.hostFromParts("127.0.0.1", 1234 + i);
executorServiceMap.put(addr, Executors.newSingleThreadExecutor());
final FastPaxos paxos = new FastPaxos(addr, 1, numNodes, messagingClient, directBroadcaster,
scheduler, onDecide, settings);
instances.put(addr, paxos);
}
return instances;
}
/**
* Directly wires Paxos messages to the instances.
*/ | private class DirectBroadcaster implements IBroadcaster { |
lalithsuresh/rapid | rapid/src/test/java/com/vrg/rapid/PaxosTests.java | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
| import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.pb.ConsensusResponse;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.Phase1bMessage;
import com.vrg.rapid.pb.Rank;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import junitparams.naming.TestCaseName;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | return params;
}
/**
* Creates a set of #numNodes Paxos instances, and prepares a single threaded executor that serializes
* messages to each instance (in line with how Rapid messages are serialized).
*/
private Map<Endpoint, FastPaxos> createNFastPaxosInstances(final int numNodes,
final Consumer<List<Endpoint>> onDecide) {
final Map<Endpoint, FastPaxos> instances = new ConcurrentHashMap<>();
final Map<Endpoint, ExecutorService> executorServiceMap = new ConcurrentHashMap<>();
final DirectMessagingClient messagingClient = new DirectMessagingClient(instances, executorServiceMap);
final DirectBroadcaster directBroadcaster = new DirectBroadcaster(instances, messagingClient);
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(numNodes);
final FastPaxos.ISettings settings = new Settings();
for (int i = 0; i < numNodes; i++) {
final Endpoint addr = Utils.hostFromParts("127.0.0.1", 1234 + i);
executorServiceMap.put(addr, Executors.newSingleThreadExecutor());
final FastPaxos paxos = new FastPaxos(addr, 1, numNodes, messagingClient, directBroadcaster,
scheduler, onDecide, settings);
instances.put(addr, paxos);
}
return instances;
}
/**
* Directly wires Paxos messages to the instances.
*/
private class DirectBroadcaster implements IBroadcaster {
private final Map<Endpoint, FastPaxos> paxosInstances; | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
// Path: rapid/src/test/java/com/vrg/rapid/PaxosTests.java
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.pb.ConsensusResponse;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.Phase1bMessage;
import com.vrg.rapid.pb.Rank;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import junitparams.naming.TestCaseName;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
return params;
}
/**
* Creates a set of #numNodes Paxos instances, and prepares a single threaded executor that serializes
* messages to each instance (in line with how Rapid messages are serialized).
*/
private Map<Endpoint, FastPaxos> createNFastPaxosInstances(final int numNodes,
final Consumer<List<Endpoint>> onDecide) {
final Map<Endpoint, FastPaxos> instances = new ConcurrentHashMap<>();
final Map<Endpoint, ExecutorService> executorServiceMap = new ConcurrentHashMap<>();
final DirectMessagingClient messagingClient = new DirectMessagingClient(instances, executorServiceMap);
final DirectBroadcaster directBroadcaster = new DirectBroadcaster(instances, messagingClient);
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(numNodes);
final FastPaxos.ISettings settings = new Settings();
for (int i = 0; i < numNodes; i++) {
final Endpoint addr = Utils.hostFromParts("127.0.0.1", 1234 + i);
executorServiceMap.put(addr, Executors.newSingleThreadExecutor());
final FastPaxos paxos = new FastPaxos(addr, 1, numNodes, messagingClient, directBroadcaster,
scheduler, onDecide, settings);
instances.put(addr, paxos);
}
return instances;
}
/**
* Directly wires Paxos messages to the instances.
*/
private class DirectBroadcaster implements IBroadcaster {
private final Map<Endpoint, FastPaxos> paxosInstances; | private final IMessagingClient messagingClient; |
lalithsuresh/rapid | rapid/src/main/java/com/vrg/rapid/Paxos.java | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
| import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.Phase1aMessage;
import com.vrg.rapid.pb.Phase1bMessage;
import com.vrg.rapid.pb.Phase2aMessage;
import com.vrg.rapid.pb.Phase2bMessage;
import com.vrg.rapid.pb.Rank;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors; | /*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Single-decree consensus. Implements classic Paxos with the modified rule for the coordinator to pick values as per
* the Fast Paxos paper: https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-2005-112.pdf
*
* The code below assumes that the first round in a consensus instance (done per configuration change) is the
* only round that is a fast round. A round is identified by a tuple (rnd-number, nodeId), where nodeId is a unique
* identifier per node that initiates phase1.
*/
@NotThreadSafe
class Paxos {
private static final Logger LOG = LoggerFactory.getLogger(Paxos.class);
| // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
// Path: rapid/src/main/java/com/vrg/rapid/Paxos.java
import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.Phase1aMessage;
import com.vrg.rapid.pb.Phase1bMessage;
import com.vrg.rapid.pb.Phase2aMessage;
import com.vrg.rapid.pb.Phase2bMessage;
import com.vrg.rapid.pb.Rank;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Single-decree consensus. Implements classic Paxos with the modified rule for the coordinator to pick values as per
* the Fast Paxos paper: https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-2005-112.pdf
*
* The code below assumes that the first round in a consensus instance (done per configuration change) is the
* only round that is a fast round. A round is identified by a tuple (rnd-number, nodeId), where nodeId is a unique
* identifier per node that initiates phase1.
*/
@NotThreadSafe
class Paxos {
private static final Logger LOG = LoggerFactory.getLogger(Paxos.class);
| private final IBroadcaster broadcaster; |
lalithsuresh/rapid | rapid/src/main/java/com/vrg/rapid/Paxos.java | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
| import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.Phase1aMessage;
import com.vrg.rapid.pb.Phase1bMessage;
import com.vrg.rapid.pb.Phase2aMessage;
import com.vrg.rapid.pb.Phase2bMessage;
import com.vrg.rapid.pb.Rank;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors; | /*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Single-decree consensus. Implements classic Paxos with the modified rule for the coordinator to pick values as per
* the Fast Paxos paper: https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-2005-112.pdf
*
* The code below assumes that the first round in a consensus instance (done per configuration change) is the
* only round that is a fast round. A round is identified by a tuple (rnd-number, nodeId), where nodeId is a unique
* identifier per node that initiates phase1.
*/
@NotThreadSafe
class Paxos {
private static final Logger LOG = LoggerFactory.getLogger(Paxos.class);
private final IBroadcaster broadcaster; | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
// Path: rapid/src/main/java/com/vrg/rapid/Paxos.java
import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.Phase1aMessage;
import com.vrg.rapid.pb.Phase1bMessage;
import com.vrg.rapid.pb.Phase2aMessage;
import com.vrg.rapid.pb.Phase2bMessage;
import com.vrg.rapid.pb.Rank;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Single-decree consensus. Implements classic Paxos with the modified rule for the coordinator to pick values as per
* the Fast Paxos paper: https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-2005-112.pdf
*
* The code below assumes that the first round in a consensus instance (done per configuration change) is the
* only round that is a fast round. A round is identified by a tuple (rnd-number, nodeId), where nodeId is a unique
* identifier per node that initiates phase1.
*/
@NotThreadSafe
class Paxos {
private static final Logger LOG = LoggerFactory.getLogger(Paxos.class);
private final IBroadcaster broadcaster; | private final IMessagingClient client; |
lalithsuresh/rapid | rapid/src/main/java/com/vrg/rapid/monitoring/impl/PingPongFailureDetector.java | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/monitoring/IEdgeFailureDetectorFactory.java
// @ExperimentalApi
// public interface IEdgeFailureDetectorFactory {
// Runnable createInstance(final Endpoint subject, final Runnable notifier);
// }
| import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.MoreExecutors;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.monitoring.IEdgeFailureDetectorFactory;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.NodeStatus;
import com.vrg.rapid.pb.ProbeMessage;
import com.vrg.rapid.pb.ProbeResponse;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.concurrent.atomic.AtomicInteger; | /*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid.monitoring.impl;
/**
* Represents a simple ping-pong failure detector. It is also aware of nodes that are added to the cluster
* but are still bootstrapping.
*/
@NotThreadSafe
public class PingPongFailureDetector implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(PingPongFailureDetector.class);
private static final int FAILURE_THRESHOLD = 10;
// Number of BOOTSTRAPPING status responses a node is allowed to return before we begin
// treating that as a failure condition.
private static final int BOOTSTRAP_COUNT_THRESHOLD = 30;
private final Endpoint address;
private final Endpoint subject;
private final AtomicInteger failureCount;
private final AtomicInteger bootstrapResponseCount; | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/monitoring/IEdgeFailureDetectorFactory.java
// @ExperimentalApi
// public interface IEdgeFailureDetectorFactory {
// Runnable createInstance(final Endpoint subject, final Runnable notifier);
// }
// Path: rapid/src/main/java/com/vrg/rapid/monitoring/impl/PingPongFailureDetector.java
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.MoreExecutors;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.monitoring.IEdgeFailureDetectorFactory;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.NodeStatus;
import com.vrg.rapid.pb.ProbeMessage;
import com.vrg.rapid.pb.ProbeResponse;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.concurrent.atomic.AtomicInteger;
/*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid.monitoring.impl;
/**
* Represents a simple ping-pong failure detector. It is also aware of nodes that are added to the cluster
* but are still bootstrapping.
*/
@NotThreadSafe
public class PingPongFailureDetector implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(PingPongFailureDetector.class);
private static final int FAILURE_THRESHOLD = 10;
// Number of BOOTSTRAPPING status responses a node is allowed to return before we begin
// treating that as a failure condition.
private static final int BOOTSTRAP_COUNT_THRESHOLD = 30;
private final Endpoint address;
private final Endpoint subject;
private final AtomicInteger failureCount;
private final AtomicInteger bootstrapResponseCount; | private final IMessagingClient rpcClient; |
lalithsuresh/rapid | rapid/src/main/java/com/vrg/rapid/monitoring/impl/PingPongFailureDetector.java | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/monitoring/IEdgeFailureDetectorFactory.java
// @ExperimentalApi
// public interface IEdgeFailureDetectorFactory {
// Runnable createInstance(final Endpoint subject, final Runnable notifier);
// }
| import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.MoreExecutors;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.monitoring.IEdgeFailureDetectorFactory;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.NodeStatus;
import com.vrg.rapid.pb.ProbeMessage;
import com.vrg.rapid.pb.ProbeResponse;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.concurrent.atomic.AtomicInteger; | return;
}
final ProbeResponse probeResponse = response.getProbeResponse();
if (probeResponse.getStatus().equals(NodeStatus.BOOTSTRAPPING)) {
final int numBootstrapResponses = bootstrapResponseCount.incrementAndGet();
if (numBootstrapResponses > BOOTSTRAP_COUNT_THRESHOLD) {
handleProbeOnFailure(new RuntimeException("BOOTSTRAP_COUNT_THRESHOLD exceeded"));
return;
}
}
handleProbeOnSuccess();
}
@Override
public void onFailure(final Throwable throwable) {
handleProbeOnFailure(throwable);
}
// Executed at observer
private void handleProbeOnSuccess() {
LOG.trace("handleProbeOnSuccess at {} from {}", address, subject);
}
// Executed at observer
private void handleProbeOnFailure(final Throwable throwable) {
failureCount.incrementAndGet();
LOG.trace("handleProbeOnFailure at {} from {}: {}", address, subject, throwable.getLocalizedMessage());
}
}
| // Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/monitoring/IEdgeFailureDetectorFactory.java
// @ExperimentalApi
// public interface IEdgeFailureDetectorFactory {
// Runnable createInstance(final Endpoint subject, final Runnable notifier);
// }
// Path: rapid/src/main/java/com/vrg/rapid/monitoring/impl/PingPongFailureDetector.java
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.MoreExecutors;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.monitoring.IEdgeFailureDetectorFactory;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.NodeStatus;
import com.vrg.rapid.pb.ProbeMessage;
import com.vrg.rapid.pb.ProbeResponse;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.concurrent.atomic.AtomicInteger;
return;
}
final ProbeResponse probeResponse = response.getProbeResponse();
if (probeResponse.getStatus().equals(NodeStatus.BOOTSTRAPPING)) {
final int numBootstrapResponses = bootstrapResponseCount.incrementAndGet();
if (numBootstrapResponses > BOOTSTRAP_COUNT_THRESHOLD) {
handleProbeOnFailure(new RuntimeException("BOOTSTRAP_COUNT_THRESHOLD exceeded"));
return;
}
}
handleProbeOnSuccess();
}
@Override
public void onFailure(final Throwable throwable) {
handleProbeOnFailure(throwable);
}
// Executed at observer
private void handleProbeOnSuccess() {
LOG.trace("handleProbeOnSuccess at {} from {}", address, subject);
}
// Executed at observer
private void handleProbeOnFailure(final Throwable throwable) {
failureCount.incrementAndGet();
LOG.trace("handleProbeOnFailure at {} from {}: {}", address, subject, throwable.getLocalizedMessage());
}
}
| public static class Factory implements IEdgeFailureDetectorFactory { |
lalithsuresh/rapid | rapid/src/main/java/com/vrg/rapid/UnicastToAllBroadcaster.java | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
| import com.vrg.rapid.pb.Endpoint;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom; | /*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Simple best-effort broadcaster.
*/
final class UnicastToAllBroadcaster implements IBroadcaster {
private static final Logger LOG = LoggerFactory.getLogger(UnicastToAllBroadcaster.class); | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
// Path: rapid/src/main/java/com/vrg/rapid/UnicastToAllBroadcaster.java
import com.vrg.rapid.pb.Endpoint;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Simple best-effort broadcaster.
*/
final class UnicastToAllBroadcaster implements IBroadcaster {
private static final Logger LOG = LoggerFactory.getLogger(UnicastToAllBroadcaster.class); | private final IMessagingClient messagingClient; |
lalithsuresh/rapid | rapid/src/main/java/com/vrg/rapid/MembershipService.java | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/monitoring/IEdgeFailureDetectorFactory.java
// @ExperimentalApi
// public interface IEdgeFailureDetectorFactory {
// Runnable createInstance(final Endpoint subject, final Runnable notifier);
// }
| import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.monitoring.IEdgeFailureDetectorFactory;
import com.vrg.rapid.pb.AlertMessage;
import com.vrg.rapid.pb.BatchedAlertMessage;
import com.vrg.rapid.pb.EdgeStatus;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.JoinMessage;
import com.vrg.rapid.pb.JoinResponse;
import com.vrg.rapid.pb.JoinStatusCode;
import com.vrg.rapid.pb.LeaveMessage;
import com.vrg.rapid.pb.Metadata;
import com.vrg.rapid.pb.NodeId;
import com.vrg.rapid.pb.PreJoinMessage;
import com.vrg.rapid.pb.ProbeMessage;
import com.vrg.rapid.pb.ProbeResponse;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream; | /*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Membership server class that implements the Rapid protocol.
*
* Note: This class is not thread-safe yet. RpcServer.start() uses a single threaded messagingExecutor during the server
* initialization to make sure that only a single thread runs the process* methods.
*
*/
@NotThreadSafe
public final class MembershipService {
private static final Logger LOG = LoggerFactory.getLogger(MembershipService.class);
static final int BATCHING_WINDOW_IN_MS = 100;
private static final int DEFAULT_FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 0;
static final int DEFAULT_FAILURE_DETECTOR_INTERVAL_IN_MS = 1000;
private static final int LEAVE_MESSAGE_TIMEOUT = 1500;
private final MembershipView membershipView;
private final MultiNodeCutDetector cutDetection;
private final Endpoint myAddr; | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/monitoring/IEdgeFailureDetectorFactory.java
// @ExperimentalApi
// public interface IEdgeFailureDetectorFactory {
// Runnable createInstance(final Endpoint subject, final Runnable notifier);
// }
// Path: rapid/src/main/java/com/vrg/rapid/MembershipService.java
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.monitoring.IEdgeFailureDetectorFactory;
import com.vrg.rapid.pb.AlertMessage;
import com.vrg.rapid.pb.BatchedAlertMessage;
import com.vrg.rapid.pb.EdgeStatus;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.JoinMessage;
import com.vrg.rapid.pb.JoinResponse;
import com.vrg.rapid.pb.JoinStatusCode;
import com.vrg.rapid.pb.LeaveMessage;
import com.vrg.rapid.pb.Metadata;
import com.vrg.rapid.pb.NodeId;
import com.vrg.rapid.pb.PreJoinMessage;
import com.vrg.rapid.pb.ProbeMessage;
import com.vrg.rapid.pb.ProbeResponse;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Membership server class that implements the Rapid protocol.
*
* Note: This class is not thread-safe yet. RpcServer.start() uses a single threaded messagingExecutor during the server
* initialization to make sure that only a single thread runs the process* methods.
*
*/
@NotThreadSafe
public final class MembershipService {
private static final Logger LOG = LoggerFactory.getLogger(MembershipService.class);
static final int BATCHING_WINDOW_IN_MS = 100;
private static final int DEFAULT_FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 0;
static final int DEFAULT_FAILURE_DETECTOR_INTERVAL_IN_MS = 1000;
private static final int LEAVE_MESSAGE_TIMEOUT = 1500;
private final MembershipView membershipView;
private final MultiNodeCutDetector cutDetection;
private final Endpoint myAddr; | private final IBroadcaster broadcaster; |
lalithsuresh/rapid | rapid/src/main/java/com/vrg/rapid/MembershipService.java | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/monitoring/IEdgeFailureDetectorFactory.java
// @ExperimentalApi
// public interface IEdgeFailureDetectorFactory {
// Runnable createInstance(final Endpoint subject, final Runnable notifier);
// }
| import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.monitoring.IEdgeFailureDetectorFactory;
import com.vrg.rapid.pb.AlertMessage;
import com.vrg.rapid.pb.BatchedAlertMessage;
import com.vrg.rapid.pb.EdgeStatus;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.JoinMessage;
import com.vrg.rapid.pb.JoinResponse;
import com.vrg.rapid.pb.JoinStatusCode;
import com.vrg.rapid.pb.LeaveMessage;
import com.vrg.rapid.pb.Metadata;
import com.vrg.rapid.pb.NodeId;
import com.vrg.rapid.pb.PreJoinMessage;
import com.vrg.rapid.pb.ProbeMessage;
import com.vrg.rapid.pb.ProbeResponse;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream; | /*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Membership server class that implements the Rapid protocol.
*
* Note: This class is not thread-safe yet. RpcServer.start() uses a single threaded messagingExecutor during the server
* initialization to make sure that only a single thread runs the process* methods.
*
*/
@NotThreadSafe
public final class MembershipService {
private static final Logger LOG = LoggerFactory.getLogger(MembershipService.class);
static final int BATCHING_WINDOW_IN_MS = 100;
private static final int DEFAULT_FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 0;
static final int DEFAULT_FAILURE_DETECTOR_INTERVAL_IN_MS = 1000;
private static final int LEAVE_MESSAGE_TIMEOUT = 1500;
private final MembershipView membershipView;
private final MultiNodeCutDetector cutDetection;
private final Endpoint myAddr;
private final IBroadcaster broadcaster;
private final Map<Endpoint, LinkedBlockingDeque<SettableFuture<RapidResponse>>> joinersToRespondTo =
new HashMap<>();
private final Map<Endpoint, NodeId> joinerUuid = new HashMap<>();
private final Map<Endpoint, Metadata> joinerMetadata = new HashMap<>(); | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/monitoring/IEdgeFailureDetectorFactory.java
// @ExperimentalApi
// public interface IEdgeFailureDetectorFactory {
// Runnable createInstance(final Endpoint subject, final Runnable notifier);
// }
// Path: rapid/src/main/java/com/vrg/rapid/MembershipService.java
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.monitoring.IEdgeFailureDetectorFactory;
import com.vrg.rapid.pb.AlertMessage;
import com.vrg.rapid.pb.BatchedAlertMessage;
import com.vrg.rapid.pb.EdgeStatus;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.JoinMessage;
import com.vrg.rapid.pb.JoinResponse;
import com.vrg.rapid.pb.JoinStatusCode;
import com.vrg.rapid.pb.LeaveMessage;
import com.vrg.rapid.pb.Metadata;
import com.vrg.rapid.pb.NodeId;
import com.vrg.rapid.pb.PreJoinMessage;
import com.vrg.rapid.pb.ProbeMessage;
import com.vrg.rapid.pb.ProbeResponse;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Membership server class that implements the Rapid protocol.
*
* Note: This class is not thread-safe yet. RpcServer.start() uses a single threaded messagingExecutor during the server
* initialization to make sure that only a single thread runs the process* methods.
*
*/
@NotThreadSafe
public final class MembershipService {
private static final Logger LOG = LoggerFactory.getLogger(MembershipService.class);
static final int BATCHING_WINDOW_IN_MS = 100;
private static final int DEFAULT_FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 0;
static final int DEFAULT_FAILURE_DETECTOR_INTERVAL_IN_MS = 1000;
private static final int LEAVE_MESSAGE_TIMEOUT = 1500;
private final MembershipView membershipView;
private final MultiNodeCutDetector cutDetection;
private final Endpoint myAddr;
private final IBroadcaster broadcaster;
private final Map<Endpoint, LinkedBlockingDeque<SettableFuture<RapidResponse>>> joinersToRespondTo =
new HashMap<>();
private final Map<Endpoint, NodeId> joinerUuid = new HashMap<>();
private final Map<Endpoint, Metadata> joinerMetadata = new HashMap<>(); | private final IMessagingClient messagingClient; |
lalithsuresh/rapid | rapid/src/main/java/com/vrg/rapid/MembershipService.java | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/monitoring/IEdgeFailureDetectorFactory.java
// @ExperimentalApi
// public interface IEdgeFailureDetectorFactory {
// Runnable createInstance(final Endpoint subject, final Runnable notifier);
// }
| import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.monitoring.IEdgeFailureDetectorFactory;
import com.vrg.rapid.pb.AlertMessage;
import com.vrg.rapid.pb.BatchedAlertMessage;
import com.vrg.rapid.pb.EdgeStatus;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.JoinMessage;
import com.vrg.rapid.pb.JoinResponse;
import com.vrg.rapid.pb.JoinStatusCode;
import com.vrg.rapid.pb.LeaveMessage;
import com.vrg.rapid.pb.Metadata;
import com.vrg.rapid.pb.NodeId;
import com.vrg.rapid.pb.PreJoinMessage;
import com.vrg.rapid.pb.ProbeMessage;
import com.vrg.rapid.pb.ProbeResponse;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream; | /*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Membership server class that implements the Rapid protocol.
*
* Note: This class is not thread-safe yet. RpcServer.start() uses a single threaded messagingExecutor during the server
* initialization to make sure that only a single thread runs the process* methods.
*
*/
@NotThreadSafe
public final class MembershipService {
private static final Logger LOG = LoggerFactory.getLogger(MembershipService.class);
static final int BATCHING_WINDOW_IN_MS = 100;
private static final int DEFAULT_FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 0;
static final int DEFAULT_FAILURE_DETECTOR_INTERVAL_IN_MS = 1000;
private static final int LEAVE_MESSAGE_TIMEOUT = 1500;
private final MembershipView membershipView;
private final MultiNodeCutDetector cutDetection;
private final Endpoint myAddr;
private final IBroadcaster broadcaster;
private final Map<Endpoint, LinkedBlockingDeque<SettableFuture<RapidResponse>>> joinersToRespondTo =
new HashMap<>();
private final Map<Endpoint, NodeId> joinerUuid = new HashMap<>();
private final Map<Endpoint, Metadata> joinerMetadata = new HashMap<>();
private final IMessagingClient messagingClient;
private final MetadataManager metadataManager;
// Event subscriptions
private final Map<ClusterEvents, List<Consumer<ClusterStatusChange>>> subscriptions;
//
private FastPaxos fastPaxosInstance;
// Fields used by batching logic.
@GuardedBy("batchSchedulerLock")
private long lastEnqueueTimestamp = -1; // Timestamp
@GuardedBy("batchSchedulerLock")
private final LinkedBlockingQueue<AlertMessage> sendQueue = new LinkedBlockingQueue<>();
private final Lock batchSchedulerLock = new ReentrantLock();
private final ScheduledExecutorService backgroundTasksExecutor;
private final ScheduledFuture<?> alertBatcherJob;
private final List<ScheduledFuture<?>> failureDetectorJobs;
private final SharedResources sharedResources;
// Failure detector | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/monitoring/IEdgeFailureDetectorFactory.java
// @ExperimentalApi
// public interface IEdgeFailureDetectorFactory {
// Runnable createInstance(final Endpoint subject, final Runnable notifier);
// }
// Path: rapid/src/main/java/com/vrg/rapid/MembershipService.java
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.monitoring.IEdgeFailureDetectorFactory;
import com.vrg.rapid.pb.AlertMessage;
import com.vrg.rapid.pb.BatchedAlertMessage;
import com.vrg.rapid.pb.EdgeStatus;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.JoinMessage;
import com.vrg.rapid.pb.JoinResponse;
import com.vrg.rapid.pb.JoinStatusCode;
import com.vrg.rapid.pb.LeaveMessage;
import com.vrg.rapid.pb.Metadata;
import com.vrg.rapid.pb.NodeId;
import com.vrg.rapid.pb.PreJoinMessage;
import com.vrg.rapid.pb.ProbeMessage;
import com.vrg.rapid.pb.ProbeResponse;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Membership server class that implements the Rapid protocol.
*
* Note: This class is not thread-safe yet. RpcServer.start() uses a single threaded messagingExecutor during the server
* initialization to make sure that only a single thread runs the process* methods.
*
*/
@NotThreadSafe
public final class MembershipService {
private static final Logger LOG = LoggerFactory.getLogger(MembershipService.class);
static final int BATCHING_WINDOW_IN_MS = 100;
private static final int DEFAULT_FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 0;
static final int DEFAULT_FAILURE_DETECTOR_INTERVAL_IN_MS = 1000;
private static final int LEAVE_MESSAGE_TIMEOUT = 1500;
private final MembershipView membershipView;
private final MultiNodeCutDetector cutDetection;
private final Endpoint myAddr;
private final IBroadcaster broadcaster;
private final Map<Endpoint, LinkedBlockingDeque<SettableFuture<RapidResponse>>> joinersToRespondTo =
new HashMap<>();
private final Map<Endpoint, NodeId> joinerUuid = new HashMap<>();
private final Map<Endpoint, Metadata> joinerMetadata = new HashMap<>();
private final IMessagingClient messagingClient;
private final MetadataManager metadataManager;
// Event subscriptions
private final Map<ClusterEvents, List<Consumer<ClusterStatusChange>>> subscriptions;
//
private FastPaxos fastPaxosInstance;
// Fields used by batching logic.
@GuardedBy("batchSchedulerLock")
private long lastEnqueueTimestamp = -1; // Timestamp
@GuardedBy("batchSchedulerLock")
private final LinkedBlockingQueue<AlertMessage> sendQueue = new LinkedBlockingQueue<>();
private final Lock batchSchedulerLock = new ReentrantLock();
private final ScheduledExecutorService backgroundTasksExecutor;
private final ScheduledFuture<?> alertBatcherJob;
private final List<ScheduledFuture<?>> failureDetectorJobs;
private final SharedResources sharedResources;
// Failure detector | private final IEdgeFailureDetectorFactory fdFactory; |
lalithsuresh/rapid | rapid/src/main/java/com/vrg/rapid/FastPaxos.java | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
| import com.google.protobuf.TextFormat;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.pb.ConsensusResponse;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.FastRoundPhase2bMessage;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer; | /*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Single-decree consensus. We always start with a Fast round.
*/
class FastPaxos {
private static final Logger LOG = LoggerFactory.getLogger(FastPaxos.class);
static final long BASE_DELAY = 1000;
private final double jitterRate;
private final Endpoint myAddr;
private final long configurationId;
private final long membershipSize;
private final Consumer<List<Endpoint>> onDecidedWrapped; | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
// Path: rapid/src/main/java/com/vrg/rapid/FastPaxos.java
import com.google.protobuf.TextFormat;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.pb.ConsensusResponse;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.FastRoundPhase2bMessage;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
/*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Single-decree consensus. We always start with a Fast round.
*/
class FastPaxos {
private static final Logger LOG = LoggerFactory.getLogger(FastPaxos.class);
static final long BASE_DELAY = 1000;
private final double jitterRate;
private final Endpoint myAddr;
private final long configurationId;
private final long membershipSize;
private final Consumer<List<Endpoint>> onDecidedWrapped; | private final IBroadcaster broadcaster; |
lalithsuresh/rapid | rapid/src/main/java/com/vrg/rapid/FastPaxos.java | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
| import com.google.protobuf.TextFormat;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.pb.ConsensusResponse;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.FastRoundPhase2bMessage;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer; | /*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Single-decree consensus. We always start with a Fast round.
*/
class FastPaxos {
private static final Logger LOG = LoggerFactory.getLogger(FastPaxos.class);
static final long BASE_DELAY = 1000;
private final double jitterRate;
private final Endpoint myAddr;
private final long configurationId;
private final long membershipSize;
private final Consumer<List<Endpoint>> onDecidedWrapped;
private final IBroadcaster broadcaster;
private final Map<List<Endpoint>, AtomicInteger> votesPerProposal = new HashMap<>();
private final Set<Endpoint> votesReceived = new HashSet<>(); // Should be a bitset
private final Paxos paxos;
private final ScheduledExecutorService scheduledExecutorService;
private final Object paxosLock = new Object();
private final AtomicBoolean decided = new AtomicBoolean(false);
@Nullable private ScheduledFuture<?> scheduledClassicRoundTask = null;
private final ISettings settings;
FastPaxos(final Endpoint myAddr, final long configurationId, final int membershipSize, | // Path: rapid/src/main/java/com/vrg/rapid/messaging/IBroadcaster.java
// public interface IBroadcaster {
// List<ListenableFuture<RapidResponse>> broadcast(RapidRequest rapidRequest);
//
// void setMembership(List<Endpoint> recipients);
// }
//
// Path: rapid/src/main/java/com/vrg/rapid/messaging/IMessagingClient.java
// public interface IMessagingClient {
// /**
// * Send a message to a remote node with re-transmissions if necessary
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessage(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Send a message to a remote node with best-effort guarantees
// *
// * @param remote Remote host to send the message to
// * @param msg Message to send
// * @return A future that returns a RapidResponse if the call was successful.
// */
// @CanIgnoreReturnValue
// ListenableFuture<RapidResponse> sendMessageBestEffort(final Endpoint remote, final RapidRequest msg);
//
// /**
// * Signals to the messaging client that it should cleanup all resources in use.
// */
// void shutdown();
// }
// Path: rapid/src/main/java/com/vrg/rapid/FastPaxos.java
import com.google.protobuf.TextFormat;
import com.vrg.rapid.messaging.IBroadcaster;
import com.vrg.rapid.messaging.IMessagingClient;
import com.vrg.rapid.pb.ConsensusResponse;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.FastRoundPhase2bMessage;
import com.vrg.rapid.pb.RapidRequest;
import com.vrg.rapid.pb.RapidResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
/*
* Copyright © 2016 - 2020 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an “AS IS” BASIS, without warranties or conditions of any kind,
* EITHER EXPRESS OR IMPLIED. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.vrg.rapid;
/**
* Single-decree consensus. We always start with a Fast round.
*/
class FastPaxos {
private static final Logger LOG = LoggerFactory.getLogger(FastPaxos.class);
static final long BASE_DELAY = 1000;
private final double jitterRate;
private final Endpoint myAddr;
private final long configurationId;
private final long membershipSize;
private final Consumer<List<Endpoint>> onDecidedWrapped;
private final IBroadcaster broadcaster;
private final Map<List<Endpoint>, AtomicInteger> votesPerProposal = new HashMap<>();
private final Set<Endpoint> votesReceived = new HashSet<>(); // Should be a bitset
private final Paxos paxos;
private final ScheduledExecutorService scheduledExecutorService;
private final Object paxosLock = new Object();
private final AtomicBoolean decided = new AtomicBoolean(false);
@Nullable private ScheduledFuture<?> scheduledClassicRoundTask = null;
private final ISettings settings;
FastPaxos(final Endpoint myAddr, final long configurationId, final int membershipSize, | final IMessagingClient client, final IBroadcaster broadcaster, |
hseeberger/akka-sse | core/src/test/java/de/heikoseeberger/akkasse/javadsl/marshalling/EventStreamMarshallingTest.java | // Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/marshalling/EventStreamMarshalling.java
// public abstract class EventStreamMarshalling {
//
// public static <T> Marshaller<Source<ServerSentEvent, T>, RequestEntity> toEventStream() {
// return Marshaller.fromScala(EventStreamMarshallingConverter$.MODULE$.toEventStream());
// }
// }
//
// Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/ServerSentEvent.java
// public abstract class ServerSentEvent {
//
// private static final Option<String> stringNone = toScala(Optional.empty());
//
// private static final Option<Object> intNone = toScala(OptionalInt.empty());
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may be empty or span multiple lines
// */
// public static ServerSentEvent create(String data) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, stringNone, stringNone, intNone);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// * @param id id, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type, String id) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type, id);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param retry reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data, int retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, retry);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type optional type, must not contain \n or \r
// * @param id optional id, must not contain \n or \r
// * @param retry optional reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data,
// Optional<String> type,
// Optional<String> id,
// OptionalInt retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(
// data, toScala(type), toScala(id), toScala(retry)
// );
// }
//
// /**
// * Data, may span multiple lines.
// */
// public abstract String getData();
//
// /**
// * Optional type, must not contain \n or \r.
// */
// public abstract Optional<String> getType();
//
// /**
// * Optional id, must not contain \n or \r.
// */
// public abstract Optional<String> getId();
//
// /**
// * Optional reconnection delay in milliseconds.
// */
// public abstract OptionalInt getRetry();
// }
//
// Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/MediaTypes.java
// public static final MediaType.WithFixedCharset TEXT_EVENT_STREAM =
// de.heikoseeberger.akkasse.scaladsl.model.MediaTypes.text$divevent$minusstream();
| import akka.http.javadsl.server.Route;
import akka.http.javadsl.testkit.JUnitRouteTest;
import akka.http.javadsl.testkit.TestRouteResult;
import akka.stream.javadsl.Source;
import akka.util.ByteString;
import java.util.ArrayList;
import java.util.List;
import de.heikoseeberger.akkasse.javadsl.marshalling.EventStreamMarshalling;
import de.heikoseeberger.akkasse.javadsl.model.ServerSentEvent;
import org.junit.Test;
import static akka.http.javadsl.model.HttpRequest.GET;
import static de.heikoseeberger.akkasse.javadsl.model.MediaTypes.TEXT_EVENT_STREAM; | /*
* Copyright 2015 Heiko Seeberger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.heikoseeberger.akkasse.javadsl.marshalling;
public class EventStreamMarshallingTest extends JUnitRouteTest {
@Test
public void testToEventStream() { | // Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/marshalling/EventStreamMarshalling.java
// public abstract class EventStreamMarshalling {
//
// public static <T> Marshaller<Source<ServerSentEvent, T>, RequestEntity> toEventStream() {
// return Marshaller.fromScala(EventStreamMarshallingConverter$.MODULE$.toEventStream());
// }
// }
//
// Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/ServerSentEvent.java
// public abstract class ServerSentEvent {
//
// private static final Option<String> stringNone = toScala(Optional.empty());
//
// private static final Option<Object> intNone = toScala(OptionalInt.empty());
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may be empty or span multiple lines
// */
// public static ServerSentEvent create(String data) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, stringNone, stringNone, intNone);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// * @param id id, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type, String id) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type, id);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param retry reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data, int retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, retry);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type optional type, must not contain \n or \r
// * @param id optional id, must not contain \n or \r
// * @param retry optional reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data,
// Optional<String> type,
// Optional<String> id,
// OptionalInt retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(
// data, toScala(type), toScala(id), toScala(retry)
// );
// }
//
// /**
// * Data, may span multiple lines.
// */
// public abstract String getData();
//
// /**
// * Optional type, must not contain \n or \r.
// */
// public abstract Optional<String> getType();
//
// /**
// * Optional id, must not contain \n or \r.
// */
// public abstract Optional<String> getId();
//
// /**
// * Optional reconnection delay in milliseconds.
// */
// public abstract OptionalInt getRetry();
// }
//
// Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/MediaTypes.java
// public static final MediaType.WithFixedCharset TEXT_EVENT_STREAM =
// de.heikoseeberger.akkasse.scaladsl.model.MediaTypes.text$divevent$minusstream();
// Path: core/src/test/java/de/heikoseeberger/akkasse/javadsl/marshalling/EventStreamMarshallingTest.java
import akka.http.javadsl.server.Route;
import akka.http.javadsl.testkit.JUnitRouteTest;
import akka.http.javadsl.testkit.TestRouteResult;
import akka.stream.javadsl.Source;
import akka.util.ByteString;
import java.util.ArrayList;
import java.util.List;
import de.heikoseeberger.akkasse.javadsl.marshalling.EventStreamMarshalling;
import de.heikoseeberger.akkasse.javadsl.model.ServerSentEvent;
import org.junit.Test;
import static akka.http.javadsl.model.HttpRequest.GET;
import static de.heikoseeberger.akkasse.javadsl.model.MediaTypes.TEXT_EVENT_STREAM;
/*
* Copyright 2015 Heiko Seeberger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.heikoseeberger.akkasse.javadsl.marshalling;
public class EventStreamMarshallingTest extends JUnitRouteTest {
@Test
public void testToEventStream() { | final List<ServerSentEvent> events = new ArrayList<>(); |
hseeberger/akka-sse | core/src/test/java/de/heikoseeberger/akkasse/javadsl/marshalling/EventStreamMarshallingTest.java | // Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/marshalling/EventStreamMarshalling.java
// public abstract class EventStreamMarshalling {
//
// public static <T> Marshaller<Source<ServerSentEvent, T>, RequestEntity> toEventStream() {
// return Marshaller.fromScala(EventStreamMarshallingConverter$.MODULE$.toEventStream());
// }
// }
//
// Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/ServerSentEvent.java
// public abstract class ServerSentEvent {
//
// private static final Option<String> stringNone = toScala(Optional.empty());
//
// private static final Option<Object> intNone = toScala(OptionalInt.empty());
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may be empty or span multiple lines
// */
// public static ServerSentEvent create(String data) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, stringNone, stringNone, intNone);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// * @param id id, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type, String id) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type, id);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param retry reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data, int retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, retry);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type optional type, must not contain \n or \r
// * @param id optional id, must not contain \n or \r
// * @param retry optional reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data,
// Optional<String> type,
// Optional<String> id,
// OptionalInt retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(
// data, toScala(type), toScala(id), toScala(retry)
// );
// }
//
// /**
// * Data, may span multiple lines.
// */
// public abstract String getData();
//
// /**
// * Optional type, must not contain \n or \r.
// */
// public abstract Optional<String> getType();
//
// /**
// * Optional id, must not contain \n or \r.
// */
// public abstract Optional<String> getId();
//
// /**
// * Optional reconnection delay in milliseconds.
// */
// public abstract OptionalInt getRetry();
// }
//
// Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/MediaTypes.java
// public static final MediaType.WithFixedCharset TEXT_EVENT_STREAM =
// de.heikoseeberger.akkasse.scaladsl.model.MediaTypes.text$divevent$minusstream();
| import akka.http.javadsl.server.Route;
import akka.http.javadsl.testkit.JUnitRouteTest;
import akka.http.javadsl.testkit.TestRouteResult;
import akka.stream.javadsl.Source;
import akka.util.ByteString;
import java.util.ArrayList;
import java.util.List;
import de.heikoseeberger.akkasse.javadsl.marshalling.EventStreamMarshalling;
import de.heikoseeberger.akkasse.javadsl.model.ServerSentEvent;
import org.junit.Test;
import static akka.http.javadsl.model.HttpRequest.GET;
import static de.heikoseeberger.akkasse.javadsl.model.MediaTypes.TEXT_EVENT_STREAM; | /*
* Copyright 2015 Heiko Seeberger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.heikoseeberger.akkasse.javadsl.marshalling;
public class EventStreamMarshallingTest extends JUnitRouteTest {
@Test
public void testToEventStream() {
final List<ServerSentEvent> events = new ArrayList<>();
events.add(ServerSentEvent.create("1"));
events.add(ServerSentEvent.create("2")); | // Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/marshalling/EventStreamMarshalling.java
// public abstract class EventStreamMarshalling {
//
// public static <T> Marshaller<Source<ServerSentEvent, T>, RequestEntity> toEventStream() {
// return Marshaller.fromScala(EventStreamMarshallingConverter$.MODULE$.toEventStream());
// }
// }
//
// Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/ServerSentEvent.java
// public abstract class ServerSentEvent {
//
// private static final Option<String> stringNone = toScala(Optional.empty());
//
// private static final Option<Object> intNone = toScala(OptionalInt.empty());
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may be empty or span multiple lines
// */
// public static ServerSentEvent create(String data) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, stringNone, stringNone, intNone);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// * @param id id, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type, String id) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type, id);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param retry reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data, int retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, retry);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type optional type, must not contain \n or \r
// * @param id optional id, must not contain \n or \r
// * @param retry optional reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data,
// Optional<String> type,
// Optional<String> id,
// OptionalInt retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(
// data, toScala(type), toScala(id), toScala(retry)
// );
// }
//
// /**
// * Data, may span multiple lines.
// */
// public abstract String getData();
//
// /**
// * Optional type, must not contain \n or \r.
// */
// public abstract Optional<String> getType();
//
// /**
// * Optional id, must not contain \n or \r.
// */
// public abstract Optional<String> getId();
//
// /**
// * Optional reconnection delay in milliseconds.
// */
// public abstract OptionalInt getRetry();
// }
//
// Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/MediaTypes.java
// public static final MediaType.WithFixedCharset TEXT_EVENT_STREAM =
// de.heikoseeberger.akkasse.scaladsl.model.MediaTypes.text$divevent$minusstream();
// Path: core/src/test/java/de/heikoseeberger/akkasse/javadsl/marshalling/EventStreamMarshallingTest.java
import akka.http.javadsl.server.Route;
import akka.http.javadsl.testkit.JUnitRouteTest;
import akka.http.javadsl.testkit.TestRouteResult;
import akka.stream.javadsl.Source;
import akka.util.ByteString;
import java.util.ArrayList;
import java.util.List;
import de.heikoseeberger.akkasse.javadsl.marshalling.EventStreamMarshalling;
import de.heikoseeberger.akkasse.javadsl.model.ServerSentEvent;
import org.junit.Test;
import static akka.http.javadsl.model.HttpRequest.GET;
import static de.heikoseeberger.akkasse.javadsl.model.MediaTypes.TEXT_EVENT_STREAM;
/*
* Copyright 2015 Heiko Seeberger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.heikoseeberger.akkasse.javadsl.marshalling;
public class EventStreamMarshallingTest extends JUnitRouteTest {
@Test
public void testToEventStream() {
final List<ServerSentEvent> events = new ArrayList<>();
events.add(ServerSentEvent.create("1"));
events.add(ServerSentEvent.create("2")); | final Route route = completeOK(Source.from(events), EventStreamMarshalling.toEventStream()); |
hseeberger/akka-sse | core/src/test/java/de/heikoseeberger/akkasse/javadsl/marshalling/EventStreamMarshallingTest.java | // Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/marshalling/EventStreamMarshalling.java
// public abstract class EventStreamMarshalling {
//
// public static <T> Marshaller<Source<ServerSentEvent, T>, RequestEntity> toEventStream() {
// return Marshaller.fromScala(EventStreamMarshallingConverter$.MODULE$.toEventStream());
// }
// }
//
// Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/ServerSentEvent.java
// public abstract class ServerSentEvent {
//
// private static final Option<String> stringNone = toScala(Optional.empty());
//
// private static final Option<Object> intNone = toScala(OptionalInt.empty());
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may be empty or span multiple lines
// */
// public static ServerSentEvent create(String data) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, stringNone, stringNone, intNone);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// * @param id id, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type, String id) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type, id);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param retry reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data, int retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, retry);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type optional type, must not contain \n or \r
// * @param id optional id, must not contain \n or \r
// * @param retry optional reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data,
// Optional<String> type,
// Optional<String> id,
// OptionalInt retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(
// data, toScala(type), toScala(id), toScala(retry)
// );
// }
//
// /**
// * Data, may span multiple lines.
// */
// public abstract String getData();
//
// /**
// * Optional type, must not contain \n or \r.
// */
// public abstract Optional<String> getType();
//
// /**
// * Optional id, must not contain \n or \r.
// */
// public abstract Optional<String> getId();
//
// /**
// * Optional reconnection delay in milliseconds.
// */
// public abstract OptionalInt getRetry();
// }
//
// Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/MediaTypes.java
// public static final MediaType.WithFixedCharset TEXT_EVENT_STREAM =
// de.heikoseeberger.akkasse.scaladsl.model.MediaTypes.text$divevent$minusstream();
| import akka.http.javadsl.server.Route;
import akka.http.javadsl.testkit.JUnitRouteTest;
import akka.http.javadsl.testkit.TestRouteResult;
import akka.stream.javadsl.Source;
import akka.util.ByteString;
import java.util.ArrayList;
import java.util.List;
import de.heikoseeberger.akkasse.javadsl.marshalling.EventStreamMarshalling;
import de.heikoseeberger.akkasse.javadsl.model.ServerSentEvent;
import org.junit.Test;
import static akka.http.javadsl.model.HttpRequest.GET;
import static de.heikoseeberger.akkasse.javadsl.model.MediaTypes.TEXT_EVENT_STREAM; | /*
* Copyright 2015 Heiko Seeberger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.heikoseeberger.akkasse.javadsl.marshalling;
public class EventStreamMarshallingTest extends JUnitRouteTest {
@Test
public void testToEventStream() {
final List<ServerSentEvent> events = new ArrayList<>();
events.add(ServerSentEvent.create("1"));
events.add(ServerSentEvent.create("2"));
final Route route = completeOK(Source.from(events), EventStreamMarshalling.toEventStream());
final ByteString expectedEntity = events
.stream()
.map(e -> ((de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent) e).encode())
.reduce(ByteString.empty(), ByteString::$plus$plus);
final TestRouteResult routeResult = testRoute(route).run(GET("/")); | // Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/marshalling/EventStreamMarshalling.java
// public abstract class EventStreamMarshalling {
//
// public static <T> Marshaller<Source<ServerSentEvent, T>, RequestEntity> toEventStream() {
// return Marshaller.fromScala(EventStreamMarshallingConverter$.MODULE$.toEventStream());
// }
// }
//
// Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/ServerSentEvent.java
// public abstract class ServerSentEvent {
//
// private static final Option<String> stringNone = toScala(Optional.empty());
//
// private static final Option<Object> intNone = toScala(OptionalInt.empty());
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may be empty or span multiple lines
// */
// public static ServerSentEvent create(String data) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, stringNone, stringNone, intNone);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// * @param id id, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type, String id) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type, id);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param retry reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data, int retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, retry);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type optional type, must not contain \n or \r
// * @param id optional id, must not contain \n or \r
// * @param retry optional reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data,
// Optional<String> type,
// Optional<String> id,
// OptionalInt retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(
// data, toScala(type), toScala(id), toScala(retry)
// );
// }
//
// /**
// * Data, may span multiple lines.
// */
// public abstract String getData();
//
// /**
// * Optional type, must not contain \n or \r.
// */
// public abstract Optional<String> getType();
//
// /**
// * Optional id, must not contain \n or \r.
// */
// public abstract Optional<String> getId();
//
// /**
// * Optional reconnection delay in milliseconds.
// */
// public abstract OptionalInt getRetry();
// }
//
// Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/MediaTypes.java
// public static final MediaType.WithFixedCharset TEXT_EVENT_STREAM =
// de.heikoseeberger.akkasse.scaladsl.model.MediaTypes.text$divevent$minusstream();
// Path: core/src/test/java/de/heikoseeberger/akkasse/javadsl/marshalling/EventStreamMarshallingTest.java
import akka.http.javadsl.server.Route;
import akka.http.javadsl.testkit.JUnitRouteTest;
import akka.http.javadsl.testkit.TestRouteResult;
import akka.stream.javadsl.Source;
import akka.util.ByteString;
import java.util.ArrayList;
import java.util.List;
import de.heikoseeberger.akkasse.javadsl.marshalling.EventStreamMarshalling;
import de.heikoseeberger.akkasse.javadsl.model.ServerSentEvent;
import org.junit.Test;
import static akka.http.javadsl.model.HttpRequest.GET;
import static de.heikoseeberger.akkasse.javadsl.model.MediaTypes.TEXT_EVENT_STREAM;
/*
* Copyright 2015 Heiko Seeberger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.heikoseeberger.akkasse.javadsl.marshalling;
public class EventStreamMarshallingTest extends JUnitRouteTest {
@Test
public void testToEventStream() {
final List<ServerSentEvent> events = new ArrayList<>();
events.add(ServerSentEvent.create("1"));
events.add(ServerSentEvent.create("2"));
final Route route = completeOK(Source.from(events), EventStreamMarshalling.toEventStream());
final ByteString expectedEntity = events
.stream()
.map(e -> ((de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent) e).encode())
.reduce(ByteString.empty(), ByteString::$plus$plus);
final TestRouteResult routeResult = testRoute(route).run(GET("/")); | routeResult.assertMediaType(TEXT_EVENT_STREAM); |
hseeberger/akka-sse | core/src/test/java/de/heikoseeberger/akkasse/javadsl/unmarshalling/EventStreamUnmarshallingTest.java | // Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/ServerSentEvent.java
// public abstract class ServerSentEvent {
//
// private static final Option<String> stringNone = toScala(Optional.empty());
//
// private static final Option<Object> intNone = toScala(OptionalInt.empty());
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may be empty or span multiple lines
// */
// public static ServerSentEvent create(String data) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, stringNone, stringNone, intNone);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// * @param id id, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type, String id) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type, id);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param retry reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data, int retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, retry);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type optional type, must not contain \n or \r
// * @param id optional id, must not contain \n or \r
// * @param retry optional reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data,
// Optional<String> type,
// Optional<String> id,
// OptionalInt retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(
// data, toScala(type), toScala(id), toScala(retry)
// );
// }
//
// /**
// * Data, may span multiple lines.
// */
// public abstract String getData();
//
// /**
// * Optional type, must not contain \n or \r.
// */
// public abstract Optional<String> getType();
//
// /**
// * Optional id, must not contain \n or \r.
// */
// public abstract Optional<String> getId();
//
// /**
// * Optional reconnection delay in milliseconds.
// */
// public abstract OptionalInt getRetry();
// }
//
// Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/unmarshalling/EventStreamUnmarshalling.java
// public abstract class EventStreamUnmarshalling {
//
// public static Unmarshaller<HttpEntity, Source<ServerSentEvent, NotUsed>> fromEventStream() {
// return Unmarshaller.fromScala(EventStreamUnmarshallingConverter$.MODULE$.fromEventStream());
// }
// }
| import akka.actor.ActorSystem;
import akka.http.javadsl.model.HttpEntity;
import akka.stream.ActorMaterializer;
import akka.stream.Materializer;
import akka.stream.javadsl.Sink;
import de.heikoseeberger.akkasse.javadsl.model.ServerSentEvent;
import de.heikoseeberger.akkasse.javadsl.unmarshalling.EventStreamUnmarshalling;
import de.heikoseeberger.akkasse.scaladsl.unmarshalling.EventStreamUnmarshallingSpec;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
import org.scalatest.junit.JUnitSuite; | /*
* Copyright 2015 Heiko Seeberger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.heikoseeberger.akkasse.javadsl.unmarshalling;
public class EventStreamUnmarshallingTest extends JUnitSuite {
@Test
public void testFromEventStream() throws Exception {
ActorSystem system = ActorSystem.create();
try {
Materializer mat = ActorMaterializer.create(system);
| // Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/ServerSentEvent.java
// public abstract class ServerSentEvent {
//
// private static final Option<String> stringNone = toScala(Optional.empty());
//
// private static final Option<Object> intNone = toScala(OptionalInt.empty());
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may be empty or span multiple lines
// */
// public static ServerSentEvent create(String data) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, stringNone, stringNone, intNone);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// * @param id id, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type, String id) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type, id);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param retry reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data, int retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, retry);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type optional type, must not contain \n or \r
// * @param id optional id, must not contain \n or \r
// * @param retry optional reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data,
// Optional<String> type,
// Optional<String> id,
// OptionalInt retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(
// data, toScala(type), toScala(id), toScala(retry)
// );
// }
//
// /**
// * Data, may span multiple lines.
// */
// public abstract String getData();
//
// /**
// * Optional type, must not contain \n or \r.
// */
// public abstract Optional<String> getType();
//
// /**
// * Optional id, must not contain \n or \r.
// */
// public abstract Optional<String> getId();
//
// /**
// * Optional reconnection delay in milliseconds.
// */
// public abstract OptionalInt getRetry();
// }
//
// Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/unmarshalling/EventStreamUnmarshalling.java
// public abstract class EventStreamUnmarshalling {
//
// public static Unmarshaller<HttpEntity, Source<ServerSentEvent, NotUsed>> fromEventStream() {
// return Unmarshaller.fromScala(EventStreamUnmarshallingConverter$.MODULE$.fromEventStream());
// }
// }
// Path: core/src/test/java/de/heikoseeberger/akkasse/javadsl/unmarshalling/EventStreamUnmarshallingTest.java
import akka.actor.ActorSystem;
import akka.http.javadsl.model.HttpEntity;
import akka.stream.ActorMaterializer;
import akka.stream.Materializer;
import akka.stream.javadsl.Sink;
import de.heikoseeberger.akkasse.javadsl.model.ServerSentEvent;
import de.heikoseeberger.akkasse.javadsl.unmarshalling.EventStreamUnmarshalling;
import de.heikoseeberger.akkasse.scaladsl.unmarshalling.EventStreamUnmarshallingSpec;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
import org.scalatest.junit.JUnitSuite;
/*
* Copyright 2015 Heiko Seeberger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.heikoseeberger.akkasse.javadsl.unmarshalling;
public class EventStreamUnmarshallingTest extends JUnitSuite {
@Test
public void testFromEventStream() throws Exception {
ActorSystem system = ActorSystem.create();
try {
Materializer mat = ActorMaterializer.create(system);
| List<ServerSentEvent> events = EventStreamUnmarshallingSpec.eventsAsJava(); |
hseeberger/akka-sse | core/src/test/java/de/heikoseeberger/akkasse/javadsl/unmarshalling/EventStreamUnmarshallingTest.java | // Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/ServerSentEvent.java
// public abstract class ServerSentEvent {
//
// private static final Option<String> stringNone = toScala(Optional.empty());
//
// private static final Option<Object> intNone = toScala(OptionalInt.empty());
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may be empty or span multiple lines
// */
// public static ServerSentEvent create(String data) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, stringNone, stringNone, intNone);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// * @param id id, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type, String id) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type, id);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param retry reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data, int retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, retry);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type optional type, must not contain \n or \r
// * @param id optional id, must not contain \n or \r
// * @param retry optional reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data,
// Optional<String> type,
// Optional<String> id,
// OptionalInt retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(
// data, toScala(type), toScala(id), toScala(retry)
// );
// }
//
// /**
// * Data, may span multiple lines.
// */
// public abstract String getData();
//
// /**
// * Optional type, must not contain \n or \r.
// */
// public abstract Optional<String> getType();
//
// /**
// * Optional id, must not contain \n or \r.
// */
// public abstract Optional<String> getId();
//
// /**
// * Optional reconnection delay in milliseconds.
// */
// public abstract OptionalInt getRetry();
// }
//
// Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/unmarshalling/EventStreamUnmarshalling.java
// public abstract class EventStreamUnmarshalling {
//
// public static Unmarshaller<HttpEntity, Source<ServerSentEvent, NotUsed>> fromEventStream() {
// return Unmarshaller.fromScala(EventStreamUnmarshallingConverter$.MODULE$.fromEventStream());
// }
// }
| import akka.actor.ActorSystem;
import akka.http.javadsl.model.HttpEntity;
import akka.stream.ActorMaterializer;
import akka.stream.Materializer;
import akka.stream.javadsl.Sink;
import de.heikoseeberger.akkasse.javadsl.model.ServerSentEvent;
import de.heikoseeberger.akkasse.javadsl.unmarshalling.EventStreamUnmarshalling;
import de.heikoseeberger.akkasse.scaladsl.unmarshalling.EventStreamUnmarshallingSpec;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
import org.scalatest.junit.JUnitSuite; | /*
* Copyright 2015 Heiko Seeberger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.heikoseeberger.akkasse.javadsl.unmarshalling;
public class EventStreamUnmarshallingTest extends JUnitSuite {
@Test
public void testFromEventStream() throws Exception {
ActorSystem system = ActorSystem.create();
try {
Materializer mat = ActorMaterializer.create(system);
List<ServerSentEvent> events = EventStreamUnmarshallingSpec.eventsAsJava();
HttpEntity entity = EventStreamUnmarshallingSpec.entity();
List<ServerSentEvent> unmarshalledEvents = | // Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/ServerSentEvent.java
// public abstract class ServerSentEvent {
//
// private static final Option<String> stringNone = toScala(Optional.empty());
//
// private static final Option<Object> intNone = toScala(OptionalInt.empty());
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may be empty or span multiple lines
// */
// public static ServerSentEvent create(String data) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, stringNone, stringNone, intNone);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// * @param id id, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type, String id) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type, id);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param retry reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data, int retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, retry);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type optional type, must not contain \n or \r
// * @param id optional id, must not contain \n or \r
// * @param retry optional reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data,
// Optional<String> type,
// Optional<String> id,
// OptionalInt retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(
// data, toScala(type), toScala(id), toScala(retry)
// );
// }
//
// /**
// * Data, may span multiple lines.
// */
// public abstract String getData();
//
// /**
// * Optional type, must not contain \n or \r.
// */
// public abstract Optional<String> getType();
//
// /**
// * Optional id, must not contain \n or \r.
// */
// public abstract Optional<String> getId();
//
// /**
// * Optional reconnection delay in milliseconds.
// */
// public abstract OptionalInt getRetry();
// }
//
// Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/unmarshalling/EventStreamUnmarshalling.java
// public abstract class EventStreamUnmarshalling {
//
// public static Unmarshaller<HttpEntity, Source<ServerSentEvent, NotUsed>> fromEventStream() {
// return Unmarshaller.fromScala(EventStreamUnmarshallingConverter$.MODULE$.fromEventStream());
// }
// }
// Path: core/src/test/java/de/heikoseeberger/akkasse/javadsl/unmarshalling/EventStreamUnmarshallingTest.java
import akka.actor.ActorSystem;
import akka.http.javadsl.model.HttpEntity;
import akka.stream.ActorMaterializer;
import akka.stream.Materializer;
import akka.stream.javadsl.Sink;
import de.heikoseeberger.akkasse.javadsl.model.ServerSentEvent;
import de.heikoseeberger.akkasse.javadsl.unmarshalling.EventStreamUnmarshalling;
import de.heikoseeberger.akkasse.scaladsl.unmarshalling.EventStreamUnmarshallingSpec;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
import org.scalatest.junit.JUnitSuite;
/*
* Copyright 2015 Heiko Seeberger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.heikoseeberger.akkasse.javadsl.unmarshalling;
public class EventStreamUnmarshallingTest extends JUnitSuite {
@Test
public void testFromEventStream() throws Exception {
ActorSystem system = ActorSystem.create();
try {
Materializer mat = ActorMaterializer.create(system);
List<ServerSentEvent> events = EventStreamUnmarshallingSpec.eventsAsJava();
HttpEntity entity = EventStreamUnmarshallingSpec.entity();
List<ServerSentEvent> unmarshalledEvents = | EventStreamUnmarshalling.fromEventStream() |
hseeberger/akka-sse | core/src/test/java/de/heikoseeberger/akkasse/javadsl/model/ServerSentEventTest.java | // Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/ServerSentEvent.java
// public abstract class ServerSentEvent {
//
// private static final Option<String> stringNone = toScala(Optional.empty());
//
// private static final Option<Object> intNone = toScala(OptionalInt.empty());
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may be empty or span multiple lines
// */
// public static ServerSentEvent create(String data) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, stringNone, stringNone, intNone);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// * @param id id, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type, String id) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type, id);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param retry reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data, int retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, retry);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type optional type, must not contain \n or \r
// * @param id optional id, must not contain \n or \r
// * @param retry optional reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data,
// Optional<String> type,
// Optional<String> id,
// OptionalInt retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(
// data, toScala(type), toScala(id), toScala(retry)
// );
// }
//
// /**
// * Data, may span multiple lines.
// */
// public abstract String getData();
//
// /**
// * Optional type, must not contain \n or \r.
// */
// public abstract Optional<String> getType();
//
// /**
// * Optional id, must not contain \n or \r.
// */
// public abstract Optional<String> getId();
//
// /**
// * Optional reconnection delay in milliseconds.
// */
// public abstract OptionalInt getRetry();
// }
| import java.util.Optional;
import java.util.OptionalInt;
import de.heikoseeberger.akkasse.javadsl.model.ServerSentEvent;
import org.junit.Assert;
import org.junit.Test;
import org.scalatest.junit.JUnitSuite; | /*
* Copyright 2015 Heiko Seeberger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.heikoseeberger.akkasse.javadsl.model;
public class ServerSentEventTest extends JUnitSuite {
@Test
public void create() { | // Path: core/src/main/java/de/heikoseeberger/akkasse/javadsl/model/ServerSentEvent.java
// public abstract class ServerSentEvent {
//
// private static final Option<String> stringNone = toScala(Optional.empty());
//
// private static final Option<Object> intNone = toScala(OptionalInt.empty());
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may be empty or span multiple lines
// */
// public static ServerSentEvent create(String data) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, stringNone, stringNone, intNone);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type type, must not contain \n or \r
// * @param id id, must not contain \n or \r
// */
// public static ServerSentEvent create(String data, String type, String id) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, type, id);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param retry reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data, int retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(data, retry);
// }
//
// /**
// * Creates a [[ServerSentEvent]].
// *
// * @param data data, may span multiple lines
// * @param type optional type, must not contain \n or \r
// * @param id optional id, must not contain \n or \r
// * @param retry optional reconnection delay in milliseconds
// */
// public static ServerSentEvent create(String data,
// Optional<String> type,
// Optional<String> id,
// OptionalInt retry) {
// return de.heikoseeberger.akkasse.scaladsl.model.ServerSentEvent.apply(
// data, toScala(type), toScala(id), toScala(retry)
// );
// }
//
// /**
// * Data, may span multiple lines.
// */
// public abstract String getData();
//
// /**
// * Optional type, must not contain \n or \r.
// */
// public abstract Optional<String> getType();
//
// /**
// * Optional id, must not contain \n or \r.
// */
// public abstract Optional<String> getId();
//
// /**
// * Optional reconnection delay in milliseconds.
// */
// public abstract OptionalInt getRetry();
// }
// Path: core/src/test/java/de/heikoseeberger/akkasse/javadsl/model/ServerSentEventTest.java
import java.util.Optional;
import java.util.OptionalInt;
import de.heikoseeberger.akkasse.javadsl.model.ServerSentEvent;
import org.junit.Assert;
import org.junit.Test;
import org.scalatest.junit.JUnitSuite;
/*
* Copyright 2015 Heiko Seeberger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.heikoseeberger.akkasse.javadsl.model;
public class ServerSentEventTest extends JUnitSuite {
@Test
public void create() { | final ServerSentEvent event = ServerSentEvent.create( |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/core/classsearch/ClassSearchResult.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/BundleClass.java
// public class BundleClass {
//
// private Bundle bundle;
//
// private String className;
//
// public BundleClass(Bundle bundle, String className) {
// this.bundle = bundle;
// this.className = className;
// }
//
// public Bundle getBundle() {
// return bundle;
// }
//
// public String getClassName() {
// return className;
// }
//
// public String getClassPath() {
// return StringUtils.replace(className, ".", "/");
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// BundleClass that = (BundleClass) o;
//
// return new EqualsBuilder()
// .append(bundle, that.bundle)
// .append(className, that.className)
// .isEquals();
// }
//
// @Override
// public int hashCode() {
// return new HashCodeBuilder()
// .append(bundle)
// .append(className)
// .toHashCode();
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/ClassDecompileServlet.java
// public class ClassDecompileServlet extends RestServlet {
//
// public static final String ALIAS_NAME = "class-decompile";
//
// public static final String BUNDLE_ID = "bundleId";
//
// public static final String CLASS_NAME = "className";
//
// private final OsgiExplorer osgiExplorer;
//
// public ClassDecompileServlet(BundleContext bundleContext) {
// super(bundleContext);
// this.osgiExplorer = new OsgiExplorer(bundleContext);
// }
//
// public static String url(BundleContext context, Bundle bundle, String className) {
// return url(context, bundle.getBundleId(), className);
// }
//
// public static String url(BundleContext context, long bundleId, String className) {
// return String.format("%s?%s=%d&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME), BUNDLE_ID, bundleId, CLASS_NAME, className);
// }
//
// @Override
// protected String getAliasName() {
// return ALIAS_NAME;
// }
//
// @Override
// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// final String bundleId = StringUtils.trimToEmpty(request.getParameter(BUNDLE_ID));
// final String className = StringUtils.trimToEmpty(request.getParameter(CLASS_NAME));
//
// final Bundle bundle = bundleContext.getBundle(Long.valueOf(bundleId));
// if (bundle == null) {
// JsonUtils.writeMessage(response, MessageType.ERROR, String.format("Bundle '%s' not be found.", bundleId));
// return;
// }
//
// final File bundleJar = osgiExplorer.findJar(Long.valueOf(bundleId));
// if (bundleJar == null) {
// JsonUtils.writeMessage(response, MessageType.ERROR, String.format("Bundle '%s' JAR cannot be found.", bundleId));
// return;
// }
//
// final String classSource = osgiExplorer.decompileClass(bundleJar, className);
//
// JsonUtils.writeMessage(response, MessageType.SUCCESS, "Class details",
// ImmutableMap.of(
// "className", className,
// "classSource", classSource,
// "bundleId", bundleId,
// "bundleSymbolicName", bundle.getSymbolicName(),
// "bundleJarPath", bundleJar.getAbsolutePath()
// ));
// }
//
// }
| import com.neva.felix.webconsole.plugins.search.core.BundleClass;
import com.neva.felix.webconsole.plugins.search.rest.ClassDecompileServlet;
import org.osgi.framework.BundleContext;
import java.io.Serializable;
import java.util.List; | package com.neva.felix.webconsole.plugins.search.core.classsearch;
public class ClassSearchResult implements Serializable {
private final long bundleId;
private final String className;
private final List<String> contexts;
private final String decompileUrl;
| // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/BundleClass.java
// public class BundleClass {
//
// private Bundle bundle;
//
// private String className;
//
// public BundleClass(Bundle bundle, String className) {
// this.bundle = bundle;
// this.className = className;
// }
//
// public Bundle getBundle() {
// return bundle;
// }
//
// public String getClassName() {
// return className;
// }
//
// public String getClassPath() {
// return StringUtils.replace(className, ".", "/");
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// BundleClass that = (BundleClass) o;
//
// return new EqualsBuilder()
// .append(bundle, that.bundle)
// .append(className, that.className)
// .isEquals();
// }
//
// @Override
// public int hashCode() {
// return new HashCodeBuilder()
// .append(bundle)
// .append(className)
// .toHashCode();
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/ClassDecompileServlet.java
// public class ClassDecompileServlet extends RestServlet {
//
// public static final String ALIAS_NAME = "class-decompile";
//
// public static final String BUNDLE_ID = "bundleId";
//
// public static final String CLASS_NAME = "className";
//
// private final OsgiExplorer osgiExplorer;
//
// public ClassDecompileServlet(BundleContext bundleContext) {
// super(bundleContext);
// this.osgiExplorer = new OsgiExplorer(bundleContext);
// }
//
// public static String url(BundleContext context, Bundle bundle, String className) {
// return url(context, bundle.getBundleId(), className);
// }
//
// public static String url(BundleContext context, long bundleId, String className) {
// return String.format("%s?%s=%d&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME), BUNDLE_ID, bundleId, CLASS_NAME, className);
// }
//
// @Override
// protected String getAliasName() {
// return ALIAS_NAME;
// }
//
// @Override
// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// final String bundleId = StringUtils.trimToEmpty(request.getParameter(BUNDLE_ID));
// final String className = StringUtils.trimToEmpty(request.getParameter(CLASS_NAME));
//
// final Bundle bundle = bundleContext.getBundle(Long.valueOf(bundleId));
// if (bundle == null) {
// JsonUtils.writeMessage(response, MessageType.ERROR, String.format("Bundle '%s' not be found.", bundleId));
// return;
// }
//
// final File bundleJar = osgiExplorer.findJar(Long.valueOf(bundleId));
// if (bundleJar == null) {
// JsonUtils.writeMessage(response, MessageType.ERROR, String.format("Bundle '%s' JAR cannot be found.", bundleId));
// return;
// }
//
// final String classSource = osgiExplorer.decompileClass(bundleJar, className);
//
// JsonUtils.writeMessage(response, MessageType.SUCCESS, "Class details",
// ImmutableMap.of(
// "className", className,
// "classSource", classSource,
// "bundleId", bundleId,
// "bundleSymbolicName", bundle.getSymbolicName(),
// "bundleJarPath", bundleJar.getAbsolutePath()
// ));
// }
//
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/classsearch/ClassSearchResult.java
import com.neva.felix.webconsole.plugins.search.core.BundleClass;
import com.neva.felix.webconsole.plugins.search.rest.ClassDecompileServlet;
import org.osgi.framework.BundleContext;
import java.io.Serializable;
import java.util.List;
package com.neva.felix.webconsole.plugins.search.core.classsearch;
public class ClassSearchResult implements Serializable {
private final long bundleId;
private final String className;
private final List<String> contexts;
private final String decompileUrl;
| public ClassSearchResult(BundleContext context, BundleClass clazz, List<String> contexts) { |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/core/classsearch/ClassSearchResult.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/BundleClass.java
// public class BundleClass {
//
// private Bundle bundle;
//
// private String className;
//
// public BundleClass(Bundle bundle, String className) {
// this.bundle = bundle;
// this.className = className;
// }
//
// public Bundle getBundle() {
// return bundle;
// }
//
// public String getClassName() {
// return className;
// }
//
// public String getClassPath() {
// return StringUtils.replace(className, ".", "/");
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// BundleClass that = (BundleClass) o;
//
// return new EqualsBuilder()
// .append(bundle, that.bundle)
// .append(className, that.className)
// .isEquals();
// }
//
// @Override
// public int hashCode() {
// return new HashCodeBuilder()
// .append(bundle)
// .append(className)
// .toHashCode();
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/ClassDecompileServlet.java
// public class ClassDecompileServlet extends RestServlet {
//
// public static final String ALIAS_NAME = "class-decompile";
//
// public static final String BUNDLE_ID = "bundleId";
//
// public static final String CLASS_NAME = "className";
//
// private final OsgiExplorer osgiExplorer;
//
// public ClassDecompileServlet(BundleContext bundleContext) {
// super(bundleContext);
// this.osgiExplorer = new OsgiExplorer(bundleContext);
// }
//
// public static String url(BundleContext context, Bundle bundle, String className) {
// return url(context, bundle.getBundleId(), className);
// }
//
// public static String url(BundleContext context, long bundleId, String className) {
// return String.format("%s?%s=%d&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME), BUNDLE_ID, bundleId, CLASS_NAME, className);
// }
//
// @Override
// protected String getAliasName() {
// return ALIAS_NAME;
// }
//
// @Override
// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// final String bundleId = StringUtils.trimToEmpty(request.getParameter(BUNDLE_ID));
// final String className = StringUtils.trimToEmpty(request.getParameter(CLASS_NAME));
//
// final Bundle bundle = bundleContext.getBundle(Long.valueOf(bundleId));
// if (bundle == null) {
// JsonUtils.writeMessage(response, MessageType.ERROR, String.format("Bundle '%s' not be found.", bundleId));
// return;
// }
//
// final File bundleJar = osgiExplorer.findJar(Long.valueOf(bundleId));
// if (bundleJar == null) {
// JsonUtils.writeMessage(response, MessageType.ERROR, String.format("Bundle '%s' JAR cannot be found.", bundleId));
// return;
// }
//
// final String classSource = osgiExplorer.decompileClass(bundleJar, className);
//
// JsonUtils.writeMessage(response, MessageType.SUCCESS, "Class details",
// ImmutableMap.of(
// "className", className,
// "classSource", classSource,
// "bundleId", bundleId,
// "bundleSymbolicName", bundle.getSymbolicName(),
// "bundleJarPath", bundleJar.getAbsolutePath()
// ));
// }
//
// }
| import com.neva.felix.webconsole.plugins.search.core.BundleClass;
import com.neva.felix.webconsole.plugins.search.rest.ClassDecompileServlet;
import org.osgi.framework.BundleContext;
import java.io.Serializable;
import java.util.List; | package com.neva.felix.webconsole.plugins.search.core.classsearch;
public class ClassSearchResult implements Serializable {
private final long bundleId;
private final String className;
private final List<String> contexts;
private final String decompileUrl;
public ClassSearchResult(BundleContext context, BundleClass clazz, List<String> contexts) {
this.bundleId = clazz.getBundle().getBundleId();
this.className = clazz.getClassName();
this.contexts = contexts; | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/BundleClass.java
// public class BundleClass {
//
// private Bundle bundle;
//
// private String className;
//
// public BundleClass(Bundle bundle, String className) {
// this.bundle = bundle;
// this.className = className;
// }
//
// public Bundle getBundle() {
// return bundle;
// }
//
// public String getClassName() {
// return className;
// }
//
// public String getClassPath() {
// return StringUtils.replace(className, ".", "/");
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// BundleClass that = (BundleClass) o;
//
// return new EqualsBuilder()
// .append(bundle, that.bundle)
// .append(className, that.className)
// .isEquals();
// }
//
// @Override
// public int hashCode() {
// return new HashCodeBuilder()
// .append(bundle)
// .append(className)
// .toHashCode();
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/ClassDecompileServlet.java
// public class ClassDecompileServlet extends RestServlet {
//
// public static final String ALIAS_NAME = "class-decompile";
//
// public static final String BUNDLE_ID = "bundleId";
//
// public static final String CLASS_NAME = "className";
//
// private final OsgiExplorer osgiExplorer;
//
// public ClassDecompileServlet(BundleContext bundleContext) {
// super(bundleContext);
// this.osgiExplorer = new OsgiExplorer(bundleContext);
// }
//
// public static String url(BundleContext context, Bundle bundle, String className) {
// return url(context, bundle.getBundleId(), className);
// }
//
// public static String url(BundleContext context, long bundleId, String className) {
// return String.format("%s?%s=%d&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME), BUNDLE_ID, bundleId, CLASS_NAME, className);
// }
//
// @Override
// protected String getAliasName() {
// return ALIAS_NAME;
// }
//
// @Override
// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// final String bundleId = StringUtils.trimToEmpty(request.getParameter(BUNDLE_ID));
// final String className = StringUtils.trimToEmpty(request.getParameter(CLASS_NAME));
//
// final Bundle bundle = bundleContext.getBundle(Long.valueOf(bundleId));
// if (bundle == null) {
// JsonUtils.writeMessage(response, MessageType.ERROR, String.format("Bundle '%s' not be found.", bundleId));
// return;
// }
//
// final File bundleJar = osgiExplorer.findJar(Long.valueOf(bundleId));
// if (bundleJar == null) {
// JsonUtils.writeMessage(response, MessageType.ERROR, String.format("Bundle '%s' JAR cannot be found.", bundleId));
// return;
// }
//
// final String classSource = osgiExplorer.decompileClass(bundleJar, className);
//
// JsonUtils.writeMessage(response, MessageType.SUCCESS, "Class details",
// ImmutableMap.of(
// "className", className,
// "classSource", classSource,
// "bundleId", bundleId,
// "bundleSymbolicName", bundle.getSymbolicName(),
// "bundleJarPath", bundleJar.getAbsolutePath()
// ));
// }
//
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/classsearch/ClassSearchResult.java
import com.neva.felix.webconsole.plugins.search.core.BundleClass;
import com.neva.felix.webconsole.plugins.search.rest.ClassDecompileServlet;
import org.osgi.framework.BundleContext;
import java.io.Serializable;
import java.util.List;
package com.neva.felix.webconsole.plugins.search.core.classsearch;
public class ClassSearchResult implements Serializable {
private final long bundleId;
private final String className;
private final List<String> contexts;
private final String decompileUrl;
public ClassSearchResult(BundleContext context, BundleClass clazz, List<String> contexts) {
this.bundleId = clazz.getBundle().getBundleId();
this.className = clazz.getClassName();
this.contexts = contexts; | this.decompileUrl = ClassDecompileServlet.url(context, clazz.getBundle(), clazz.getClassName()); |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchUtils.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/PrettifierUtils.java
// public final class PrettifierUtils {
//
// private PrettifierUtils() {
// // hidden constructor
// }
//
// public static String escape(String source) {
// String[] search = { "<", ">", };
// String[] replace = { "<", ">" };
//
// return StringUtils.replaceEach(source, search, replace);
// }
//
// public static String highlight(String line) {
// return String.format("<span class=\"highlighted\">%s</span>", line);
// }
//
// }
| import com.neva.felix.webconsole.plugins.search.utils.PrettifierUtils;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.lang3.StringUtils;
import java.util.Collections;
import java.util.List;
import java.util.Map; | }
/**
* Compose human readable parameter list as description
*/
public static String composeDescription(Map<String, Object> params) {
List<String> lines = Lists.newArrayList();
for (Map.Entry<String, Object> entry : params.entrySet()) {
Object value = entry.getValue();
if (value instanceof String[]) {
value = "[" + StringUtils.join((String[] )value, ", ") + "]";
}
lines.add(String.format("%s: %s", entry.getKey(), value));
}
return StringUtils.join(lines, "\n");
}
public static List<String> findContexts(String phrase, String source, int contextLineCount) {
List<String> contexts = Lists.newLinkedList();
List<String> lines = Splitter.on(LINE_DELIMITER).splitToList(source);
int i = 0;
for (String line : lines) {
if (StringUtils.containsIgnoreCase(line, phrase)) {
String before = Joiner.on("\n")
.join(lines.subList(Math.max(0, i - contextLineCount - 1), Math.max(0, i - 1)));
String after = Joiner.on("\n").join(lines.subList(Math.min(i + 1, lines.size()),
Math.min(lines.size(), i + 1 + contextLineCount))); | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/PrettifierUtils.java
// public final class PrettifierUtils {
//
// private PrettifierUtils() {
// // hidden constructor
// }
//
// public static String escape(String source) {
// String[] search = { "<", ">", };
// String[] replace = { "<", ">" };
//
// return StringUtils.replaceEach(source, search, replace);
// }
//
// public static String highlight(String line) {
// return String.format("<span class=\"highlighted\">%s</span>", line);
// }
//
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchUtils.java
import com.neva.felix.webconsole.plugins.search.utils.PrettifierUtils;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.lang3.StringUtils;
import java.util.Collections;
import java.util.List;
import java.util.Map;
}
/**
* Compose human readable parameter list as description
*/
public static String composeDescription(Map<String, Object> params) {
List<String> lines = Lists.newArrayList();
for (Map.Entry<String, Object> entry : params.entrySet()) {
Object value = entry.getValue();
if (value instanceof String[]) {
value = "[" + StringUtils.join((String[] )value, ", ") + "]";
}
lines.add(String.format("%s: %s", entry.getKey(), value));
}
return StringUtils.join(lines, "\n");
}
public static List<String> findContexts(String phrase, String source, int contextLineCount) {
List<String> contexts = Lists.newLinkedList();
List<String> lines = Splitter.on(LINE_DELIMITER).splitToList(source);
int i = 0;
for (String line : lines) {
if (StringUtils.containsIgnoreCase(line, phrase)) {
String before = Joiner.on("\n")
.join(lines.subList(Math.max(0, i - contextLineCount - 1), Math.max(0, i - 1)));
String after = Joiner.on("\n").join(lines.subList(Math.min(i + 1, lines.size()),
Math.min(lines.size(), i + 1 + contextLineCount))); | String context = PrettifierUtils.escape(before) + "\n" + PrettifierUtils |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/rest/RestServlet.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/TemplateRenderer.java
// public class TemplateRenderer {
//
// private static final Logger LOG = LoggerFactory.getLogger(TemplateRenderer.class);
//
// protected final Map<String, String> globalVars;
//
// public TemplateRenderer() {
// this(Collections.<String, String>emptyMap());
// }
//
// public TemplateRenderer(Map<String, String> globalVars) {
// this.globalVars = globalVars;
// }
//
// public static String render(String templateFile) {
// return render(templateFile, Collections.<String, String>emptyMap());
// }
//
// public static String render(String templateFile, Map<String, String> vars) {
// return new TemplateRenderer().renderTemplate(templateFile, vars);
// }
//
// public final String renderTemplate(String templateFile) {
// return renderTemplate(templateFile, Collections.<String, String>emptyMap());
// }
//
// public final String renderTemplate(String templateFile, Map<String, String> vars) {
// String result = null;
//
// InputStream templateStream = getClass().getResourceAsStream("/" + templateFile);
// if (templateStream == null) {
// LOG.error(String.format("Template '%s' cannot be found.", templateFile));
// } else {
// try {
// result = IOUtils.toString(templateStream, "UTF-8");
// } catch (IOException e) {
// LOG.error(String.format("Cannot load template '%s'", templateFile), e);
// } finally {
// IOUtils.closeQuietly(templateStream);
// }
// }
//
// final Map<String, String> allVars = ImmutableMap.<String, String>builder()
// .putAll(globalVars)
// .putAll(vars)
// .build();
//
// return StrSubstitutor.replace(result, allVars);
// }
//
// }
| import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.TemplateRenderer;
import org.osgi.framework.BundleContext;
import javax.servlet.http.HttpServlet;
import java.util.Dictionary;
import java.util.Hashtable; | package com.neva.felix.webconsole.plugins.search.rest;
public abstract class RestServlet extends HttpServlet {
protected final BundleContext bundleContext;
| // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/TemplateRenderer.java
// public class TemplateRenderer {
//
// private static final Logger LOG = LoggerFactory.getLogger(TemplateRenderer.class);
//
// protected final Map<String, String> globalVars;
//
// public TemplateRenderer() {
// this(Collections.<String, String>emptyMap());
// }
//
// public TemplateRenderer(Map<String, String> globalVars) {
// this.globalVars = globalVars;
// }
//
// public static String render(String templateFile) {
// return render(templateFile, Collections.<String, String>emptyMap());
// }
//
// public static String render(String templateFile, Map<String, String> vars) {
// return new TemplateRenderer().renderTemplate(templateFile, vars);
// }
//
// public final String renderTemplate(String templateFile) {
// return renderTemplate(templateFile, Collections.<String, String>emptyMap());
// }
//
// public final String renderTemplate(String templateFile, Map<String, String> vars) {
// String result = null;
//
// InputStream templateStream = getClass().getResourceAsStream("/" + templateFile);
// if (templateStream == null) {
// LOG.error(String.format("Template '%s' cannot be found.", templateFile));
// } else {
// try {
// result = IOUtils.toString(templateStream, "UTF-8");
// } catch (IOException e) {
// LOG.error(String.format("Cannot load template '%s'", templateFile), e);
// } finally {
// IOUtils.closeQuietly(templateStream);
// }
// }
//
// final Map<String, String> allVars = ImmutableMap.<String, String>builder()
// .putAll(globalVars)
// .putAll(vars)
// .build();
//
// return StrSubstitutor.replace(result, allVars);
// }
//
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/RestServlet.java
import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.TemplateRenderer;
import org.osgi.framework.BundleContext;
import javax.servlet.http.HttpServlet;
import java.util.Dictionary;
import java.util.Hashtable;
package com.neva.felix.webconsole.plugins.search.rest;
public abstract class RestServlet extends HttpServlet {
protected final BundleContext bundleContext;
| protected final TemplateRenderer templateRenderer; |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/rest/RestServlet.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/TemplateRenderer.java
// public class TemplateRenderer {
//
// private static final Logger LOG = LoggerFactory.getLogger(TemplateRenderer.class);
//
// protected final Map<String, String> globalVars;
//
// public TemplateRenderer() {
// this(Collections.<String, String>emptyMap());
// }
//
// public TemplateRenderer(Map<String, String> globalVars) {
// this.globalVars = globalVars;
// }
//
// public static String render(String templateFile) {
// return render(templateFile, Collections.<String, String>emptyMap());
// }
//
// public static String render(String templateFile, Map<String, String> vars) {
// return new TemplateRenderer().renderTemplate(templateFile, vars);
// }
//
// public final String renderTemplate(String templateFile) {
// return renderTemplate(templateFile, Collections.<String, String>emptyMap());
// }
//
// public final String renderTemplate(String templateFile, Map<String, String> vars) {
// String result = null;
//
// InputStream templateStream = getClass().getResourceAsStream("/" + templateFile);
// if (templateStream == null) {
// LOG.error(String.format("Template '%s' cannot be found.", templateFile));
// } else {
// try {
// result = IOUtils.toString(templateStream, "UTF-8");
// } catch (IOException e) {
// LOG.error(String.format("Cannot load template '%s'", templateFile), e);
// } finally {
// IOUtils.closeQuietly(templateStream);
// }
// }
//
// final Map<String, String> allVars = ImmutableMap.<String, String>builder()
// .putAll(globalVars)
// .putAll(vars)
// .build();
//
// return StrSubstitutor.replace(result, allVars);
// }
//
// }
| import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.TemplateRenderer;
import org.osgi.framework.BundleContext;
import javax.servlet.http.HttpServlet;
import java.util.Dictionary;
import java.util.Hashtable; | package com.neva.felix.webconsole.plugins.search.rest;
public abstract class RestServlet extends HttpServlet {
protected final BundleContext bundleContext;
protected final TemplateRenderer templateRenderer;
public RestServlet(BundleContext bundleContext) {
this.bundleContext = bundleContext;
this.templateRenderer = new TemplateRenderer();
}
protected abstract String getAliasName();
public Dictionary<String, Object> createProps() {
Dictionary<String, Object> props = new Hashtable<>();
props.put("alias", getAlias());
return props;
}
public String getAlias() { | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/TemplateRenderer.java
// public class TemplateRenderer {
//
// private static final Logger LOG = LoggerFactory.getLogger(TemplateRenderer.class);
//
// protected final Map<String, String> globalVars;
//
// public TemplateRenderer() {
// this(Collections.<String, String>emptyMap());
// }
//
// public TemplateRenderer(Map<String, String> globalVars) {
// this.globalVars = globalVars;
// }
//
// public static String render(String templateFile) {
// return render(templateFile, Collections.<String, String>emptyMap());
// }
//
// public static String render(String templateFile, Map<String, String> vars) {
// return new TemplateRenderer().renderTemplate(templateFile, vars);
// }
//
// public final String renderTemplate(String templateFile) {
// return renderTemplate(templateFile, Collections.<String, String>emptyMap());
// }
//
// public final String renderTemplate(String templateFile, Map<String, String> vars) {
// String result = null;
//
// InputStream templateStream = getClass().getResourceAsStream("/" + templateFile);
// if (templateStream == null) {
// LOG.error(String.format("Template '%s' cannot be found.", templateFile));
// } else {
// try {
// result = IOUtils.toString(templateStream, "UTF-8");
// } catch (IOException e) {
// LOG.error(String.format("Cannot load template '%s'", templateFile), e);
// } finally {
// IOUtils.closeQuietly(templateStream);
// }
// }
//
// final Map<String, String> allVars = ImmutableMap.<String, String>builder()
// .putAll(globalVars)
// .putAll(vars)
// .build();
//
// return StrSubstitutor.replace(result, allVars);
// }
//
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/RestServlet.java
import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.TemplateRenderer;
import org.osgi.framework.BundleContext;
import javax.servlet.http.HttpServlet;
import java.util.Dictionary;
import java.util.Hashtable;
package com.neva.felix.webconsole.plugins.search.rest;
public abstract class RestServlet extends HttpServlet {
protected final BundleContext bundleContext;
protected final TemplateRenderer templateRenderer;
public RestServlet(BundleContext bundleContext) {
this.bundleContext = bundleContext;
this.templateRenderer = new TemplateRenderer();
}
protected abstract String getAliasName();
public Dictionary<String, Object> createProps() {
Dictionary<String, Object> props = new Hashtable<>();
props.put("alias", getAlias());
return props;
}
public String getAlias() { | return SearchPaths.from(bundleContext).pluginAlias(getAliasName()); |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/SearchActivator.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/plugin/AbstractPlugin.java
// public abstract class AbstractPlugin extends AbstractWebConsolePlugin {
//
// public static final String CATEGORY = "OSGi";
//
// protected final BundleContext bundleContext;
//
// public AbstractPlugin(BundleContext bundleContext) {
// this.bundleContext = bundleContext;
// }
//
// @Override
// protected void renderContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// final String common = readTemplateFile("/search/common.html");
// final String specific = readTemplateFile("/" + getLabel() + "/plugin.html");
// final String content = StrSubstitutor.replace(specific, ImmutableMap.of("common", common));
//
// response.getWriter().write(content);
// }
//
// protected Dictionary<String, Object> createProps() {
// final Dictionary<String, Object> props = new Hashtable<>();
//
// props.put("felix.webconsole.label", getLabel());
// props.put("felix.webconsole.category", CATEGORY);
//
// return props;
// }
//
// public void register() {
// bundleContext.registerService(Servlet.class.getName(), this, createProps());
// }
//
// public URL getResource(final String path) {
// String prefix = "/" + getLabel() + "/";
// if (path.startsWith(prefix)) {
// return this.getClass().getResource(path);
// }
//
// return null;
// }
//
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/plugin/SearchPlugin.java
// public class SearchPlugin extends AbstractPlugin {
//
// public static final String LABEL = "search";
//
// public static final String TITLE = "Search";
//
// public SearchPlugin(BundleContext bundleContext) {
// super(bundleContext);
// }
//
// @Override
// public String getLabel() {
// return LABEL;
// }
//
// @Override
// public String getTitle() {
// return TITLE;
// }
//
// }
| import com.neva.felix.webconsole.plugins.search.plugin.AbstractPlugin;
import com.neva.felix.webconsole.plugins.search.plugin.SearchPlugin;
import com.google.common.collect.ImmutableSet;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import java.util.Set; | package com.neva.felix.webconsole.plugins.search;
public class SearchActivator implements BundleActivator {
private SearchHttpTracker httpTracker;
@Override
public void start(BundleContext bundleContext) throws Exception { | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/plugin/AbstractPlugin.java
// public abstract class AbstractPlugin extends AbstractWebConsolePlugin {
//
// public static final String CATEGORY = "OSGi";
//
// protected final BundleContext bundleContext;
//
// public AbstractPlugin(BundleContext bundleContext) {
// this.bundleContext = bundleContext;
// }
//
// @Override
// protected void renderContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// final String common = readTemplateFile("/search/common.html");
// final String specific = readTemplateFile("/" + getLabel() + "/plugin.html");
// final String content = StrSubstitutor.replace(specific, ImmutableMap.of("common", common));
//
// response.getWriter().write(content);
// }
//
// protected Dictionary<String, Object> createProps() {
// final Dictionary<String, Object> props = new Hashtable<>();
//
// props.put("felix.webconsole.label", getLabel());
// props.put("felix.webconsole.category", CATEGORY);
//
// return props;
// }
//
// public void register() {
// bundleContext.registerService(Servlet.class.getName(), this, createProps());
// }
//
// public URL getResource(final String path) {
// String prefix = "/" + getLabel() + "/";
// if (path.startsWith(prefix)) {
// return this.getClass().getResource(path);
// }
//
// return null;
// }
//
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/plugin/SearchPlugin.java
// public class SearchPlugin extends AbstractPlugin {
//
// public static final String LABEL = "search";
//
// public static final String TITLE = "Search";
//
// public SearchPlugin(BundleContext bundleContext) {
// super(bundleContext);
// }
//
// @Override
// public String getLabel() {
// return LABEL;
// }
//
// @Override
// public String getTitle() {
// return TITLE;
// }
//
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/SearchActivator.java
import com.neva.felix.webconsole.plugins.search.plugin.AbstractPlugin;
import com.neva.felix.webconsole.plugins.search.plugin.SearchPlugin;
import com.google.common.collect.ImmutableSet;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import java.util.Set;
package com.neva.felix.webconsole.plugins.search;
public class SearchActivator implements BundleActivator {
private SearchHttpTracker httpTracker;
@Override
public void start(BundleContext bundleContext) throws Exception { | for (AbstractPlugin plugin : getPlugins(bundleContext)) { |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/SearchActivator.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/plugin/AbstractPlugin.java
// public abstract class AbstractPlugin extends AbstractWebConsolePlugin {
//
// public static final String CATEGORY = "OSGi";
//
// protected final BundleContext bundleContext;
//
// public AbstractPlugin(BundleContext bundleContext) {
// this.bundleContext = bundleContext;
// }
//
// @Override
// protected void renderContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// final String common = readTemplateFile("/search/common.html");
// final String specific = readTemplateFile("/" + getLabel() + "/plugin.html");
// final String content = StrSubstitutor.replace(specific, ImmutableMap.of("common", common));
//
// response.getWriter().write(content);
// }
//
// protected Dictionary<String, Object> createProps() {
// final Dictionary<String, Object> props = new Hashtable<>();
//
// props.put("felix.webconsole.label", getLabel());
// props.put("felix.webconsole.category", CATEGORY);
//
// return props;
// }
//
// public void register() {
// bundleContext.registerService(Servlet.class.getName(), this, createProps());
// }
//
// public URL getResource(final String path) {
// String prefix = "/" + getLabel() + "/";
// if (path.startsWith(prefix)) {
// return this.getClass().getResource(path);
// }
//
// return null;
// }
//
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/plugin/SearchPlugin.java
// public class SearchPlugin extends AbstractPlugin {
//
// public static final String LABEL = "search";
//
// public static final String TITLE = "Search";
//
// public SearchPlugin(BundleContext bundleContext) {
// super(bundleContext);
// }
//
// @Override
// public String getLabel() {
// return LABEL;
// }
//
// @Override
// public String getTitle() {
// return TITLE;
// }
//
// }
| import com.neva.felix.webconsole.plugins.search.plugin.AbstractPlugin;
import com.neva.felix.webconsole.plugins.search.plugin.SearchPlugin;
import com.google.common.collect.ImmutableSet;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import java.util.Set; | package com.neva.felix.webconsole.plugins.search;
public class SearchActivator implements BundleActivator {
private SearchHttpTracker httpTracker;
@Override
public void start(BundleContext bundleContext) throws Exception {
for (AbstractPlugin plugin : getPlugins(bundleContext)) {
plugin.register();
}
httpTracker = new SearchHttpTracker(bundleContext);
httpTracker.open();
}
@Override
public void stop(BundleContext bundleContext) throws Exception {
httpTracker.close();
httpTracker = null;
}
private Set<AbstractPlugin> getPlugins(BundleContext bundleContext) {
return ImmutableSet.<AbstractPlugin>of( | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/plugin/AbstractPlugin.java
// public abstract class AbstractPlugin extends AbstractWebConsolePlugin {
//
// public static final String CATEGORY = "OSGi";
//
// protected final BundleContext bundleContext;
//
// public AbstractPlugin(BundleContext bundleContext) {
// this.bundleContext = bundleContext;
// }
//
// @Override
// protected void renderContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// final String common = readTemplateFile("/search/common.html");
// final String specific = readTemplateFile("/" + getLabel() + "/plugin.html");
// final String content = StrSubstitutor.replace(specific, ImmutableMap.of("common", common));
//
// response.getWriter().write(content);
// }
//
// protected Dictionary<String, Object> createProps() {
// final Dictionary<String, Object> props = new Hashtable<>();
//
// props.put("felix.webconsole.label", getLabel());
// props.put("felix.webconsole.category", CATEGORY);
//
// return props;
// }
//
// public void register() {
// bundleContext.registerService(Servlet.class.getName(), this, createProps());
// }
//
// public URL getResource(final String path) {
// String prefix = "/" + getLabel() + "/";
// if (path.startsWith(prefix)) {
// return this.getClass().getResource(path);
// }
//
// return null;
// }
//
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/plugin/SearchPlugin.java
// public class SearchPlugin extends AbstractPlugin {
//
// public static final String LABEL = "search";
//
// public static final String TITLE = "Search";
//
// public SearchPlugin(BundleContext bundleContext) {
// super(bundleContext);
// }
//
// @Override
// public String getLabel() {
// return LABEL;
// }
//
// @Override
// public String getTitle() {
// return TITLE;
// }
//
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/SearchActivator.java
import com.neva.felix.webconsole.plugins.search.plugin.AbstractPlugin;
import com.neva.felix.webconsole.plugins.search.plugin.SearchPlugin;
import com.google.common.collect.ImmutableSet;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import java.util.Set;
package com.neva.felix.webconsole.plugins.search;
public class SearchActivator implements BundleActivator {
private SearchHttpTracker httpTracker;
@Override
public void start(BundleContext bundleContext) throws Exception {
for (AbstractPlugin plugin : getPlugins(bundleContext)) {
plugin.register();
}
httpTracker = new SearchHttpTracker(bundleContext);
httpTracker.open();
}
@Override
public void stop(BundleContext bundleContext) throws Exception {
httpTracker.close();
httpTracker = null;
}
private Set<AbstractPlugin> getPlugins(BundleContext bundleContext) {
return ImmutableSet.<AbstractPlugin>of( | new SearchPlugin(bundleContext) |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/utils/BundleUtils.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
| import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import java.util.Map; | package com.neva.felix.webconsole.plugins.search.utils;
public class BundleUtils {
public static String consolePath(BundleContext context, Bundle bundle) {
return consolePath(context, bundle.getBundleId());
}
public static String consolePath(BundleContext context, long bundleId) { | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/BundleUtils.java
import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import java.util.Map;
package com.neva.felix.webconsole.plugins.search.utils;
public class BundleUtils {
public static String consolePath(BundleContext context, Bundle bundle) {
return consolePath(context, bundle.getBundleId());
}
public static String consolePath(BundleContext context, long bundleId) { | return SearchPaths.from(context).appAlias("bundles") + "/" + String.valueOf(bundleId); |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/rest/FileDownloadServlet.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/io/FileDownloader.java
// public final class FileDownloader {
//
// private final HttpServletResponse response;
//
// private final MemoryStream fileContent;
//
// private final String fileName;
//
// public FileDownloader(HttpServletResponse response, InputStream input, String fileName) {
// this.response = response;
// this.fileContent = new MemoryStream(input);
// this.fileName = fileName;
// }
//
// public void download() throws IOException {
// setResponseHeaders();
// writeResponseOutput();
// }
//
// private void setResponseHeaders() throws IOException {
// response.setContentLength(fileContent.getLength());
// response.setContentType("application/force-download");
// response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader("Content-Disposition",
// String.format("attachment; filename=\"%s\"", fileName.trim()));
// response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// response.setHeader("Pragma", "no-cache");
// }
//
// private void writeResponseOutput() throws IOException {
// fileContent.writeOutput(response.getOutputStream());
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public enum MessageType {
// SUCCESS,
// ERROR
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public static void writeMessage(HttpServletResponse response, MessageType type, String text)
// throws IOException {
// writeMessage(response, type, text, Collections.<String, Object>emptyMap());
// }
| import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.io.FileDownloader;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage; | package com.neva.felix.webconsole.plugins.search.rest;
public class FileDownloadServlet extends RestServlet {
public static final String ALIAS_NAME = "file-download";
private static final Logger LOG = LoggerFactory.getLogger(FileDownloadServlet.class);
public FileDownloadServlet(BundleContext bundleContext) {
super(bundleContext);
}
public static String url(BundleContext context, String path, String fileName) { | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/io/FileDownloader.java
// public final class FileDownloader {
//
// private final HttpServletResponse response;
//
// private final MemoryStream fileContent;
//
// private final String fileName;
//
// public FileDownloader(HttpServletResponse response, InputStream input, String fileName) {
// this.response = response;
// this.fileContent = new MemoryStream(input);
// this.fileName = fileName;
// }
//
// public void download() throws IOException {
// setResponseHeaders();
// writeResponseOutput();
// }
//
// private void setResponseHeaders() throws IOException {
// response.setContentLength(fileContent.getLength());
// response.setContentType("application/force-download");
// response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader("Content-Disposition",
// String.format("attachment; filename=\"%s\"", fileName.trim()));
// response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// response.setHeader("Pragma", "no-cache");
// }
//
// private void writeResponseOutput() throws IOException {
// fileContent.writeOutput(response.getOutputStream());
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public enum MessageType {
// SUCCESS,
// ERROR
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public static void writeMessage(HttpServletResponse response, MessageType type, String text)
// throws IOException {
// writeMessage(response, type, text, Collections.<String, Object>emptyMap());
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/FileDownloadServlet.java
import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.io.FileDownloader;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage;
package com.neva.felix.webconsole.plugins.search.rest;
public class FileDownloadServlet extends RestServlet {
public static final String ALIAS_NAME = "file-download";
private static final Logger LOG = LoggerFactory.getLogger(FileDownloadServlet.class);
public FileDownloadServlet(BundleContext bundleContext) {
super(bundleContext);
}
public static String url(BundleContext context, String path, String fileName) { | return String.format("%s?%s=%s&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME), |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/rest/FileDownloadServlet.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/io/FileDownloader.java
// public final class FileDownloader {
//
// private final HttpServletResponse response;
//
// private final MemoryStream fileContent;
//
// private final String fileName;
//
// public FileDownloader(HttpServletResponse response, InputStream input, String fileName) {
// this.response = response;
// this.fileContent = new MemoryStream(input);
// this.fileName = fileName;
// }
//
// public void download() throws IOException {
// setResponseHeaders();
// writeResponseOutput();
// }
//
// private void setResponseHeaders() throws IOException {
// response.setContentLength(fileContent.getLength());
// response.setContentType("application/force-download");
// response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader("Content-Disposition",
// String.format("attachment; filename=\"%s\"", fileName.trim()));
// response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// response.setHeader("Pragma", "no-cache");
// }
//
// private void writeResponseOutput() throws IOException {
// fileContent.writeOutput(response.getOutputStream());
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public enum MessageType {
// SUCCESS,
// ERROR
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public static void writeMessage(HttpServletResponse response, MessageType type, String text)
// throws IOException {
// writeMessage(response, type, text, Collections.<String, Object>emptyMap());
// }
| import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.io.FileDownloader;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage; | package com.neva.felix.webconsole.plugins.search.rest;
public class FileDownloadServlet extends RestServlet {
public static final String ALIAS_NAME = "file-download";
private static final Logger LOG = LoggerFactory.getLogger(FileDownloadServlet.class);
public FileDownloadServlet(BundleContext bundleContext) {
super(bundleContext);
}
public static String url(BundleContext context, String path, String fileName) {
return String.format("%s?%s=%s&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME),
RestParams.PATH_PARAM, path, RestParams.NAME_PARAM, fileName);
}
@Override
protected String getAliasName() {
return ALIAS_NAME;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
final RestParams params = RestParams.from(request);
final String path = params.getString(RestParams.PATH_PARAM);
final String name = StringUtils.defaultIfBlank(params.getString(RestParams.NAME_PARAM), UUID.randomUUID().toString());
final File file = new File(path);
if (!file.exists()) { | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/io/FileDownloader.java
// public final class FileDownloader {
//
// private final HttpServletResponse response;
//
// private final MemoryStream fileContent;
//
// private final String fileName;
//
// public FileDownloader(HttpServletResponse response, InputStream input, String fileName) {
// this.response = response;
// this.fileContent = new MemoryStream(input);
// this.fileName = fileName;
// }
//
// public void download() throws IOException {
// setResponseHeaders();
// writeResponseOutput();
// }
//
// private void setResponseHeaders() throws IOException {
// response.setContentLength(fileContent.getLength());
// response.setContentType("application/force-download");
// response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader("Content-Disposition",
// String.format("attachment; filename=\"%s\"", fileName.trim()));
// response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// response.setHeader("Pragma", "no-cache");
// }
//
// private void writeResponseOutput() throws IOException {
// fileContent.writeOutput(response.getOutputStream());
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public enum MessageType {
// SUCCESS,
// ERROR
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public static void writeMessage(HttpServletResponse response, MessageType type, String text)
// throws IOException {
// writeMessage(response, type, text, Collections.<String, Object>emptyMap());
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/FileDownloadServlet.java
import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.io.FileDownloader;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage;
package com.neva.felix.webconsole.plugins.search.rest;
public class FileDownloadServlet extends RestServlet {
public static final String ALIAS_NAME = "file-download";
private static final Logger LOG = LoggerFactory.getLogger(FileDownloadServlet.class);
public FileDownloadServlet(BundleContext bundleContext) {
super(bundleContext);
}
public static String url(BundleContext context, String path, String fileName) {
return String.format("%s?%s=%s&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME),
RestParams.PATH_PARAM, path, RestParams.NAME_PARAM, fileName);
}
@Override
protected String getAliasName() {
return ALIAS_NAME;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
final RestParams params = RestParams.from(request);
final String path = params.getString(RestParams.PATH_PARAM);
final String name = StringUtils.defaultIfBlank(params.getString(RestParams.NAME_PARAM), UUID.randomUUID().toString());
final File file = new File(path);
if (!file.exists()) { | writeMessage(response, MessageType.ERROR, String.format("File at path '%s' cannot be found.", path)); |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/rest/FileDownloadServlet.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/io/FileDownloader.java
// public final class FileDownloader {
//
// private final HttpServletResponse response;
//
// private final MemoryStream fileContent;
//
// private final String fileName;
//
// public FileDownloader(HttpServletResponse response, InputStream input, String fileName) {
// this.response = response;
// this.fileContent = new MemoryStream(input);
// this.fileName = fileName;
// }
//
// public void download() throws IOException {
// setResponseHeaders();
// writeResponseOutput();
// }
//
// private void setResponseHeaders() throws IOException {
// response.setContentLength(fileContent.getLength());
// response.setContentType("application/force-download");
// response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader("Content-Disposition",
// String.format("attachment; filename=\"%s\"", fileName.trim()));
// response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// response.setHeader("Pragma", "no-cache");
// }
//
// private void writeResponseOutput() throws IOException {
// fileContent.writeOutput(response.getOutputStream());
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public enum MessageType {
// SUCCESS,
// ERROR
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public static void writeMessage(HttpServletResponse response, MessageType type, String text)
// throws IOException {
// writeMessage(response, type, text, Collections.<String, Object>emptyMap());
// }
| import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.io.FileDownloader;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage; | package com.neva.felix.webconsole.plugins.search.rest;
public class FileDownloadServlet extends RestServlet {
public static final String ALIAS_NAME = "file-download";
private static final Logger LOG = LoggerFactory.getLogger(FileDownloadServlet.class);
public FileDownloadServlet(BundleContext bundleContext) {
super(bundleContext);
}
public static String url(BundleContext context, String path, String fileName) {
return String.format("%s?%s=%s&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME),
RestParams.PATH_PARAM, path, RestParams.NAME_PARAM, fileName);
}
@Override
protected String getAliasName() {
return ALIAS_NAME;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
final RestParams params = RestParams.from(request);
final String path = params.getString(RestParams.PATH_PARAM);
final String name = StringUtils.defaultIfBlank(params.getString(RestParams.NAME_PARAM), UUID.randomUUID().toString());
final File file = new File(path);
if (!file.exists()) { | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/io/FileDownloader.java
// public final class FileDownloader {
//
// private final HttpServletResponse response;
//
// private final MemoryStream fileContent;
//
// private final String fileName;
//
// public FileDownloader(HttpServletResponse response, InputStream input, String fileName) {
// this.response = response;
// this.fileContent = new MemoryStream(input);
// this.fileName = fileName;
// }
//
// public void download() throws IOException {
// setResponseHeaders();
// writeResponseOutput();
// }
//
// private void setResponseHeaders() throws IOException {
// response.setContentLength(fileContent.getLength());
// response.setContentType("application/force-download");
// response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader("Content-Disposition",
// String.format("attachment; filename=\"%s\"", fileName.trim()));
// response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// response.setHeader("Pragma", "no-cache");
// }
//
// private void writeResponseOutput() throws IOException {
// fileContent.writeOutput(response.getOutputStream());
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public enum MessageType {
// SUCCESS,
// ERROR
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public static void writeMessage(HttpServletResponse response, MessageType type, String text)
// throws IOException {
// writeMessage(response, type, text, Collections.<String, Object>emptyMap());
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/FileDownloadServlet.java
import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.io.FileDownloader;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage;
package com.neva.felix.webconsole.plugins.search.rest;
public class FileDownloadServlet extends RestServlet {
public static final String ALIAS_NAME = "file-download";
private static final Logger LOG = LoggerFactory.getLogger(FileDownloadServlet.class);
public FileDownloadServlet(BundleContext bundleContext) {
super(bundleContext);
}
public static String url(BundleContext context, String path, String fileName) {
return String.format("%s?%s=%s&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME),
RestParams.PATH_PARAM, path, RestParams.NAME_PARAM, fileName);
}
@Override
protected String getAliasName() {
return ALIAS_NAME;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
final RestParams params = RestParams.from(request);
final String path = params.getString(RestParams.PATH_PARAM);
final String name = StringUtils.defaultIfBlank(params.getString(RestParams.NAME_PARAM), UUID.randomUUID().toString());
final File file = new File(path);
if (!file.exists()) { | writeMessage(response, MessageType.ERROR, String.format("File at path '%s' cannot be found.", path)); |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/rest/FileDownloadServlet.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/io/FileDownloader.java
// public final class FileDownloader {
//
// private final HttpServletResponse response;
//
// private final MemoryStream fileContent;
//
// private final String fileName;
//
// public FileDownloader(HttpServletResponse response, InputStream input, String fileName) {
// this.response = response;
// this.fileContent = new MemoryStream(input);
// this.fileName = fileName;
// }
//
// public void download() throws IOException {
// setResponseHeaders();
// writeResponseOutput();
// }
//
// private void setResponseHeaders() throws IOException {
// response.setContentLength(fileContent.getLength());
// response.setContentType("application/force-download");
// response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader("Content-Disposition",
// String.format("attachment; filename=\"%s\"", fileName.trim()));
// response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// response.setHeader("Pragma", "no-cache");
// }
//
// private void writeResponseOutput() throws IOException {
// fileContent.writeOutput(response.getOutputStream());
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public enum MessageType {
// SUCCESS,
// ERROR
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public static void writeMessage(HttpServletResponse response, MessageType type, String text)
// throws IOException {
// writeMessage(response, type, text, Collections.<String, Object>emptyMap());
// }
| import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.io.FileDownloader;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage; | package com.neva.felix.webconsole.plugins.search.rest;
public class FileDownloadServlet extends RestServlet {
public static final String ALIAS_NAME = "file-download";
private static final Logger LOG = LoggerFactory.getLogger(FileDownloadServlet.class);
public FileDownloadServlet(BundleContext bundleContext) {
super(bundleContext);
}
public static String url(BundleContext context, String path, String fileName) {
return String.format("%s?%s=%s&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME),
RestParams.PATH_PARAM, path, RestParams.NAME_PARAM, fileName);
}
@Override
protected String getAliasName() {
return ALIAS_NAME;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
final RestParams params = RestParams.from(request);
final String path = params.getString(RestParams.PATH_PARAM);
final String name = StringUtils.defaultIfBlank(params.getString(RestParams.NAME_PARAM), UUID.randomUUID().toString());
final File file = new File(path);
if (!file.exists()) {
writeMessage(response, MessageType.ERROR, String.format("File at path '%s' cannot be found.", path));
} else { | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/io/FileDownloader.java
// public final class FileDownloader {
//
// private final HttpServletResponse response;
//
// private final MemoryStream fileContent;
//
// private final String fileName;
//
// public FileDownloader(HttpServletResponse response, InputStream input, String fileName) {
// this.response = response;
// this.fileContent = new MemoryStream(input);
// this.fileName = fileName;
// }
//
// public void download() throws IOException {
// setResponseHeaders();
// writeResponseOutput();
// }
//
// private void setResponseHeaders() throws IOException {
// response.setContentLength(fileContent.getLength());
// response.setContentType("application/force-download");
// response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader("Content-Disposition",
// String.format("attachment; filename=\"%s\"", fileName.trim()));
// response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// response.setHeader("Pragma", "no-cache");
// }
//
// private void writeResponseOutput() throws IOException {
// fileContent.writeOutput(response.getOutputStream());
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public enum MessageType {
// SUCCESS,
// ERROR
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public static void writeMessage(HttpServletResponse response, MessageType type, String text)
// throws IOException {
// writeMessage(response, type, text, Collections.<String, Object>emptyMap());
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/FileDownloadServlet.java
import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.io.FileDownloader;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage;
package com.neva.felix.webconsole.plugins.search.rest;
public class FileDownloadServlet extends RestServlet {
public static final String ALIAS_NAME = "file-download";
private static final Logger LOG = LoggerFactory.getLogger(FileDownloadServlet.class);
public FileDownloadServlet(BundleContext bundleContext) {
super(bundleContext);
}
public static String url(BundleContext context, String path, String fileName) {
return String.format("%s?%s=%s&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME),
RestParams.PATH_PARAM, path, RestParams.NAME_PARAM, fileName);
}
@Override
protected String getAliasName() {
return ALIAS_NAME;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
final RestParams params = RestParams.from(request);
final String path = params.getString(RestParams.PATH_PARAM);
final String name = StringUtils.defaultIfBlank(params.getString(RestParams.NAME_PARAM), UUID.randomUUID().toString());
final File file = new File(path);
if (!file.exists()) {
writeMessage(response, MessageType.ERROR, String.format("File at path '%s' cannot be found.", path));
} else { | new FileDownloader(response, new FileInputStream(file), name).download(); |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Interactor.java
// public interface Interactor extends Runnable{
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
| import com.tonilopezmr.interactorexecutor.Interactor;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException; | package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public interface SubjectUseCase extends Interactor {
interface Callback { | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Interactor.java
// public interface Interactor extends Runnable{
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
import com.tonilopezmr.interactorexecutor.Interactor;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public interface SubjectUseCase extends Interactor {
interface Callback { | void onMissionAccomplished(Subject subject); |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java | // Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
| import com.tonilopezmr.sample.domain.Subject; | package com.tonilopezmr.sample.ui.viewmodel;
/**
* Created by toni on 05/02/15.
*/
public class SubjectViewModelImp implements SubjectViewModel {
private int id;
private String name;
public SubjectViewModelImp(String name) {
this.name = name;
}
| // Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java
import com.tonilopezmr.sample.domain.Subject;
package com.tonilopezmr.sample.ui.viewmodel;
/**
* Created by toni on 05/02/15.
*/
public class SubjectViewModelImp implements SubjectViewModel {
private int id;
private String name;
public SubjectViewModelImp(String name) {
this.name = name;
}
| public SubjectViewModelImp(Subject subject) { |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/di/modules/PresenterModule.java | // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/MainPresenter.java
// public interface MainPresenter extends SubjectListPresenter,CreateSubjectPresenter {
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
// public class SubjectListPresenterImp extends BasePresenter implements MainPresenter {
//
// private SubjectListView view;
//
// private GetSubjectListUseCase subjectListUseCase;
// private SubjectUseCase createSubjectUseCase;
// private SubjectUseCase deleteSubjectUseCase;
//
// public SubjectListPresenterImp(Context context, GetSubjectListUseCase subjectListUseCase,
// @Named("create usecase") SubjectUseCase createSubjectUseCase,
// @Named("delete usecase") SubjectUseCase deleteSubjectUseCase) {
// super(context);
// this.createSubjectUseCase = createSubjectUseCase;
// this.deleteSubjectUseCase = deleteSubjectUseCase;
// this.subjectListUseCase = subjectListUseCase;
// }
//
// @Override
// public void setView(SubjectListView view){
// this.view = view;
// }
//
// @Override
// public void onInit() {
// view.showProgress();
// showSubjects();
// }
//
// private void showSubjects(){
// subjectListUseCase.execute(new GetSubjectListUseCase.Callback() {
// @Override
// public void onSubjectListLoaded(Collection<Subject> subjects) {
// view.showSubjects(convertToViewModel(subjects));
// view.hideProgress();
// }
//
// @Override
// public void onError(SubjectException exception) {
// view.showMessage(exception.getMessage()); //For example
// view.hideProgress();
// view.showLayoutError();
// Log.i(getClass().toString(), "¡¡Show error!!");
// }
// });
// }
//
// private Collection<SubjectViewModel> convertToViewModel(Collection<Subject> subjectsCollection){
// Collection<SubjectViewModel> subjectsViewModel = new ArrayList<>();
//
// for (Subject subject : subjectsCollection){
// subjectsViewModel.add(new SubjectViewModelImp(subject));
// }
//
// return subjectsViewModel;
// }
//
// @Override
// public void onClickItem(SubjectViewModel subjectModel) {
// view.showMessage("the subject: "+subjectModel);
// }
//
// @Override
// public void onLongItemClick(SubjectViewModel subjectModel) {
// deleteSubjectUseCase.execute(new Subject(subjectModel.getId(), subjectModel.getName()), new SubjectUseCase.Callback() {
// @Override
// public void onMissionAccomplished(Subject subject) {
// view.remove(new SubjectViewModelImp(subject));
// view.showMessage("Mission accomplished, "+subject+", it has been deleted.");
// }
//
// @Override
// public void onError(SubjectException ex) {
// view.showMessage(ex.getMessage());
// }
// });
// }
//
// @Override
// public void onRetryButtonClick() {
// view.hideLayoutError();
// onInit();
// }
//
// @Override
// public void onFloatingButtonClick(final SubjectViewModel subjectModel) {
// createSubjectUseCase.execute(new Subject(subjectModel.getName()), new SubjectUseCase.Callback() {
// @Override
// public void onMissionAccomplished(Subject subject) {
// view.add(new SubjectViewModelImp(subject));
// view.showMessage("Create new subject number "+subject.getId());
// }
//
// @Override
// public void onError(SubjectException ex) {
// view.showMessage(ex.getMessage());
// }
// });
// }
//
// }
| import android.content.Context;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.presenter.MainPresenter;
import com.tonilopezmr.sample.ui.presenter.SubjectListPresenterImp;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides; | package com.tonilopezmr.sample.di.modules;
/**
* @author Antonio López.
*/
@Module(
complete = false,
library = true
)
public class PresenterModule {
@Provides | // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/MainPresenter.java
// public interface MainPresenter extends SubjectListPresenter,CreateSubjectPresenter {
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
// public class SubjectListPresenterImp extends BasePresenter implements MainPresenter {
//
// private SubjectListView view;
//
// private GetSubjectListUseCase subjectListUseCase;
// private SubjectUseCase createSubjectUseCase;
// private SubjectUseCase deleteSubjectUseCase;
//
// public SubjectListPresenterImp(Context context, GetSubjectListUseCase subjectListUseCase,
// @Named("create usecase") SubjectUseCase createSubjectUseCase,
// @Named("delete usecase") SubjectUseCase deleteSubjectUseCase) {
// super(context);
// this.createSubjectUseCase = createSubjectUseCase;
// this.deleteSubjectUseCase = deleteSubjectUseCase;
// this.subjectListUseCase = subjectListUseCase;
// }
//
// @Override
// public void setView(SubjectListView view){
// this.view = view;
// }
//
// @Override
// public void onInit() {
// view.showProgress();
// showSubjects();
// }
//
// private void showSubjects(){
// subjectListUseCase.execute(new GetSubjectListUseCase.Callback() {
// @Override
// public void onSubjectListLoaded(Collection<Subject> subjects) {
// view.showSubjects(convertToViewModel(subjects));
// view.hideProgress();
// }
//
// @Override
// public void onError(SubjectException exception) {
// view.showMessage(exception.getMessage()); //For example
// view.hideProgress();
// view.showLayoutError();
// Log.i(getClass().toString(), "¡¡Show error!!");
// }
// });
// }
//
// private Collection<SubjectViewModel> convertToViewModel(Collection<Subject> subjectsCollection){
// Collection<SubjectViewModel> subjectsViewModel = new ArrayList<>();
//
// for (Subject subject : subjectsCollection){
// subjectsViewModel.add(new SubjectViewModelImp(subject));
// }
//
// return subjectsViewModel;
// }
//
// @Override
// public void onClickItem(SubjectViewModel subjectModel) {
// view.showMessage("the subject: "+subjectModel);
// }
//
// @Override
// public void onLongItemClick(SubjectViewModel subjectModel) {
// deleteSubjectUseCase.execute(new Subject(subjectModel.getId(), subjectModel.getName()), new SubjectUseCase.Callback() {
// @Override
// public void onMissionAccomplished(Subject subject) {
// view.remove(new SubjectViewModelImp(subject));
// view.showMessage("Mission accomplished, "+subject+", it has been deleted.");
// }
//
// @Override
// public void onError(SubjectException ex) {
// view.showMessage(ex.getMessage());
// }
// });
// }
//
// @Override
// public void onRetryButtonClick() {
// view.hideLayoutError();
// onInit();
// }
//
// @Override
// public void onFloatingButtonClick(final SubjectViewModel subjectModel) {
// createSubjectUseCase.execute(new Subject(subjectModel.getName()), new SubjectUseCase.Callback() {
// @Override
// public void onMissionAccomplished(Subject subject) {
// view.add(new SubjectViewModelImp(subject));
// view.showMessage("Create new subject number "+subject.getId());
// }
//
// @Override
// public void onError(SubjectException ex) {
// view.showMessage(ex.getMessage());
// }
// });
// }
//
// }
// Path: app/src/main/java/com/tonilopezmr/sample/di/modules/PresenterModule.java
import android.content.Context;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.presenter.MainPresenter;
import com.tonilopezmr.sample.ui.presenter.SubjectListPresenterImp;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides;
package com.tonilopezmr.sample.di.modules;
/**
* @author Antonio López.
*/
@Module(
complete = false,
library = true
)
public class PresenterModule {
@Provides | public MainPresenter provideMainPresenter(Context context, GetSubjectListUseCase subjectListUseCase, |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/di/modules/PresenterModule.java | // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/MainPresenter.java
// public interface MainPresenter extends SubjectListPresenter,CreateSubjectPresenter {
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
// public class SubjectListPresenterImp extends BasePresenter implements MainPresenter {
//
// private SubjectListView view;
//
// private GetSubjectListUseCase subjectListUseCase;
// private SubjectUseCase createSubjectUseCase;
// private SubjectUseCase deleteSubjectUseCase;
//
// public SubjectListPresenterImp(Context context, GetSubjectListUseCase subjectListUseCase,
// @Named("create usecase") SubjectUseCase createSubjectUseCase,
// @Named("delete usecase") SubjectUseCase deleteSubjectUseCase) {
// super(context);
// this.createSubjectUseCase = createSubjectUseCase;
// this.deleteSubjectUseCase = deleteSubjectUseCase;
// this.subjectListUseCase = subjectListUseCase;
// }
//
// @Override
// public void setView(SubjectListView view){
// this.view = view;
// }
//
// @Override
// public void onInit() {
// view.showProgress();
// showSubjects();
// }
//
// private void showSubjects(){
// subjectListUseCase.execute(new GetSubjectListUseCase.Callback() {
// @Override
// public void onSubjectListLoaded(Collection<Subject> subjects) {
// view.showSubjects(convertToViewModel(subjects));
// view.hideProgress();
// }
//
// @Override
// public void onError(SubjectException exception) {
// view.showMessage(exception.getMessage()); //For example
// view.hideProgress();
// view.showLayoutError();
// Log.i(getClass().toString(), "¡¡Show error!!");
// }
// });
// }
//
// private Collection<SubjectViewModel> convertToViewModel(Collection<Subject> subjectsCollection){
// Collection<SubjectViewModel> subjectsViewModel = new ArrayList<>();
//
// for (Subject subject : subjectsCollection){
// subjectsViewModel.add(new SubjectViewModelImp(subject));
// }
//
// return subjectsViewModel;
// }
//
// @Override
// public void onClickItem(SubjectViewModel subjectModel) {
// view.showMessage("the subject: "+subjectModel);
// }
//
// @Override
// public void onLongItemClick(SubjectViewModel subjectModel) {
// deleteSubjectUseCase.execute(new Subject(subjectModel.getId(), subjectModel.getName()), new SubjectUseCase.Callback() {
// @Override
// public void onMissionAccomplished(Subject subject) {
// view.remove(new SubjectViewModelImp(subject));
// view.showMessage("Mission accomplished, "+subject+", it has been deleted.");
// }
//
// @Override
// public void onError(SubjectException ex) {
// view.showMessage(ex.getMessage());
// }
// });
// }
//
// @Override
// public void onRetryButtonClick() {
// view.hideLayoutError();
// onInit();
// }
//
// @Override
// public void onFloatingButtonClick(final SubjectViewModel subjectModel) {
// createSubjectUseCase.execute(new Subject(subjectModel.getName()), new SubjectUseCase.Callback() {
// @Override
// public void onMissionAccomplished(Subject subject) {
// view.add(new SubjectViewModelImp(subject));
// view.showMessage("Create new subject number "+subject.getId());
// }
//
// @Override
// public void onError(SubjectException ex) {
// view.showMessage(ex.getMessage());
// }
// });
// }
//
// }
| import android.content.Context;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.presenter.MainPresenter;
import com.tonilopezmr.sample.ui.presenter.SubjectListPresenterImp;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides; | package com.tonilopezmr.sample.di.modules;
/**
* @author Antonio López.
*/
@Module(
complete = false,
library = true
)
public class PresenterModule {
@Provides | // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/MainPresenter.java
// public interface MainPresenter extends SubjectListPresenter,CreateSubjectPresenter {
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
// public class SubjectListPresenterImp extends BasePresenter implements MainPresenter {
//
// private SubjectListView view;
//
// private GetSubjectListUseCase subjectListUseCase;
// private SubjectUseCase createSubjectUseCase;
// private SubjectUseCase deleteSubjectUseCase;
//
// public SubjectListPresenterImp(Context context, GetSubjectListUseCase subjectListUseCase,
// @Named("create usecase") SubjectUseCase createSubjectUseCase,
// @Named("delete usecase") SubjectUseCase deleteSubjectUseCase) {
// super(context);
// this.createSubjectUseCase = createSubjectUseCase;
// this.deleteSubjectUseCase = deleteSubjectUseCase;
// this.subjectListUseCase = subjectListUseCase;
// }
//
// @Override
// public void setView(SubjectListView view){
// this.view = view;
// }
//
// @Override
// public void onInit() {
// view.showProgress();
// showSubjects();
// }
//
// private void showSubjects(){
// subjectListUseCase.execute(new GetSubjectListUseCase.Callback() {
// @Override
// public void onSubjectListLoaded(Collection<Subject> subjects) {
// view.showSubjects(convertToViewModel(subjects));
// view.hideProgress();
// }
//
// @Override
// public void onError(SubjectException exception) {
// view.showMessage(exception.getMessage()); //For example
// view.hideProgress();
// view.showLayoutError();
// Log.i(getClass().toString(), "¡¡Show error!!");
// }
// });
// }
//
// private Collection<SubjectViewModel> convertToViewModel(Collection<Subject> subjectsCollection){
// Collection<SubjectViewModel> subjectsViewModel = new ArrayList<>();
//
// for (Subject subject : subjectsCollection){
// subjectsViewModel.add(new SubjectViewModelImp(subject));
// }
//
// return subjectsViewModel;
// }
//
// @Override
// public void onClickItem(SubjectViewModel subjectModel) {
// view.showMessage("the subject: "+subjectModel);
// }
//
// @Override
// public void onLongItemClick(SubjectViewModel subjectModel) {
// deleteSubjectUseCase.execute(new Subject(subjectModel.getId(), subjectModel.getName()), new SubjectUseCase.Callback() {
// @Override
// public void onMissionAccomplished(Subject subject) {
// view.remove(new SubjectViewModelImp(subject));
// view.showMessage("Mission accomplished, "+subject+", it has been deleted.");
// }
//
// @Override
// public void onError(SubjectException ex) {
// view.showMessage(ex.getMessage());
// }
// });
// }
//
// @Override
// public void onRetryButtonClick() {
// view.hideLayoutError();
// onInit();
// }
//
// @Override
// public void onFloatingButtonClick(final SubjectViewModel subjectModel) {
// createSubjectUseCase.execute(new Subject(subjectModel.getName()), new SubjectUseCase.Callback() {
// @Override
// public void onMissionAccomplished(Subject subject) {
// view.add(new SubjectViewModelImp(subject));
// view.showMessage("Create new subject number "+subject.getId());
// }
//
// @Override
// public void onError(SubjectException ex) {
// view.showMessage(ex.getMessage());
// }
// });
// }
//
// }
// Path: app/src/main/java/com/tonilopezmr/sample/di/modules/PresenterModule.java
import android.content.Context;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.presenter.MainPresenter;
import com.tonilopezmr.sample.ui.presenter.SubjectListPresenterImp;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides;
package com.tonilopezmr.sample.di.modules;
/**
* @author Antonio López.
*/
@Module(
complete = false,
library = true
)
public class PresenterModule {
@Provides | public MainPresenter provideMainPresenter(Context context, GetSubjectListUseCase subjectListUseCase, |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/di/modules/PresenterModule.java | // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/MainPresenter.java
// public interface MainPresenter extends SubjectListPresenter,CreateSubjectPresenter {
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
// public class SubjectListPresenterImp extends BasePresenter implements MainPresenter {
//
// private SubjectListView view;
//
// private GetSubjectListUseCase subjectListUseCase;
// private SubjectUseCase createSubjectUseCase;
// private SubjectUseCase deleteSubjectUseCase;
//
// public SubjectListPresenterImp(Context context, GetSubjectListUseCase subjectListUseCase,
// @Named("create usecase") SubjectUseCase createSubjectUseCase,
// @Named("delete usecase") SubjectUseCase deleteSubjectUseCase) {
// super(context);
// this.createSubjectUseCase = createSubjectUseCase;
// this.deleteSubjectUseCase = deleteSubjectUseCase;
// this.subjectListUseCase = subjectListUseCase;
// }
//
// @Override
// public void setView(SubjectListView view){
// this.view = view;
// }
//
// @Override
// public void onInit() {
// view.showProgress();
// showSubjects();
// }
//
// private void showSubjects(){
// subjectListUseCase.execute(new GetSubjectListUseCase.Callback() {
// @Override
// public void onSubjectListLoaded(Collection<Subject> subjects) {
// view.showSubjects(convertToViewModel(subjects));
// view.hideProgress();
// }
//
// @Override
// public void onError(SubjectException exception) {
// view.showMessage(exception.getMessage()); //For example
// view.hideProgress();
// view.showLayoutError();
// Log.i(getClass().toString(), "¡¡Show error!!");
// }
// });
// }
//
// private Collection<SubjectViewModel> convertToViewModel(Collection<Subject> subjectsCollection){
// Collection<SubjectViewModel> subjectsViewModel = new ArrayList<>();
//
// for (Subject subject : subjectsCollection){
// subjectsViewModel.add(new SubjectViewModelImp(subject));
// }
//
// return subjectsViewModel;
// }
//
// @Override
// public void onClickItem(SubjectViewModel subjectModel) {
// view.showMessage("the subject: "+subjectModel);
// }
//
// @Override
// public void onLongItemClick(SubjectViewModel subjectModel) {
// deleteSubjectUseCase.execute(new Subject(subjectModel.getId(), subjectModel.getName()), new SubjectUseCase.Callback() {
// @Override
// public void onMissionAccomplished(Subject subject) {
// view.remove(new SubjectViewModelImp(subject));
// view.showMessage("Mission accomplished, "+subject+", it has been deleted.");
// }
//
// @Override
// public void onError(SubjectException ex) {
// view.showMessage(ex.getMessage());
// }
// });
// }
//
// @Override
// public void onRetryButtonClick() {
// view.hideLayoutError();
// onInit();
// }
//
// @Override
// public void onFloatingButtonClick(final SubjectViewModel subjectModel) {
// createSubjectUseCase.execute(new Subject(subjectModel.getName()), new SubjectUseCase.Callback() {
// @Override
// public void onMissionAccomplished(Subject subject) {
// view.add(new SubjectViewModelImp(subject));
// view.showMessage("Create new subject number "+subject.getId());
// }
//
// @Override
// public void onError(SubjectException ex) {
// view.showMessage(ex.getMessage());
// }
// });
// }
//
// }
| import android.content.Context;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.presenter.MainPresenter;
import com.tonilopezmr.sample.ui.presenter.SubjectListPresenterImp;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides; | package com.tonilopezmr.sample.di.modules;
/**
* @author Antonio López.
*/
@Module(
complete = false,
library = true
)
public class PresenterModule {
@Provides
public MainPresenter provideMainPresenter(Context context, GetSubjectListUseCase subjectListUseCase, | // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/MainPresenter.java
// public interface MainPresenter extends SubjectListPresenter,CreateSubjectPresenter {
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
// public class SubjectListPresenterImp extends BasePresenter implements MainPresenter {
//
// private SubjectListView view;
//
// private GetSubjectListUseCase subjectListUseCase;
// private SubjectUseCase createSubjectUseCase;
// private SubjectUseCase deleteSubjectUseCase;
//
// public SubjectListPresenterImp(Context context, GetSubjectListUseCase subjectListUseCase,
// @Named("create usecase") SubjectUseCase createSubjectUseCase,
// @Named("delete usecase") SubjectUseCase deleteSubjectUseCase) {
// super(context);
// this.createSubjectUseCase = createSubjectUseCase;
// this.deleteSubjectUseCase = deleteSubjectUseCase;
// this.subjectListUseCase = subjectListUseCase;
// }
//
// @Override
// public void setView(SubjectListView view){
// this.view = view;
// }
//
// @Override
// public void onInit() {
// view.showProgress();
// showSubjects();
// }
//
// private void showSubjects(){
// subjectListUseCase.execute(new GetSubjectListUseCase.Callback() {
// @Override
// public void onSubjectListLoaded(Collection<Subject> subjects) {
// view.showSubjects(convertToViewModel(subjects));
// view.hideProgress();
// }
//
// @Override
// public void onError(SubjectException exception) {
// view.showMessage(exception.getMessage()); //For example
// view.hideProgress();
// view.showLayoutError();
// Log.i(getClass().toString(), "¡¡Show error!!");
// }
// });
// }
//
// private Collection<SubjectViewModel> convertToViewModel(Collection<Subject> subjectsCollection){
// Collection<SubjectViewModel> subjectsViewModel = new ArrayList<>();
//
// for (Subject subject : subjectsCollection){
// subjectsViewModel.add(new SubjectViewModelImp(subject));
// }
//
// return subjectsViewModel;
// }
//
// @Override
// public void onClickItem(SubjectViewModel subjectModel) {
// view.showMessage("the subject: "+subjectModel);
// }
//
// @Override
// public void onLongItemClick(SubjectViewModel subjectModel) {
// deleteSubjectUseCase.execute(new Subject(subjectModel.getId(), subjectModel.getName()), new SubjectUseCase.Callback() {
// @Override
// public void onMissionAccomplished(Subject subject) {
// view.remove(new SubjectViewModelImp(subject));
// view.showMessage("Mission accomplished, "+subject+", it has been deleted.");
// }
//
// @Override
// public void onError(SubjectException ex) {
// view.showMessage(ex.getMessage());
// }
// });
// }
//
// @Override
// public void onRetryButtonClick() {
// view.hideLayoutError();
// onInit();
// }
//
// @Override
// public void onFloatingButtonClick(final SubjectViewModel subjectModel) {
// createSubjectUseCase.execute(new Subject(subjectModel.getName()), new SubjectUseCase.Callback() {
// @Override
// public void onMissionAccomplished(Subject subject) {
// view.add(new SubjectViewModelImp(subject));
// view.showMessage("Create new subject number "+subject.getId());
// }
//
// @Override
// public void onError(SubjectException ex) {
// view.showMessage(ex.getMessage());
// }
// });
// }
//
// }
// Path: app/src/main/java/com/tonilopezmr/sample/di/modules/PresenterModule.java
import android.content.Context;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.presenter.MainPresenter;
import com.tonilopezmr.sample.ui.presenter.SubjectListPresenterImp;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides;
package com.tonilopezmr.sample.di.modules;
/**
* @author Antonio López.
*/
@Module(
complete = false,
library = true
)
public class PresenterModule {
@Provides
public MainPresenter provideMainPresenter(Context context, GetSubjectListUseCase subjectListUseCase, | @Named("create usecase") SubjectUseCase createSubjectUseCase, |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/di/modules/PresenterModule.java | // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/MainPresenter.java
// public interface MainPresenter extends SubjectListPresenter,CreateSubjectPresenter {
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
// public class SubjectListPresenterImp extends BasePresenter implements MainPresenter {
//
// private SubjectListView view;
//
// private GetSubjectListUseCase subjectListUseCase;
// private SubjectUseCase createSubjectUseCase;
// private SubjectUseCase deleteSubjectUseCase;
//
// public SubjectListPresenterImp(Context context, GetSubjectListUseCase subjectListUseCase,
// @Named("create usecase") SubjectUseCase createSubjectUseCase,
// @Named("delete usecase") SubjectUseCase deleteSubjectUseCase) {
// super(context);
// this.createSubjectUseCase = createSubjectUseCase;
// this.deleteSubjectUseCase = deleteSubjectUseCase;
// this.subjectListUseCase = subjectListUseCase;
// }
//
// @Override
// public void setView(SubjectListView view){
// this.view = view;
// }
//
// @Override
// public void onInit() {
// view.showProgress();
// showSubjects();
// }
//
// private void showSubjects(){
// subjectListUseCase.execute(new GetSubjectListUseCase.Callback() {
// @Override
// public void onSubjectListLoaded(Collection<Subject> subjects) {
// view.showSubjects(convertToViewModel(subjects));
// view.hideProgress();
// }
//
// @Override
// public void onError(SubjectException exception) {
// view.showMessage(exception.getMessage()); //For example
// view.hideProgress();
// view.showLayoutError();
// Log.i(getClass().toString(), "¡¡Show error!!");
// }
// });
// }
//
// private Collection<SubjectViewModel> convertToViewModel(Collection<Subject> subjectsCollection){
// Collection<SubjectViewModel> subjectsViewModel = new ArrayList<>();
//
// for (Subject subject : subjectsCollection){
// subjectsViewModel.add(new SubjectViewModelImp(subject));
// }
//
// return subjectsViewModel;
// }
//
// @Override
// public void onClickItem(SubjectViewModel subjectModel) {
// view.showMessage("the subject: "+subjectModel);
// }
//
// @Override
// public void onLongItemClick(SubjectViewModel subjectModel) {
// deleteSubjectUseCase.execute(new Subject(subjectModel.getId(), subjectModel.getName()), new SubjectUseCase.Callback() {
// @Override
// public void onMissionAccomplished(Subject subject) {
// view.remove(new SubjectViewModelImp(subject));
// view.showMessage("Mission accomplished, "+subject+", it has been deleted.");
// }
//
// @Override
// public void onError(SubjectException ex) {
// view.showMessage(ex.getMessage());
// }
// });
// }
//
// @Override
// public void onRetryButtonClick() {
// view.hideLayoutError();
// onInit();
// }
//
// @Override
// public void onFloatingButtonClick(final SubjectViewModel subjectModel) {
// createSubjectUseCase.execute(new Subject(subjectModel.getName()), new SubjectUseCase.Callback() {
// @Override
// public void onMissionAccomplished(Subject subject) {
// view.add(new SubjectViewModelImp(subject));
// view.showMessage("Create new subject number "+subject.getId());
// }
//
// @Override
// public void onError(SubjectException ex) {
// view.showMessage(ex.getMessage());
// }
// });
// }
//
// }
| import android.content.Context;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.presenter.MainPresenter;
import com.tonilopezmr.sample.ui.presenter.SubjectListPresenterImp;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides; | package com.tonilopezmr.sample.di.modules;
/**
* @author Antonio López.
*/
@Module(
complete = false,
library = true
)
public class PresenterModule {
@Provides
public MainPresenter provideMainPresenter(Context context, GetSubjectListUseCase subjectListUseCase,
@Named("create usecase") SubjectUseCase createSubjectUseCase,
@Named("delete usecase") SubjectUseCase deleteSubjectUseCase){ | // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/MainPresenter.java
// public interface MainPresenter extends SubjectListPresenter,CreateSubjectPresenter {
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
// public class SubjectListPresenterImp extends BasePresenter implements MainPresenter {
//
// private SubjectListView view;
//
// private GetSubjectListUseCase subjectListUseCase;
// private SubjectUseCase createSubjectUseCase;
// private SubjectUseCase deleteSubjectUseCase;
//
// public SubjectListPresenterImp(Context context, GetSubjectListUseCase subjectListUseCase,
// @Named("create usecase") SubjectUseCase createSubjectUseCase,
// @Named("delete usecase") SubjectUseCase deleteSubjectUseCase) {
// super(context);
// this.createSubjectUseCase = createSubjectUseCase;
// this.deleteSubjectUseCase = deleteSubjectUseCase;
// this.subjectListUseCase = subjectListUseCase;
// }
//
// @Override
// public void setView(SubjectListView view){
// this.view = view;
// }
//
// @Override
// public void onInit() {
// view.showProgress();
// showSubjects();
// }
//
// private void showSubjects(){
// subjectListUseCase.execute(new GetSubjectListUseCase.Callback() {
// @Override
// public void onSubjectListLoaded(Collection<Subject> subjects) {
// view.showSubjects(convertToViewModel(subjects));
// view.hideProgress();
// }
//
// @Override
// public void onError(SubjectException exception) {
// view.showMessage(exception.getMessage()); //For example
// view.hideProgress();
// view.showLayoutError();
// Log.i(getClass().toString(), "¡¡Show error!!");
// }
// });
// }
//
// private Collection<SubjectViewModel> convertToViewModel(Collection<Subject> subjectsCollection){
// Collection<SubjectViewModel> subjectsViewModel = new ArrayList<>();
//
// for (Subject subject : subjectsCollection){
// subjectsViewModel.add(new SubjectViewModelImp(subject));
// }
//
// return subjectsViewModel;
// }
//
// @Override
// public void onClickItem(SubjectViewModel subjectModel) {
// view.showMessage("the subject: "+subjectModel);
// }
//
// @Override
// public void onLongItemClick(SubjectViewModel subjectModel) {
// deleteSubjectUseCase.execute(new Subject(subjectModel.getId(), subjectModel.getName()), new SubjectUseCase.Callback() {
// @Override
// public void onMissionAccomplished(Subject subject) {
// view.remove(new SubjectViewModelImp(subject));
// view.showMessage("Mission accomplished, "+subject+", it has been deleted.");
// }
//
// @Override
// public void onError(SubjectException ex) {
// view.showMessage(ex.getMessage());
// }
// });
// }
//
// @Override
// public void onRetryButtonClick() {
// view.hideLayoutError();
// onInit();
// }
//
// @Override
// public void onFloatingButtonClick(final SubjectViewModel subjectModel) {
// createSubjectUseCase.execute(new Subject(subjectModel.getName()), new SubjectUseCase.Callback() {
// @Override
// public void onMissionAccomplished(Subject subject) {
// view.add(new SubjectViewModelImp(subject));
// view.showMessage("Create new subject number "+subject.getId());
// }
//
// @Override
// public void onError(SubjectException ex) {
// view.showMessage(ex.getMessage());
// }
// });
// }
//
// }
// Path: app/src/main/java/com/tonilopezmr/sample/di/modules/PresenterModule.java
import android.content.Context;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.presenter.MainPresenter;
import com.tonilopezmr.sample.ui.presenter.SubjectListPresenterImp;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides;
package com.tonilopezmr.sample.di.modules;
/**
* @author Antonio López.
*/
@Module(
complete = false,
library = true
)
public class PresenterModule {
@Provides
public MainPresenter provideMainPresenter(Context context, GetSubjectListUseCase subjectListUseCase,
@Named("create usecase") SubjectUseCase createSubjectUseCase,
@Named("delete usecase") SubjectUseCase deleteSubjectUseCase){ | return new SubjectListPresenterImp(context, subjectListUseCase, createSubjectUseCase, deleteSubjectUseCase); |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/di/modules/RepositoryModule.java | // Path: app/src/main/java/com/tonilopezmr/sample/data/SQLite/entity/mapper/SubjectEntityMapper.java
// public class SubjectEntityMapper implements SubjectMapper<SubjectEntity>{
//
// public SubjectEntityMapper() {
// }
//
// public Subject mapToSubject(SubjectEntity subjectEntity){
// return new Subject(subjectEntity.getId(), subjectEntity.getName());
// }
//
// public SubjectEntity mapToSubjectEntity(Subject subject){
// return new SubjectEntity(subject.getId(), subject.getName());
// }
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/mapper/SubjectMapper.java
// public interface SubjectMapper<T> {
//
// public Subject mapToSubject(T subjectEntity);
//
// public T mapToSubjectEntity(Subject subject);
// }
| import android.content.Context;
import com.tonilopezmr.sample.data.SQLite.entity.mapper.SubjectEntityMapper;
import com.tonilopezmr.sample.data.SQLite.repository.SubjectDataRepository;
import com.tonilopezmr.sample.data.mock.MockSubjectRepository;
import com.tonilopezmr.sample.domain.mapper.SubjectMapper;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides; | package com.tonilopezmr.sample.di.modules;
/**
*
* @author Toni
*/
@Module(
complete = false,
library = true
)
public final class RepositoryModule {
@Provides | // Path: app/src/main/java/com/tonilopezmr/sample/data/SQLite/entity/mapper/SubjectEntityMapper.java
// public class SubjectEntityMapper implements SubjectMapper<SubjectEntity>{
//
// public SubjectEntityMapper() {
// }
//
// public Subject mapToSubject(SubjectEntity subjectEntity){
// return new Subject(subjectEntity.getId(), subjectEntity.getName());
// }
//
// public SubjectEntity mapToSubjectEntity(Subject subject){
// return new SubjectEntity(subject.getId(), subject.getName());
// }
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/mapper/SubjectMapper.java
// public interface SubjectMapper<T> {
//
// public Subject mapToSubject(T subjectEntity);
//
// public T mapToSubjectEntity(Subject subject);
// }
// Path: app/src/main/java/com/tonilopezmr/sample/di/modules/RepositoryModule.java
import android.content.Context;
import com.tonilopezmr.sample.data.SQLite.entity.mapper.SubjectEntityMapper;
import com.tonilopezmr.sample.data.SQLite.repository.SubjectDataRepository;
import com.tonilopezmr.sample.data.mock.MockSubjectRepository;
import com.tonilopezmr.sample.domain.mapper.SubjectMapper;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides;
package com.tonilopezmr.sample.di.modules;
/**
*
* @author Toni
*/
@Module(
complete = false,
library = true
)
public final class RepositoryModule {
@Provides | public SubjectMapper provideSubjectMapper(){ |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/di/modules/RepositoryModule.java | // Path: app/src/main/java/com/tonilopezmr/sample/data/SQLite/entity/mapper/SubjectEntityMapper.java
// public class SubjectEntityMapper implements SubjectMapper<SubjectEntity>{
//
// public SubjectEntityMapper() {
// }
//
// public Subject mapToSubject(SubjectEntity subjectEntity){
// return new Subject(subjectEntity.getId(), subjectEntity.getName());
// }
//
// public SubjectEntity mapToSubjectEntity(Subject subject){
// return new SubjectEntity(subject.getId(), subject.getName());
// }
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/mapper/SubjectMapper.java
// public interface SubjectMapper<T> {
//
// public Subject mapToSubject(T subjectEntity);
//
// public T mapToSubjectEntity(Subject subject);
// }
| import android.content.Context;
import com.tonilopezmr.sample.data.SQLite.entity.mapper.SubjectEntityMapper;
import com.tonilopezmr.sample.data.SQLite.repository.SubjectDataRepository;
import com.tonilopezmr.sample.data.mock.MockSubjectRepository;
import com.tonilopezmr.sample.domain.mapper.SubjectMapper;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides; | package com.tonilopezmr.sample.di.modules;
/**
*
* @author Toni
*/
@Module(
complete = false,
library = true
)
public final class RepositoryModule {
@Provides
public SubjectMapper provideSubjectMapper(){ | // Path: app/src/main/java/com/tonilopezmr/sample/data/SQLite/entity/mapper/SubjectEntityMapper.java
// public class SubjectEntityMapper implements SubjectMapper<SubjectEntity>{
//
// public SubjectEntityMapper() {
// }
//
// public Subject mapToSubject(SubjectEntity subjectEntity){
// return new Subject(subjectEntity.getId(), subjectEntity.getName());
// }
//
// public SubjectEntity mapToSubjectEntity(Subject subject){
// return new SubjectEntity(subject.getId(), subject.getName());
// }
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/mapper/SubjectMapper.java
// public interface SubjectMapper<T> {
//
// public Subject mapToSubject(T subjectEntity);
//
// public T mapToSubjectEntity(Subject subject);
// }
// Path: app/src/main/java/com/tonilopezmr/sample/di/modules/RepositoryModule.java
import android.content.Context;
import com.tonilopezmr.sample.data.SQLite.entity.mapper.SubjectEntityMapper;
import com.tonilopezmr.sample.data.SQLite.repository.SubjectDataRepository;
import com.tonilopezmr.sample.data.mock.MockSubjectRepository;
import com.tonilopezmr.sample.domain.mapper.SubjectMapper;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides;
package com.tonilopezmr.sample.di.modules;
/**
*
* @author Toni
*/
@Module(
complete = false,
library = true
)
public final class RepositoryModule {
@Provides
public SubjectMapper provideSubjectMapper(){ | return new SubjectEntityMapper(); |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/di/modules/ExecutorModule.java | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/ThreadExecutor.java
// public class ThreadExecutor implements Executor{
//
// private static final int CORE_POOL_SIZE = 3;
// private static final int MAX_POOL_SIZE = 5;
// private static final int KEEP_ALIVE_TIME = 120;
// private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
// private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue();
//
// private ThreadPoolExecutor threadPoolexecutor;
//
// public ThreadExecutor() {
// int corePoolSize = CORE_POOL_SIZE;
// int maxPoolSize = MAX_POOL_SIZE;
// int keepAliveTime = KEEP_ALIVE_TIME;
// TimeUnit timeUnit = TIME_UNIT;
// BlockingQueue<Runnable> workQueue = WORK_QUEUE;
//
// threadPoolexecutor =
// new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
// }
//
// public ThreadExecutor(final int corePoolSize, final int maxPoolSize,
// final int keepAliveTime, final TimeUnit timeUnit) {
//
// BlockingQueue<Runnable> workQueue = WORK_QUEUE;
//
// threadPoolexecutor =
// new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
// }
//
// @Override
// public void run(final Interactor interactor) {
// if (interactor == null) {
// throw new IllegalArgumentException("Interactor to execute can't be null");
// }
//
// threadPoolexecutor.submit(interactor);
// }
//
//
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/executor/MainThreadImp.java
// public class MainThreadImp implements MainThread {
//
// private Handler handler;
//
// public MainThreadImp() {
// this.handler = new Handler(Looper.getMainLooper());
// }
//
// @Override
// public void post(Runnable runnable) {
// handler.post(runnable);
// }
// }
| import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.interactorexecutor.ThreadExecutor;
import com.tonilopezmr.sample.domain.executor.MainThreadImp;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides; | package com.tonilopezmr.sample.di.modules;
/**
*
* @author Toni
*/
@Module(
complete = false,
library = true
)
public final class ExecutorModule {
@Provides
@Singleton | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/ThreadExecutor.java
// public class ThreadExecutor implements Executor{
//
// private static final int CORE_POOL_SIZE = 3;
// private static final int MAX_POOL_SIZE = 5;
// private static final int KEEP_ALIVE_TIME = 120;
// private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
// private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue();
//
// private ThreadPoolExecutor threadPoolexecutor;
//
// public ThreadExecutor() {
// int corePoolSize = CORE_POOL_SIZE;
// int maxPoolSize = MAX_POOL_SIZE;
// int keepAliveTime = KEEP_ALIVE_TIME;
// TimeUnit timeUnit = TIME_UNIT;
// BlockingQueue<Runnable> workQueue = WORK_QUEUE;
//
// threadPoolexecutor =
// new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
// }
//
// public ThreadExecutor(final int corePoolSize, final int maxPoolSize,
// final int keepAliveTime, final TimeUnit timeUnit) {
//
// BlockingQueue<Runnable> workQueue = WORK_QUEUE;
//
// threadPoolexecutor =
// new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
// }
//
// @Override
// public void run(final Interactor interactor) {
// if (interactor == null) {
// throw new IllegalArgumentException("Interactor to execute can't be null");
// }
//
// threadPoolexecutor.submit(interactor);
// }
//
//
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/executor/MainThreadImp.java
// public class MainThreadImp implements MainThread {
//
// private Handler handler;
//
// public MainThreadImp() {
// this.handler = new Handler(Looper.getMainLooper());
// }
//
// @Override
// public void post(Runnable runnable) {
// handler.post(runnable);
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/di/modules/ExecutorModule.java
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.interactorexecutor.ThreadExecutor;
import com.tonilopezmr.sample.domain.executor.MainThreadImp;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
package com.tonilopezmr.sample.di.modules;
/**
*
* @author Toni
*/
@Module(
complete = false,
library = true
)
public final class ExecutorModule {
@Provides
@Singleton | public Executor provideThreadExecutor(){ |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/di/modules/ExecutorModule.java | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/ThreadExecutor.java
// public class ThreadExecutor implements Executor{
//
// private static final int CORE_POOL_SIZE = 3;
// private static final int MAX_POOL_SIZE = 5;
// private static final int KEEP_ALIVE_TIME = 120;
// private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
// private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue();
//
// private ThreadPoolExecutor threadPoolexecutor;
//
// public ThreadExecutor() {
// int corePoolSize = CORE_POOL_SIZE;
// int maxPoolSize = MAX_POOL_SIZE;
// int keepAliveTime = KEEP_ALIVE_TIME;
// TimeUnit timeUnit = TIME_UNIT;
// BlockingQueue<Runnable> workQueue = WORK_QUEUE;
//
// threadPoolexecutor =
// new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
// }
//
// public ThreadExecutor(final int corePoolSize, final int maxPoolSize,
// final int keepAliveTime, final TimeUnit timeUnit) {
//
// BlockingQueue<Runnable> workQueue = WORK_QUEUE;
//
// threadPoolexecutor =
// new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
// }
//
// @Override
// public void run(final Interactor interactor) {
// if (interactor == null) {
// throw new IllegalArgumentException("Interactor to execute can't be null");
// }
//
// threadPoolexecutor.submit(interactor);
// }
//
//
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/executor/MainThreadImp.java
// public class MainThreadImp implements MainThread {
//
// private Handler handler;
//
// public MainThreadImp() {
// this.handler = new Handler(Looper.getMainLooper());
// }
//
// @Override
// public void post(Runnable runnable) {
// handler.post(runnable);
// }
// }
| import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.interactorexecutor.ThreadExecutor;
import com.tonilopezmr.sample.domain.executor.MainThreadImp;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides; | package com.tonilopezmr.sample.di.modules;
/**
*
* @author Toni
*/
@Module(
complete = false,
library = true
)
public final class ExecutorModule {
@Provides
@Singleton
public Executor provideThreadExecutor(){ | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/ThreadExecutor.java
// public class ThreadExecutor implements Executor{
//
// private static final int CORE_POOL_SIZE = 3;
// private static final int MAX_POOL_SIZE = 5;
// private static final int KEEP_ALIVE_TIME = 120;
// private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
// private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue();
//
// private ThreadPoolExecutor threadPoolexecutor;
//
// public ThreadExecutor() {
// int corePoolSize = CORE_POOL_SIZE;
// int maxPoolSize = MAX_POOL_SIZE;
// int keepAliveTime = KEEP_ALIVE_TIME;
// TimeUnit timeUnit = TIME_UNIT;
// BlockingQueue<Runnable> workQueue = WORK_QUEUE;
//
// threadPoolexecutor =
// new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
// }
//
// public ThreadExecutor(final int corePoolSize, final int maxPoolSize,
// final int keepAliveTime, final TimeUnit timeUnit) {
//
// BlockingQueue<Runnable> workQueue = WORK_QUEUE;
//
// threadPoolexecutor =
// new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
// }
//
// @Override
// public void run(final Interactor interactor) {
// if (interactor == null) {
// throw new IllegalArgumentException("Interactor to execute can't be null");
// }
//
// threadPoolexecutor.submit(interactor);
// }
//
//
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/executor/MainThreadImp.java
// public class MainThreadImp implements MainThread {
//
// private Handler handler;
//
// public MainThreadImp() {
// this.handler = new Handler(Looper.getMainLooper());
// }
//
// @Override
// public void post(Runnable runnable) {
// handler.post(runnable);
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/di/modules/ExecutorModule.java
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.interactorexecutor.ThreadExecutor;
import com.tonilopezmr.sample.domain.executor.MainThreadImp;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
package com.tonilopezmr.sample.di.modules;
/**
*
* @author Toni
*/
@Module(
complete = false,
library = true
)
public final class ExecutorModule {
@Provides
@Singleton
public Executor provideThreadExecutor(){ | return new ThreadExecutor(); |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/di/modules/ExecutorModule.java | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/ThreadExecutor.java
// public class ThreadExecutor implements Executor{
//
// private static final int CORE_POOL_SIZE = 3;
// private static final int MAX_POOL_SIZE = 5;
// private static final int KEEP_ALIVE_TIME = 120;
// private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
// private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue();
//
// private ThreadPoolExecutor threadPoolexecutor;
//
// public ThreadExecutor() {
// int corePoolSize = CORE_POOL_SIZE;
// int maxPoolSize = MAX_POOL_SIZE;
// int keepAliveTime = KEEP_ALIVE_TIME;
// TimeUnit timeUnit = TIME_UNIT;
// BlockingQueue<Runnable> workQueue = WORK_QUEUE;
//
// threadPoolexecutor =
// new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
// }
//
// public ThreadExecutor(final int corePoolSize, final int maxPoolSize,
// final int keepAliveTime, final TimeUnit timeUnit) {
//
// BlockingQueue<Runnable> workQueue = WORK_QUEUE;
//
// threadPoolexecutor =
// new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
// }
//
// @Override
// public void run(final Interactor interactor) {
// if (interactor == null) {
// throw new IllegalArgumentException("Interactor to execute can't be null");
// }
//
// threadPoolexecutor.submit(interactor);
// }
//
//
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/executor/MainThreadImp.java
// public class MainThreadImp implements MainThread {
//
// private Handler handler;
//
// public MainThreadImp() {
// this.handler = new Handler(Looper.getMainLooper());
// }
//
// @Override
// public void post(Runnable runnable) {
// handler.post(runnable);
// }
// }
| import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.interactorexecutor.ThreadExecutor;
import com.tonilopezmr.sample.domain.executor.MainThreadImp;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides; | package com.tonilopezmr.sample.di.modules;
/**
*
* @author Toni
*/
@Module(
complete = false,
library = true
)
public final class ExecutorModule {
@Provides
@Singleton
public Executor provideThreadExecutor(){
return new ThreadExecutor();
}
@Provides
@Singleton | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/ThreadExecutor.java
// public class ThreadExecutor implements Executor{
//
// private static final int CORE_POOL_SIZE = 3;
// private static final int MAX_POOL_SIZE = 5;
// private static final int KEEP_ALIVE_TIME = 120;
// private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
// private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue();
//
// private ThreadPoolExecutor threadPoolexecutor;
//
// public ThreadExecutor() {
// int corePoolSize = CORE_POOL_SIZE;
// int maxPoolSize = MAX_POOL_SIZE;
// int keepAliveTime = KEEP_ALIVE_TIME;
// TimeUnit timeUnit = TIME_UNIT;
// BlockingQueue<Runnable> workQueue = WORK_QUEUE;
//
// threadPoolexecutor =
// new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
// }
//
// public ThreadExecutor(final int corePoolSize, final int maxPoolSize,
// final int keepAliveTime, final TimeUnit timeUnit) {
//
// BlockingQueue<Runnable> workQueue = WORK_QUEUE;
//
// threadPoolexecutor =
// new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
// }
//
// @Override
// public void run(final Interactor interactor) {
// if (interactor == null) {
// throw new IllegalArgumentException("Interactor to execute can't be null");
// }
//
// threadPoolexecutor.submit(interactor);
// }
//
//
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/executor/MainThreadImp.java
// public class MainThreadImp implements MainThread {
//
// private Handler handler;
//
// public MainThreadImp() {
// this.handler = new Handler(Looper.getMainLooper());
// }
//
// @Override
// public void post(Runnable runnable) {
// handler.post(runnable);
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/di/modules/ExecutorModule.java
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.interactorexecutor.ThreadExecutor;
import com.tonilopezmr.sample.domain.executor.MainThreadImp;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
package com.tonilopezmr.sample.di.modules;
/**
*
* @author Toni
*/
@Module(
complete = false,
library = true
)
public final class ExecutorModule {
@Provides
@Singleton
public Executor provideThreadExecutor(){
return new ThreadExecutor();
}
@Provides
@Singleton | public MainThread provideMainThreadImp(){ |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/di/modules/ExecutorModule.java | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/ThreadExecutor.java
// public class ThreadExecutor implements Executor{
//
// private static final int CORE_POOL_SIZE = 3;
// private static final int MAX_POOL_SIZE = 5;
// private static final int KEEP_ALIVE_TIME = 120;
// private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
// private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue();
//
// private ThreadPoolExecutor threadPoolexecutor;
//
// public ThreadExecutor() {
// int corePoolSize = CORE_POOL_SIZE;
// int maxPoolSize = MAX_POOL_SIZE;
// int keepAliveTime = KEEP_ALIVE_TIME;
// TimeUnit timeUnit = TIME_UNIT;
// BlockingQueue<Runnable> workQueue = WORK_QUEUE;
//
// threadPoolexecutor =
// new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
// }
//
// public ThreadExecutor(final int corePoolSize, final int maxPoolSize,
// final int keepAliveTime, final TimeUnit timeUnit) {
//
// BlockingQueue<Runnable> workQueue = WORK_QUEUE;
//
// threadPoolexecutor =
// new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
// }
//
// @Override
// public void run(final Interactor interactor) {
// if (interactor == null) {
// throw new IllegalArgumentException("Interactor to execute can't be null");
// }
//
// threadPoolexecutor.submit(interactor);
// }
//
//
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/executor/MainThreadImp.java
// public class MainThreadImp implements MainThread {
//
// private Handler handler;
//
// public MainThreadImp() {
// this.handler = new Handler(Looper.getMainLooper());
// }
//
// @Override
// public void post(Runnable runnable) {
// handler.post(runnable);
// }
// }
| import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.interactorexecutor.ThreadExecutor;
import com.tonilopezmr.sample.domain.executor.MainThreadImp;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides; | package com.tonilopezmr.sample.di.modules;
/**
*
* @author Toni
*/
@Module(
complete = false,
library = true
)
public final class ExecutorModule {
@Provides
@Singleton
public Executor provideThreadExecutor(){
return new ThreadExecutor();
}
@Provides
@Singleton
public MainThread provideMainThreadImp(){ | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/ThreadExecutor.java
// public class ThreadExecutor implements Executor{
//
// private static final int CORE_POOL_SIZE = 3;
// private static final int MAX_POOL_SIZE = 5;
// private static final int KEEP_ALIVE_TIME = 120;
// private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
// private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue();
//
// private ThreadPoolExecutor threadPoolexecutor;
//
// public ThreadExecutor() {
// int corePoolSize = CORE_POOL_SIZE;
// int maxPoolSize = MAX_POOL_SIZE;
// int keepAliveTime = KEEP_ALIVE_TIME;
// TimeUnit timeUnit = TIME_UNIT;
// BlockingQueue<Runnable> workQueue = WORK_QUEUE;
//
// threadPoolexecutor =
// new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
// }
//
// public ThreadExecutor(final int corePoolSize, final int maxPoolSize,
// final int keepAliveTime, final TimeUnit timeUnit) {
//
// BlockingQueue<Runnable> workQueue = WORK_QUEUE;
//
// threadPoolexecutor =
// new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
// }
//
// @Override
// public void run(final Interactor interactor) {
// if (interactor == null) {
// throw new IllegalArgumentException("Interactor to execute can't be null");
// }
//
// threadPoolexecutor.submit(interactor);
// }
//
//
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/executor/MainThreadImp.java
// public class MainThreadImp implements MainThread {
//
// private Handler handler;
//
// public MainThreadImp() {
// this.handler = new Handler(Looper.getMainLooper());
// }
//
// @Override
// public void post(Runnable runnable) {
// handler.post(runnable);
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/di/modules/ExecutorModule.java
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.interactorexecutor.ThreadExecutor;
import com.tonilopezmr.sample.domain.executor.MainThreadImp;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
package com.tonilopezmr.sample.di.modules;
/**
*
* @author Toni
*/
@Module(
complete = false,
library = true
)
public final class ExecutorModule {
@Provides
@Singleton
public Executor provideThreadExecutor(){
return new ThreadExecutor();
}
@Provides
@Singleton
public MainThread provideMainThreadImp(){ | return new MainThreadImp(); |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/data/SQLite/dao/SubjectDAO.java | // Path: app/src/main/java/com/tonilopezmr/sample/data/SQLite/transformer/SubjectTransformer.java
// public class SubjectTransformer implements SQLiteTransformer<SubjectEntity>{
//
// public static final String ID = "id";
// public static final String NAME = "name";
//
// public static final String TABLE_NAME = "subject";
// public static final String[] FIELDS = {ID, NAME};
//
// @Override
// public SubjectEntity transform(Cursor cursor) throws Exception {
// int id = cursor.getInt(0);
// String name = cursor.getString(1);
// return new SubjectEntity(id, name);
// }
//
// @Override
// public ContentValues transform(SubjectEntity dto) throws Exception {
// ContentValues values = new ContentValues();
// // values.put(ID, dto.getId()); it is not necessary, autoincrement!
// values.put(NAME, dto.getName());
//
// return values;
// }
//
// @Override
// public String getWhereClause(SubjectEntity dto) throws Exception {
// return ID+"="+dto.getId();
// }
//
// @Override
// public SubjectEntity setId(SubjectEntity dto, Object id) throws Exception {
// dto.setId((Integer.valueOf(id.toString())));
// return dto;
// }
//
// @Override
// public String[] getFields() throws Exception {
// return FIELDS;
// }
//
// @Override
// public String getTableName() throws Exception {
// return TABLE_NAME;
// }
// }
| import android.database.sqlite.SQLiteDatabase;
import com.tonilopezmr.easysqlite.SQLiteDelegate;
import com.tonilopezmr.sample.data.SQLite.entity.SubjectEntity;
import com.tonilopezmr.sample.data.SQLite.transformer.SubjectTransformer; | package com.tonilopezmr.sample.data.SQLite.dao;
/**
* DAO implementation, important extend for SQLiteDelegate and indicate the ObjectEntity.
* Each DAO implementation should have a Transformer.
*
* @author Toni
*/
public class SubjectDAO extends SQLiteDelegate<SubjectEntity> {
public SubjectDAO(SQLiteDatabase db) { | // Path: app/src/main/java/com/tonilopezmr/sample/data/SQLite/transformer/SubjectTransformer.java
// public class SubjectTransformer implements SQLiteTransformer<SubjectEntity>{
//
// public static final String ID = "id";
// public static final String NAME = "name";
//
// public static final String TABLE_NAME = "subject";
// public static final String[] FIELDS = {ID, NAME};
//
// @Override
// public SubjectEntity transform(Cursor cursor) throws Exception {
// int id = cursor.getInt(0);
// String name = cursor.getString(1);
// return new SubjectEntity(id, name);
// }
//
// @Override
// public ContentValues transform(SubjectEntity dto) throws Exception {
// ContentValues values = new ContentValues();
// // values.put(ID, dto.getId()); it is not necessary, autoincrement!
// values.put(NAME, dto.getName());
//
// return values;
// }
//
// @Override
// public String getWhereClause(SubjectEntity dto) throws Exception {
// return ID+"="+dto.getId();
// }
//
// @Override
// public SubjectEntity setId(SubjectEntity dto, Object id) throws Exception {
// dto.setId((Integer.valueOf(id.toString())));
// return dto;
// }
//
// @Override
// public String[] getFields() throws Exception {
// return FIELDS;
// }
//
// @Override
// public String getTableName() throws Exception {
// return TABLE_NAME;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/data/SQLite/dao/SubjectDAO.java
import android.database.sqlite.SQLiteDatabase;
import com.tonilopezmr.easysqlite.SQLiteDelegate;
import com.tonilopezmr.sample.data.SQLite.entity.SubjectEntity;
import com.tonilopezmr.sample.data.SQLite.transformer.SubjectTransformer;
package com.tonilopezmr.sample.data.SQLite.dao;
/**
* DAO implementation, important extend for SQLiteDelegate and indicate the ObjectEntity.
* Each DAO implementation should have a Transformer.
*
* @author Toni
*/
public class SubjectDAO extends SQLiteDelegate<SubjectEntity> {
public SubjectDAO(SQLiteDatabase db) { | super(db, new SubjectTransformer()); |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCaseImp.java | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
| import android.util.Log;
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
import java.util.Collection; | package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class GetSubjectListUseCaseImp implements GetSubjectListUseCase{
private SubjectRepository subjectRepository; | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCaseImp.java
import android.util.Log;
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
import java.util.Collection;
package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class GetSubjectListUseCaseImp implements GetSubjectListUseCase{
private SubjectRepository subjectRepository; | private Executor executor; |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCaseImp.java | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
| import android.util.Log;
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
import java.util.Collection; | package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class GetSubjectListUseCaseImp implements GetSubjectListUseCase{
private SubjectRepository subjectRepository;
private Executor executor; | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCaseImp.java
import android.util.Log;
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
import java.util.Collection;
package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class GetSubjectListUseCaseImp implements GetSubjectListUseCase{
private SubjectRepository subjectRepository;
private Executor executor; | private MainThread mainThread; |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCaseImp.java | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
| import android.util.Log;
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
import java.util.Collection; | package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class GetSubjectListUseCaseImp implements GetSubjectListUseCase{
private SubjectRepository subjectRepository;
private Executor executor;
private MainThread mainThread;
private Callback callback;
public GetSubjectListUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) {
this.subjectRepository = subjectRepository;
this.executor = executor;
this.mainThread = mainThread;
}
//Run interactor
@Override
public void execute(final Callback callback) {
if (callback == null) {
throw new IllegalArgumentException("Callback parameter can't be null");
}
this.callback = callback;
this.executor.run(this);
}
//Interactor User case
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
subjectRepository.getSubjectsCollection(new SubjectRepository.SubjectListCallback() {
@Override | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCaseImp.java
import android.util.Log;
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
import java.util.Collection;
package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class GetSubjectListUseCaseImp implements GetSubjectListUseCase{
private SubjectRepository subjectRepository;
private Executor executor;
private MainThread mainThread;
private Callback callback;
public GetSubjectListUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) {
this.subjectRepository = subjectRepository;
this.executor = executor;
this.mainThread = mainThread;
}
//Run interactor
@Override
public void execute(final Callback callback) {
if (callback == null) {
throw new IllegalArgumentException("Callback parameter can't be null");
}
this.callback = callback;
this.executor.run(this);
}
//Interactor User case
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
subjectRepository.getSubjectsCollection(new SubjectRepository.SubjectListCallback() {
@Override | public void onSubjectListLoader(final Collection<Subject> subjects) { |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
| import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository; | package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase {
private Callback callback; | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase {
private Callback callback; | private Subject subject; |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
| import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository; | package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase {
private Callback callback;
private Subject subject;
| // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase {
private Callback callback;
private Subject subject;
| public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
| import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository; | package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase {
private Callback callback;
private Subject subject;
| // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase {
private Callback callback;
private Subject subject;
| public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/ui/view/SubjectListView.java | // Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModel.java
// public interface SubjectViewModel {
//
// public int getId();
// public String getName();
// }
| import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel;
import java.util.Collection; | package com.tonilopezmr.sample.ui.view;
/**
* Created by toni on 07/02/15.
*/
public interface SubjectListView extends ModelListView {
public boolean isShowLayoutError();
public void hideLayoutError();
public void showLayoutError();
public void showMessage(String message);
| // Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModel.java
// public interface SubjectViewModel {
//
// public int getId();
// public String getName();
// }
// Path: app/src/main/java/com/tonilopezmr/sample/ui/view/SubjectListView.java
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel;
import java.util.Collection;
package com.tonilopezmr.sample.ui.view;
/**
* Created by toni on 07/02/15.
*/
public interface SubjectListView extends ModelListView {
public boolean isShowLayoutError();
public void hideLayoutError();
public void showLayoutError();
public void showMessage(String message);
| public void showSubjects(Collection<SubjectViewModel> subjects); |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
| import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository; | package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase {
private Callback callback; | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase {
private Callback callback; | private Subject subject; |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
| import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository; | package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase {
private Callback callback;
private Subject subject;
| // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase {
private Callback callback;
private Subject subject;
| public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
| import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository; | package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase {
private Callback callback;
private Subject subject;
| // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase {
private Callback callback;
private Subject subject;
| public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenter.java | // Path: app/src/main/java/com/tonilopezmr/sample/ui/view/SubjectListView.java
// public interface SubjectListView extends ModelListView {
//
// public boolean isShowLayoutError();
//
// public void hideLayoutError();
//
// public void showLayoutError();
//
// public void showMessage(String message);
//
// public void showSubjects(Collection<SubjectViewModel> subjects);
//
// public void showProgress();
//
// public void hideProgress();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModel.java
// public interface SubjectViewModel {
//
// public int getId();
// public String getName();
// }
| import com.tonilopezmr.sample.ui.view.SubjectListView;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel; | package com.tonilopezmr.sample.ui.presenter;
/**
* @author toni.
*/
public interface SubjectListPresenter extends Presenter{
void setView(SubjectListView view);
| // Path: app/src/main/java/com/tonilopezmr/sample/ui/view/SubjectListView.java
// public interface SubjectListView extends ModelListView {
//
// public boolean isShowLayoutError();
//
// public void hideLayoutError();
//
// public void showLayoutError();
//
// public void showMessage(String message);
//
// public void showSubjects(Collection<SubjectViewModel> subjects);
//
// public void showProgress();
//
// public void hideProgress();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModel.java
// public interface SubjectViewModel {
//
// public int getId();
// public String getName();
// }
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenter.java
import com.tonilopezmr.sample.ui.view.SubjectListView;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel;
package com.tonilopezmr.sample.ui.presenter;
/**
* @author toni.
*/
public interface SubjectListPresenter extends Presenter{
void setView(SubjectListView view);
| public void onClickItem(SubjectViewModel SubjectModel); |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java | // Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/view/SubjectListView.java
// public interface SubjectListView extends ModelListView {
//
// public boolean isShowLayoutError();
//
// public void hideLayoutError();
//
// public void showLayoutError();
//
// public void showMessage(String message);
//
// public void showSubjects(Collection<SubjectViewModel> subjects);
//
// public void showProgress();
//
// public void hideProgress();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModel.java
// public interface SubjectViewModel {
//
// public int getId();
// public String getName();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java
// public class SubjectViewModelImp implements SubjectViewModel {
//
// private int id;
// private String name;
//
// public SubjectViewModelImp(String name) {
// this.name = name;
// }
//
// public SubjectViewModelImp(Subject subject) {
// this.id = subject.getId();
// this.name = subject.getName();
// }
//
// public int getId(){
// return this.id;
// }
//
// public String getName(){
// return this.name;
// }
//
// @Override
// public boolean equals(Object o) {
// boolean result = false;
// if (o instanceof SubjectViewModel){
// SubjectViewModel model = (SubjectViewModel)o;
// if (this.id == model.getId() && this.name.equals(model.getName())){
// result = true;
// }
// }
// return result;
// }
//
// @Override
// public String toString() {
// return id+" "+name;
// }
// }
| import android.content.Context;
import android.util.Log;
import com.tonilopezmr.sample.di.BasePresenter;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.view.SubjectListView;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp;
import java.util.ArrayList;
import java.util.Collection;
import javax.inject.Named; | package com.tonilopezmr.sample.ui.presenter;
/**
* @author toni.
*/
public class SubjectListPresenterImp extends BasePresenter implements MainPresenter {
private SubjectListView view;
| // Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/view/SubjectListView.java
// public interface SubjectListView extends ModelListView {
//
// public boolean isShowLayoutError();
//
// public void hideLayoutError();
//
// public void showLayoutError();
//
// public void showMessage(String message);
//
// public void showSubjects(Collection<SubjectViewModel> subjects);
//
// public void showProgress();
//
// public void hideProgress();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModel.java
// public interface SubjectViewModel {
//
// public int getId();
// public String getName();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java
// public class SubjectViewModelImp implements SubjectViewModel {
//
// private int id;
// private String name;
//
// public SubjectViewModelImp(String name) {
// this.name = name;
// }
//
// public SubjectViewModelImp(Subject subject) {
// this.id = subject.getId();
// this.name = subject.getName();
// }
//
// public int getId(){
// return this.id;
// }
//
// public String getName(){
// return this.name;
// }
//
// @Override
// public boolean equals(Object o) {
// boolean result = false;
// if (o instanceof SubjectViewModel){
// SubjectViewModel model = (SubjectViewModel)o;
// if (this.id == model.getId() && this.name.equals(model.getName())){
// result = true;
// }
// }
// return result;
// }
//
// @Override
// public String toString() {
// return id+" "+name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
import android.content.Context;
import android.util.Log;
import com.tonilopezmr.sample.di.BasePresenter;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.view.SubjectListView;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp;
import java.util.ArrayList;
import java.util.Collection;
import javax.inject.Named;
package com.tonilopezmr.sample.ui.presenter;
/**
* @author toni.
*/
public class SubjectListPresenterImp extends BasePresenter implements MainPresenter {
private SubjectListView view;
| private GetSubjectListUseCase subjectListUseCase; |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java | // Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/view/SubjectListView.java
// public interface SubjectListView extends ModelListView {
//
// public boolean isShowLayoutError();
//
// public void hideLayoutError();
//
// public void showLayoutError();
//
// public void showMessage(String message);
//
// public void showSubjects(Collection<SubjectViewModel> subjects);
//
// public void showProgress();
//
// public void hideProgress();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModel.java
// public interface SubjectViewModel {
//
// public int getId();
// public String getName();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java
// public class SubjectViewModelImp implements SubjectViewModel {
//
// private int id;
// private String name;
//
// public SubjectViewModelImp(String name) {
// this.name = name;
// }
//
// public SubjectViewModelImp(Subject subject) {
// this.id = subject.getId();
// this.name = subject.getName();
// }
//
// public int getId(){
// return this.id;
// }
//
// public String getName(){
// return this.name;
// }
//
// @Override
// public boolean equals(Object o) {
// boolean result = false;
// if (o instanceof SubjectViewModel){
// SubjectViewModel model = (SubjectViewModel)o;
// if (this.id == model.getId() && this.name.equals(model.getName())){
// result = true;
// }
// }
// return result;
// }
//
// @Override
// public String toString() {
// return id+" "+name;
// }
// }
| import android.content.Context;
import android.util.Log;
import com.tonilopezmr.sample.di.BasePresenter;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.view.SubjectListView;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp;
import java.util.ArrayList;
import java.util.Collection;
import javax.inject.Named; | package com.tonilopezmr.sample.ui.presenter;
/**
* @author toni.
*/
public class SubjectListPresenterImp extends BasePresenter implements MainPresenter {
private SubjectListView view;
private GetSubjectListUseCase subjectListUseCase; | // Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/view/SubjectListView.java
// public interface SubjectListView extends ModelListView {
//
// public boolean isShowLayoutError();
//
// public void hideLayoutError();
//
// public void showLayoutError();
//
// public void showMessage(String message);
//
// public void showSubjects(Collection<SubjectViewModel> subjects);
//
// public void showProgress();
//
// public void hideProgress();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModel.java
// public interface SubjectViewModel {
//
// public int getId();
// public String getName();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java
// public class SubjectViewModelImp implements SubjectViewModel {
//
// private int id;
// private String name;
//
// public SubjectViewModelImp(String name) {
// this.name = name;
// }
//
// public SubjectViewModelImp(Subject subject) {
// this.id = subject.getId();
// this.name = subject.getName();
// }
//
// public int getId(){
// return this.id;
// }
//
// public String getName(){
// return this.name;
// }
//
// @Override
// public boolean equals(Object o) {
// boolean result = false;
// if (o instanceof SubjectViewModel){
// SubjectViewModel model = (SubjectViewModel)o;
// if (this.id == model.getId() && this.name.equals(model.getName())){
// result = true;
// }
// }
// return result;
// }
//
// @Override
// public String toString() {
// return id+" "+name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
import android.content.Context;
import android.util.Log;
import com.tonilopezmr.sample.di.BasePresenter;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.view.SubjectListView;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp;
import java.util.ArrayList;
import java.util.Collection;
import javax.inject.Named;
package com.tonilopezmr.sample.ui.presenter;
/**
* @author toni.
*/
public class SubjectListPresenterImp extends BasePresenter implements MainPresenter {
private SubjectListView view;
private GetSubjectListUseCase subjectListUseCase; | private SubjectUseCase createSubjectUseCase; |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java | // Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/view/SubjectListView.java
// public interface SubjectListView extends ModelListView {
//
// public boolean isShowLayoutError();
//
// public void hideLayoutError();
//
// public void showLayoutError();
//
// public void showMessage(String message);
//
// public void showSubjects(Collection<SubjectViewModel> subjects);
//
// public void showProgress();
//
// public void hideProgress();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModel.java
// public interface SubjectViewModel {
//
// public int getId();
// public String getName();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java
// public class SubjectViewModelImp implements SubjectViewModel {
//
// private int id;
// private String name;
//
// public SubjectViewModelImp(String name) {
// this.name = name;
// }
//
// public SubjectViewModelImp(Subject subject) {
// this.id = subject.getId();
// this.name = subject.getName();
// }
//
// public int getId(){
// return this.id;
// }
//
// public String getName(){
// return this.name;
// }
//
// @Override
// public boolean equals(Object o) {
// boolean result = false;
// if (o instanceof SubjectViewModel){
// SubjectViewModel model = (SubjectViewModel)o;
// if (this.id == model.getId() && this.name.equals(model.getName())){
// result = true;
// }
// }
// return result;
// }
//
// @Override
// public String toString() {
// return id+" "+name;
// }
// }
| import android.content.Context;
import android.util.Log;
import com.tonilopezmr.sample.di.BasePresenter;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.view.SubjectListView;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp;
import java.util.ArrayList;
import java.util.Collection;
import javax.inject.Named; | package com.tonilopezmr.sample.ui.presenter;
/**
* @author toni.
*/
public class SubjectListPresenterImp extends BasePresenter implements MainPresenter {
private SubjectListView view;
private GetSubjectListUseCase subjectListUseCase;
private SubjectUseCase createSubjectUseCase;
private SubjectUseCase deleteSubjectUseCase;
public SubjectListPresenterImp(Context context, GetSubjectListUseCase subjectListUseCase,
@Named("create usecase") SubjectUseCase createSubjectUseCase,
@Named("delete usecase") SubjectUseCase deleteSubjectUseCase) {
super(context);
this.createSubjectUseCase = createSubjectUseCase;
this.deleteSubjectUseCase = deleteSubjectUseCase;
this.subjectListUseCase = subjectListUseCase;
}
@Override
public void setView(SubjectListView view){
this.view = view;
}
@Override
public void onInit() {
view.showProgress();
showSubjects();
}
private void showSubjects(){
subjectListUseCase.execute(new GetSubjectListUseCase.Callback() {
@Override | // Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/view/SubjectListView.java
// public interface SubjectListView extends ModelListView {
//
// public boolean isShowLayoutError();
//
// public void hideLayoutError();
//
// public void showLayoutError();
//
// public void showMessage(String message);
//
// public void showSubjects(Collection<SubjectViewModel> subjects);
//
// public void showProgress();
//
// public void hideProgress();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModel.java
// public interface SubjectViewModel {
//
// public int getId();
// public String getName();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java
// public class SubjectViewModelImp implements SubjectViewModel {
//
// private int id;
// private String name;
//
// public SubjectViewModelImp(String name) {
// this.name = name;
// }
//
// public SubjectViewModelImp(Subject subject) {
// this.id = subject.getId();
// this.name = subject.getName();
// }
//
// public int getId(){
// return this.id;
// }
//
// public String getName(){
// return this.name;
// }
//
// @Override
// public boolean equals(Object o) {
// boolean result = false;
// if (o instanceof SubjectViewModel){
// SubjectViewModel model = (SubjectViewModel)o;
// if (this.id == model.getId() && this.name.equals(model.getName())){
// result = true;
// }
// }
// return result;
// }
//
// @Override
// public String toString() {
// return id+" "+name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
import android.content.Context;
import android.util.Log;
import com.tonilopezmr.sample.di.BasePresenter;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.view.SubjectListView;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp;
import java.util.ArrayList;
import java.util.Collection;
import javax.inject.Named;
package com.tonilopezmr.sample.ui.presenter;
/**
* @author toni.
*/
public class SubjectListPresenterImp extends BasePresenter implements MainPresenter {
private SubjectListView view;
private GetSubjectListUseCase subjectListUseCase;
private SubjectUseCase createSubjectUseCase;
private SubjectUseCase deleteSubjectUseCase;
public SubjectListPresenterImp(Context context, GetSubjectListUseCase subjectListUseCase,
@Named("create usecase") SubjectUseCase createSubjectUseCase,
@Named("delete usecase") SubjectUseCase deleteSubjectUseCase) {
super(context);
this.createSubjectUseCase = createSubjectUseCase;
this.deleteSubjectUseCase = deleteSubjectUseCase;
this.subjectListUseCase = subjectListUseCase;
}
@Override
public void setView(SubjectListView view){
this.view = view;
}
@Override
public void onInit() {
view.showProgress();
showSubjects();
}
private void showSubjects(){
subjectListUseCase.execute(new GetSubjectListUseCase.Callback() {
@Override | public void onSubjectListLoaded(Collection<Subject> subjects) { |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java | // Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/view/SubjectListView.java
// public interface SubjectListView extends ModelListView {
//
// public boolean isShowLayoutError();
//
// public void hideLayoutError();
//
// public void showLayoutError();
//
// public void showMessage(String message);
//
// public void showSubjects(Collection<SubjectViewModel> subjects);
//
// public void showProgress();
//
// public void hideProgress();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModel.java
// public interface SubjectViewModel {
//
// public int getId();
// public String getName();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java
// public class SubjectViewModelImp implements SubjectViewModel {
//
// private int id;
// private String name;
//
// public SubjectViewModelImp(String name) {
// this.name = name;
// }
//
// public SubjectViewModelImp(Subject subject) {
// this.id = subject.getId();
// this.name = subject.getName();
// }
//
// public int getId(){
// return this.id;
// }
//
// public String getName(){
// return this.name;
// }
//
// @Override
// public boolean equals(Object o) {
// boolean result = false;
// if (o instanceof SubjectViewModel){
// SubjectViewModel model = (SubjectViewModel)o;
// if (this.id == model.getId() && this.name.equals(model.getName())){
// result = true;
// }
// }
// return result;
// }
//
// @Override
// public String toString() {
// return id+" "+name;
// }
// }
| import android.content.Context;
import android.util.Log;
import com.tonilopezmr.sample.di.BasePresenter;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.view.SubjectListView;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp;
import java.util.ArrayList;
import java.util.Collection;
import javax.inject.Named; |
@Override
public void setView(SubjectListView view){
this.view = view;
}
@Override
public void onInit() {
view.showProgress();
showSubjects();
}
private void showSubjects(){
subjectListUseCase.execute(new GetSubjectListUseCase.Callback() {
@Override
public void onSubjectListLoaded(Collection<Subject> subjects) {
view.showSubjects(convertToViewModel(subjects));
view.hideProgress();
}
@Override
public void onError(SubjectException exception) {
view.showMessage(exception.getMessage()); //For example
view.hideProgress();
view.showLayoutError();
Log.i(getClass().toString(), "¡¡Show error!!");
}
});
}
| // Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/view/SubjectListView.java
// public interface SubjectListView extends ModelListView {
//
// public boolean isShowLayoutError();
//
// public void hideLayoutError();
//
// public void showLayoutError();
//
// public void showMessage(String message);
//
// public void showSubjects(Collection<SubjectViewModel> subjects);
//
// public void showProgress();
//
// public void hideProgress();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModel.java
// public interface SubjectViewModel {
//
// public int getId();
// public String getName();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java
// public class SubjectViewModelImp implements SubjectViewModel {
//
// private int id;
// private String name;
//
// public SubjectViewModelImp(String name) {
// this.name = name;
// }
//
// public SubjectViewModelImp(Subject subject) {
// this.id = subject.getId();
// this.name = subject.getName();
// }
//
// public int getId(){
// return this.id;
// }
//
// public String getName(){
// return this.name;
// }
//
// @Override
// public boolean equals(Object o) {
// boolean result = false;
// if (o instanceof SubjectViewModel){
// SubjectViewModel model = (SubjectViewModel)o;
// if (this.id == model.getId() && this.name.equals(model.getName())){
// result = true;
// }
// }
// return result;
// }
//
// @Override
// public String toString() {
// return id+" "+name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
import android.content.Context;
import android.util.Log;
import com.tonilopezmr.sample.di.BasePresenter;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.view.SubjectListView;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp;
import java.util.ArrayList;
import java.util.Collection;
import javax.inject.Named;
@Override
public void setView(SubjectListView view){
this.view = view;
}
@Override
public void onInit() {
view.showProgress();
showSubjects();
}
private void showSubjects(){
subjectListUseCase.execute(new GetSubjectListUseCase.Callback() {
@Override
public void onSubjectListLoaded(Collection<Subject> subjects) {
view.showSubjects(convertToViewModel(subjects));
view.hideProgress();
}
@Override
public void onError(SubjectException exception) {
view.showMessage(exception.getMessage()); //For example
view.hideProgress();
view.showLayoutError();
Log.i(getClass().toString(), "¡¡Show error!!");
}
});
}
| private Collection<SubjectViewModel> convertToViewModel(Collection<Subject> subjectsCollection){ |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java | // Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/view/SubjectListView.java
// public interface SubjectListView extends ModelListView {
//
// public boolean isShowLayoutError();
//
// public void hideLayoutError();
//
// public void showLayoutError();
//
// public void showMessage(String message);
//
// public void showSubjects(Collection<SubjectViewModel> subjects);
//
// public void showProgress();
//
// public void hideProgress();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModel.java
// public interface SubjectViewModel {
//
// public int getId();
// public String getName();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java
// public class SubjectViewModelImp implements SubjectViewModel {
//
// private int id;
// private String name;
//
// public SubjectViewModelImp(String name) {
// this.name = name;
// }
//
// public SubjectViewModelImp(Subject subject) {
// this.id = subject.getId();
// this.name = subject.getName();
// }
//
// public int getId(){
// return this.id;
// }
//
// public String getName(){
// return this.name;
// }
//
// @Override
// public boolean equals(Object o) {
// boolean result = false;
// if (o instanceof SubjectViewModel){
// SubjectViewModel model = (SubjectViewModel)o;
// if (this.id == model.getId() && this.name.equals(model.getName())){
// result = true;
// }
// }
// return result;
// }
//
// @Override
// public String toString() {
// return id+" "+name;
// }
// }
| import android.content.Context;
import android.util.Log;
import com.tonilopezmr.sample.di.BasePresenter;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.view.SubjectListView;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp;
import java.util.ArrayList;
import java.util.Collection;
import javax.inject.Named; | }
@Override
public void onInit() {
view.showProgress();
showSubjects();
}
private void showSubjects(){
subjectListUseCase.execute(new GetSubjectListUseCase.Callback() {
@Override
public void onSubjectListLoaded(Collection<Subject> subjects) {
view.showSubjects(convertToViewModel(subjects));
view.hideProgress();
}
@Override
public void onError(SubjectException exception) {
view.showMessage(exception.getMessage()); //For example
view.hideProgress();
view.showLayoutError();
Log.i(getClass().toString(), "¡¡Show error!!");
}
});
}
private Collection<SubjectViewModel> convertToViewModel(Collection<Subject> subjectsCollection){
Collection<SubjectViewModel> subjectsViewModel = new ArrayList<>();
for (Subject subject : subjectsCollection){ | // Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// public interface GetSubjectListUseCase extends Interactor {
//
// interface Callback{
// void onSubjectListLoaded(Collection<Subject> subjects);
// void onError(SubjectException exception);
// }
//
// public void execute(final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// public interface SubjectUseCase extends Interactor {
//
// interface Callback {
// void onMissionAccomplished(Subject subject);
// void onError(SubjectException ex);
// }
//
// public void execute(Subject subject, final Callback callback);
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/view/SubjectListView.java
// public interface SubjectListView extends ModelListView {
//
// public boolean isShowLayoutError();
//
// public void hideLayoutError();
//
// public void showLayoutError();
//
// public void showMessage(String message);
//
// public void showSubjects(Collection<SubjectViewModel> subjects);
//
// public void showProgress();
//
// public void hideProgress();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModel.java
// public interface SubjectViewModel {
//
// public int getId();
// public String getName();
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java
// public class SubjectViewModelImp implements SubjectViewModel {
//
// private int id;
// private String name;
//
// public SubjectViewModelImp(String name) {
// this.name = name;
// }
//
// public SubjectViewModelImp(Subject subject) {
// this.id = subject.getId();
// this.name = subject.getName();
// }
//
// public int getId(){
// return this.id;
// }
//
// public String getName(){
// return this.name;
// }
//
// @Override
// public boolean equals(Object o) {
// boolean result = false;
// if (o instanceof SubjectViewModel){
// SubjectViewModel model = (SubjectViewModel)o;
// if (this.id == model.getId() && this.name.equals(model.getName())){
// result = true;
// }
// }
// return result;
// }
//
// @Override
// public String toString() {
// return id+" "+name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
import android.content.Context;
import android.util.Log;
import com.tonilopezmr.sample.di.BasePresenter;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase;
import com.tonilopezmr.sample.domain.interactor.SubjectUseCase;
import com.tonilopezmr.sample.ui.view.SubjectListView;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel;
import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp;
import java.util.ArrayList;
import java.util.Collection;
import javax.inject.Named;
}
@Override
public void onInit() {
view.showProgress();
showSubjects();
}
private void showSubjects(){
subjectListUseCase.execute(new GetSubjectListUseCase.Callback() {
@Override
public void onSubjectListLoaded(Collection<Subject> subjects) {
view.showSubjects(convertToViewModel(subjects));
view.hideProgress();
}
@Override
public void onError(SubjectException exception) {
view.showMessage(exception.getMessage()); //For example
view.hideProgress();
view.showLayoutError();
Log.i(getClass().toString(), "¡¡Show error!!");
}
});
}
private Collection<SubjectViewModel> convertToViewModel(Collection<Subject> subjectsCollection){
Collection<SubjectViewModel> subjectsViewModel = new ArrayList<>();
for (Subject subject : subjectsCollection){ | subjectsViewModel.add(new SubjectViewModelImp(subject)); |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/data/SQLite/entity/mapper/SubjectEntityMapper.java | // Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/mapper/SubjectMapper.java
// public interface SubjectMapper<T> {
//
// public Subject mapToSubject(T subjectEntity);
//
// public T mapToSubjectEntity(Subject subject);
// }
| import com.tonilopezmr.sample.data.SQLite.entity.SubjectEntity;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.mapper.SubjectMapper; | package com.tonilopezmr.sample.data.SQLite.entity.mapper;
/**
*
* @author Toni
*/
public class SubjectEntityMapper implements SubjectMapper<SubjectEntity>{
public SubjectEntityMapper() {
}
| // Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/mapper/SubjectMapper.java
// public interface SubjectMapper<T> {
//
// public Subject mapToSubject(T subjectEntity);
//
// public T mapToSubjectEntity(Subject subject);
// }
// Path: app/src/main/java/com/tonilopezmr/sample/data/SQLite/entity/mapper/SubjectEntityMapper.java
import com.tonilopezmr.sample.data.SQLite.entity.SubjectEntity;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.mapper.SubjectMapper;
package com.tonilopezmr.sample.data.SQLite.entity.mapper;
/**
*
* @author Toni
*/
public class SubjectEntityMapper implements SubjectMapper<SubjectEntity>{
public SubjectEntityMapper() {
}
| public Subject mapToSubject(SubjectEntity subjectEntity){ |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/domain/interactor/AbstractSubjectUseCase.java | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
| import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.repository.SubjectRepository; | package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public abstract class AbstractSubjectUseCase implements SubjectUseCase {
private Executor executor; | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Executor.java
// public interface Executor {
// void run(final Interactor interactor);
// }
//
// Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/MainThread.java
// public interface MainThread {
// void post(final Runnable runnable);
// }
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/AbstractSubjectUseCase.java
import com.tonilopezmr.interactorexecutor.Executor;
import com.tonilopezmr.interactorexecutor.MainThread;
import com.tonilopezmr.sample.domain.repository.SubjectRepository;
package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public abstract class AbstractSubjectUseCase implements SubjectUseCase {
private Executor executor; | private MainThread mainThread; |
tonilopezmr/InteractorExecutor | app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Interactor.java
// public interface Interactor extends Runnable{
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
| import com.tonilopezmr.interactorexecutor.Interactor;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import java.util.Collection; | package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public interface GetSubjectListUseCase extends Interactor {
interface Callback{ | // Path: interactorexecutor/src/main/java/com/tonilopezmr/interactorexecutor/Interactor.java
// public interface Interactor extends Runnable{
// }
//
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java
// public class Subject {
//
// private int id;
// private String name;
//
// public Subject(String name) {
// this.name = name;
// }
//
// public Subject(int id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "ID: "+this.id+" Subject: "+this.name;
// }
// }
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
import com.tonilopezmr.interactorexecutor.Interactor;
import com.tonilopezmr.sample.domain.Subject;
import com.tonilopezmr.sample.domain.exception.SubjectException;
import java.util.Collection;
package com.tonilopezmr.sample.domain.interactor;
/**
* @author toni.
*/
public interface GetSubjectListUseCase extends Interactor {
interface Callback{ | void onSubjectListLoaded(Collection<Subject> subjects); |
idugalic/micro-company | monolithic/src/test/java/com/idugalic/ApplicationIntegrationTest.java | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/web/CreateBlogPostRequest.java
// public class CreateBlogPostRequest {
//
// private String title;
// private String rawContent;
// private String publicSlug;
// private Boolean draft;
// private Boolean broadcast;
// private Date publishAt;
// private BlogPostCategory category;
//
// public CreateBlogPostRequest() {
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public void setRawContent(String rawContent) {
// this.rawContent = rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public void setPublicSlug(String publicSlug) {
// this.publicSlug = publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public void setDraft(Boolean draft) {
// this.draft = draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public void setBroadcast(Boolean broadcast) {
// this.broadcast = broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public void setPublishAt(Date publishAt) {
// this.publishAt = publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public void setCategory(BlogPostCategory category) {
// this.category = category;
// }
//
// }
| import com.idugalic.commandside.blog.web.CreateBlogPostRequest;
import com.idugalic.commandside.project.web.CreateProjectRequest;
import com.idugalic.common.blog.model.BlogPostCategory;
import java.util.Calendar;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat; | package com.idugalic;
/**
* Integration test for {@link Application} starting on a random port.
*
* @author idugalic
*
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ApplicationIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
| // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/web/CreateBlogPostRequest.java
// public class CreateBlogPostRequest {
//
// private String title;
// private String rawContent;
// private String publicSlug;
// private Boolean draft;
// private Boolean broadcast;
// private Date publishAt;
// private BlogPostCategory category;
//
// public CreateBlogPostRequest() {
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public void setRawContent(String rawContent) {
// this.rawContent = rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public void setPublicSlug(String publicSlug) {
// this.publicSlug = publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public void setDraft(Boolean draft) {
// this.draft = draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public void setBroadcast(Boolean broadcast) {
// this.broadcast = broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public void setPublishAt(Date publishAt) {
// this.publishAt = publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public void setCategory(BlogPostCategory category) {
// this.category = category;
// }
//
// }
// Path: monolithic/src/test/java/com/idugalic/ApplicationIntegrationTest.java
import com.idugalic.commandside.blog.web.CreateBlogPostRequest;
import com.idugalic.commandside.project.web.CreateProjectRequest;
import com.idugalic.common.blog.model.BlogPostCategory;
import java.util.Calendar;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
package com.idugalic;
/**
* Integration test for {@link Application} starting on a random port.
*
* @author idugalic
*
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ApplicationIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
| private CreateBlogPostRequest createBlogPostRequest; |
idugalic/micro-company | monolithic/src/test/java/com/idugalic/commandside/project/aggregate/BlogPostAggregateTest.java | // Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/CreateProjectCommand.java
// public class CreateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String category;
// private String description;
//
// public CreateProjectCommand(AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String category, String description) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.category = category;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getCategory() {
// return category;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
//
// Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/UpdateProjectCommand.java
// public class UpdateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String description;
//
// public UpdateProjectCommand(String id, AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String description) {
// super(auditEntry);
// this.id = id;
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
| import com.idugalic.commandside.project.command.CreateProjectCommand;
import com.idugalic.commandside.project.command.UpdateProjectCommand;
import com.idugalic.common.model.AuditEntry;
import com.idugalic.common.project.event.ProjectCreatedEvent;
import com.idugalic.common.project.event.ProjectUpdatedEvent;
import org.axonframework.messaging.interceptors.BeanValidationInterceptor;
import org.axonframework.messaging.interceptors.JSR303ViolationException;
import org.axonframework.test.aggregate.AggregateTestFixture;
import org.axonframework.test.aggregate.FixtureConfiguration;
import org.junit.Before;
import org.junit.Test; | package com.idugalic.commandside.project.aggregate;
/**
* Domain (aggregate) test for {@link ProjectAggregate}.
*
* @author idugalic
*
*/
public class BlogPostAggregateTest {
private FixtureConfiguration<ProjectAggregate> fixture;
private AuditEntry auditEntry;
private static final String WHO = "idugalic";
@Before
public void setUp() throws Exception {
fixture = new AggregateTestFixture<ProjectAggregate>(ProjectAggregate.class);
fixture.registerCommandDispatchInterceptor(new BeanValidationInterceptor());
auditEntry = new AuditEntry(WHO);
}
@Test
public void createBlogPostTest() throws Exception { | // Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/CreateProjectCommand.java
// public class CreateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String category;
// private String description;
//
// public CreateProjectCommand(AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String category, String description) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.category = category;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getCategory() {
// return category;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
//
// Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/UpdateProjectCommand.java
// public class UpdateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String description;
//
// public UpdateProjectCommand(String id, AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String description) {
// super(auditEntry);
// this.id = id;
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
// Path: monolithic/src/test/java/com/idugalic/commandside/project/aggregate/BlogPostAggregateTest.java
import com.idugalic.commandside.project.command.CreateProjectCommand;
import com.idugalic.commandside.project.command.UpdateProjectCommand;
import com.idugalic.common.model.AuditEntry;
import com.idugalic.common.project.event.ProjectCreatedEvent;
import com.idugalic.common.project.event.ProjectUpdatedEvent;
import org.axonframework.messaging.interceptors.BeanValidationInterceptor;
import org.axonframework.messaging.interceptors.JSR303ViolationException;
import org.axonframework.test.aggregate.AggregateTestFixture;
import org.axonframework.test.aggregate.FixtureConfiguration;
import org.junit.Before;
import org.junit.Test;
package com.idugalic.commandside.project.aggregate;
/**
* Domain (aggregate) test for {@link ProjectAggregate}.
*
* @author idugalic
*
*/
public class BlogPostAggregateTest {
private FixtureConfiguration<ProjectAggregate> fixture;
private AuditEntry auditEntry;
private static final String WHO = "idugalic";
@Before
public void setUp() throws Exception {
fixture = new AggregateTestFixture<ProjectAggregate>(ProjectAggregate.class);
fixture.registerCommandDispatchInterceptor(new BeanValidationInterceptor());
auditEntry = new AuditEntry(WHO);
}
@Test
public void createBlogPostTest() throws Exception { | CreateProjectCommand command = new CreateProjectCommand(auditEntry, "name", "repoURL", "siteURL", "category", "description"); |
idugalic/micro-company | monolithic/src/test/java/com/idugalic/commandside/project/aggregate/BlogPostAggregateTest.java | // Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/CreateProjectCommand.java
// public class CreateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String category;
// private String description;
//
// public CreateProjectCommand(AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String category, String description) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.category = category;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getCategory() {
// return category;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
//
// Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/UpdateProjectCommand.java
// public class UpdateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String description;
//
// public UpdateProjectCommand(String id, AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String description) {
// super(auditEntry);
// this.id = id;
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
| import com.idugalic.commandside.project.command.CreateProjectCommand;
import com.idugalic.commandside.project.command.UpdateProjectCommand;
import com.idugalic.common.model.AuditEntry;
import com.idugalic.common.project.event.ProjectCreatedEvent;
import com.idugalic.common.project.event.ProjectUpdatedEvent;
import org.axonframework.messaging.interceptors.BeanValidationInterceptor;
import org.axonframework.messaging.interceptors.JSR303ViolationException;
import org.axonframework.test.aggregate.AggregateTestFixture;
import org.axonframework.test.aggregate.FixtureConfiguration;
import org.junit.Before;
import org.junit.Test; | package com.idugalic.commandside.project.aggregate;
/**
* Domain (aggregate) test for {@link ProjectAggregate}.
*
* @author idugalic
*
*/
public class BlogPostAggregateTest {
private FixtureConfiguration<ProjectAggregate> fixture;
private AuditEntry auditEntry;
private static final String WHO = "idugalic";
@Before
public void setUp() throws Exception {
fixture = new AggregateTestFixture<ProjectAggregate>(ProjectAggregate.class);
fixture.registerCommandDispatchInterceptor(new BeanValidationInterceptor());
auditEntry = new AuditEntry(WHO);
}
@Test
public void createBlogPostTest() throws Exception {
CreateProjectCommand command = new CreateProjectCommand(auditEntry, "name", "repoURL", "siteURL", "category", "description");
fixture.given().when(command).expectEvents(new ProjectCreatedEvent(command.getId(), auditEntry, "name", "repoURL", "siteURL", "category", "description"));
}
@Test(expected = JSR303ViolationException.class)
public void createBlogPostWithWrongNameTest() throws Exception {
CreateProjectCommand command = new CreateProjectCommand(auditEntry, null, "repoURL", "siteURL", "category", "description");
fixture.given().when(command).expectEvents(new ProjectCreatedEvent(command.getId(), auditEntry, "name", "repoURL", "siteURL", "category", "description"));
}
@Test
public void updateBlogPostTest() throws Exception { | // Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/CreateProjectCommand.java
// public class CreateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String category;
// private String description;
//
// public CreateProjectCommand(AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String category, String description) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.category = category;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getCategory() {
// return category;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
//
// Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/UpdateProjectCommand.java
// public class UpdateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String description;
//
// public UpdateProjectCommand(String id, AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String description) {
// super(auditEntry);
// this.id = id;
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
// Path: monolithic/src/test/java/com/idugalic/commandside/project/aggregate/BlogPostAggregateTest.java
import com.idugalic.commandside.project.command.CreateProjectCommand;
import com.idugalic.commandside.project.command.UpdateProjectCommand;
import com.idugalic.common.model.AuditEntry;
import com.idugalic.common.project.event.ProjectCreatedEvent;
import com.idugalic.common.project.event.ProjectUpdatedEvent;
import org.axonframework.messaging.interceptors.BeanValidationInterceptor;
import org.axonframework.messaging.interceptors.JSR303ViolationException;
import org.axonframework.test.aggregate.AggregateTestFixture;
import org.axonframework.test.aggregate.FixtureConfiguration;
import org.junit.Before;
import org.junit.Test;
package com.idugalic.commandside.project.aggregate;
/**
* Domain (aggregate) test for {@link ProjectAggregate}.
*
* @author idugalic
*
*/
public class BlogPostAggregateTest {
private FixtureConfiguration<ProjectAggregate> fixture;
private AuditEntry auditEntry;
private static final String WHO = "idugalic";
@Before
public void setUp() throws Exception {
fixture = new AggregateTestFixture<ProjectAggregate>(ProjectAggregate.class);
fixture.registerCommandDispatchInterceptor(new BeanValidationInterceptor());
auditEntry = new AuditEntry(WHO);
}
@Test
public void createBlogPostTest() throws Exception {
CreateProjectCommand command = new CreateProjectCommand(auditEntry, "name", "repoURL", "siteURL", "category", "description");
fixture.given().when(command).expectEvents(new ProjectCreatedEvent(command.getId(), auditEntry, "name", "repoURL", "siteURL", "category", "description"));
}
@Test(expected = JSR303ViolationException.class)
public void createBlogPostWithWrongNameTest() throws Exception {
CreateProjectCommand command = new CreateProjectCommand(auditEntry, null, "repoURL", "siteURL", "category", "description");
fixture.given().when(command).expectEvents(new ProjectCreatedEvent(command.getId(), auditEntry, "name", "repoURL", "siteURL", "category", "description"));
}
@Test
public void updateBlogPostTest() throws Exception { | UpdateProjectCommand command = new UpdateProjectCommand("id", auditEntry, "name2", "repoURL2", "siteURL2", "description2"); |
idugalic/micro-company | command-side-blog/src/main/java/com/idugalic/commandside/blog/aggregate/BlogPostAggregate.java | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/aggregate/exception/PublishBlogPostException.java
// public class PublishBlogPostException extends IllegalStateException {
//
// private static final long serialVersionUID = 2680537715575935263L;
//
// public PublishBlogPostException() {
// }
//
// public PublishBlogPostException(String s) {
// super(s);
// }
//
// public PublishBlogPostException(Throwable cause) {
// super(cause);
// }
//
// public PublishBlogPostException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/CreateBlogPostCommand.java
// public class CreateBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Title is mandatory")
// @NotBlank(message = "Title is mandatory")
// private String title;
// @NotNull(message = "rawContent is mandatory")
// @NotBlank(message = "rawContent is mandatory")
// private String rawContent;
// @NotNull(message = "PublicSlug is mandatory")
// @NotBlank(message = "PublicSlug is mandatory")
// private String publicSlug;
// @NotNull
// private Boolean draft;
// @NotNull
// private Boolean broadcast;
// @Future(message = "Publish at date must be the future")
// @NotNull
// private Date publishAt;
// @NotNull
// private BlogPostCategory category;
// private String authorId;
//
// public CreateBlogPostCommand(AuditEntry auditEntry, String title, String rawContent, String publicSlug,
// Boolean draft, Boolean broadcast, Date publishAt, BlogPostCategory category, String authorId) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.title = title;
// this.rawContent = rawContent;
// this.publicSlug = publicSlug;
// this.draft = draft;
// this.broadcast = broadcast;
// this.publishAt = publishAt;
// this.category = category;
// this.authorId = authorId;
// }
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public String getAuthorId() {
// return authorId;
// }
//
// }
//
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/PublishBlogPostCommand.java
// public class PublishBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// private Date publishAt;
//
// public PublishBlogPostCommand(String id, AuditEntry auditEntry, Date publishAt) {
// this.id = id;
// this.publishAt = publishAt;
// this.setAuditEntry(auditEntry);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
// }
| import com.idugalic.commandside.blog.aggregate.exception.PublishBlogPostException;
import com.idugalic.commandside.blog.command.CreateBlogPostCommand;
import com.idugalic.commandside.blog.command.PublishBlogPostCommand;
import com.idugalic.common.blog.event.BlogPostCreatedEvent;
import com.idugalic.common.blog.event.BlogPostPublishedEvent;
import com.idugalic.common.blog.model.BlogPostCategory;
import java.util.Date;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.model.AggregateIdentifier;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.spring.stereotype.Aggregate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.axonframework.commandhandling.model.AggregateLifecycle.apply; | package com.idugalic.commandside.blog.aggregate;
/**
* A BlogPost aggregate root.
*
* @author idugalic
*
*/
@Aggregate
public class BlogPostAggregate{
private static final Logger LOG = LoggerFactory.getLogger(BlogPostAggregate.class);
/**
* Aggregates that are managed by Axon must have a unique identifier. Strategies
* similar to GUID are often used. The annotation 'AggregateIdentifier' identifies the
* id field as such.
*/
@AggregateIdentifier
private String id;
private String title;
private String rawContent;
private String publicSlug;
private Boolean draft;
private Boolean broadcast;
private Date publishAt;
private BlogPostCategory category;
private String authorId;
/**
* This default constructor is used by the Repository to construct a prototype
* BlogPostAggregate. Events are then used to set properties such as the
* BlogPostAggregate's Id in order to make the Aggregate reflect it's true logical
* state.
*/
public BlogPostAggregate() {
}
/**
* This constructor is marked as a 'CommandHandler' for the AddProductCommand. This
* command can be used to construct new instances of the Aggregate. If successful a
* new BlogPostAggregate is 'applied' to the aggregate using the Axon 'apply' method.
* The apply method appears to also propagate the Event to any other registered 'Event
* Listeners', who may take further action.
*
* @param command
*/
@CommandHandler | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/aggregate/exception/PublishBlogPostException.java
// public class PublishBlogPostException extends IllegalStateException {
//
// private static final long serialVersionUID = 2680537715575935263L;
//
// public PublishBlogPostException() {
// }
//
// public PublishBlogPostException(String s) {
// super(s);
// }
//
// public PublishBlogPostException(Throwable cause) {
// super(cause);
// }
//
// public PublishBlogPostException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/CreateBlogPostCommand.java
// public class CreateBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Title is mandatory")
// @NotBlank(message = "Title is mandatory")
// private String title;
// @NotNull(message = "rawContent is mandatory")
// @NotBlank(message = "rawContent is mandatory")
// private String rawContent;
// @NotNull(message = "PublicSlug is mandatory")
// @NotBlank(message = "PublicSlug is mandatory")
// private String publicSlug;
// @NotNull
// private Boolean draft;
// @NotNull
// private Boolean broadcast;
// @Future(message = "Publish at date must be the future")
// @NotNull
// private Date publishAt;
// @NotNull
// private BlogPostCategory category;
// private String authorId;
//
// public CreateBlogPostCommand(AuditEntry auditEntry, String title, String rawContent, String publicSlug,
// Boolean draft, Boolean broadcast, Date publishAt, BlogPostCategory category, String authorId) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.title = title;
// this.rawContent = rawContent;
// this.publicSlug = publicSlug;
// this.draft = draft;
// this.broadcast = broadcast;
// this.publishAt = publishAt;
// this.category = category;
// this.authorId = authorId;
// }
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public String getAuthorId() {
// return authorId;
// }
//
// }
//
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/PublishBlogPostCommand.java
// public class PublishBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// private Date publishAt;
//
// public PublishBlogPostCommand(String id, AuditEntry auditEntry, Date publishAt) {
// this.id = id;
// this.publishAt = publishAt;
// this.setAuditEntry(auditEntry);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
// }
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/aggregate/BlogPostAggregate.java
import com.idugalic.commandside.blog.aggregate.exception.PublishBlogPostException;
import com.idugalic.commandside.blog.command.CreateBlogPostCommand;
import com.idugalic.commandside.blog.command.PublishBlogPostCommand;
import com.idugalic.common.blog.event.BlogPostCreatedEvent;
import com.idugalic.common.blog.event.BlogPostPublishedEvent;
import com.idugalic.common.blog.model.BlogPostCategory;
import java.util.Date;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.model.AggregateIdentifier;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.spring.stereotype.Aggregate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.axonframework.commandhandling.model.AggregateLifecycle.apply;
package com.idugalic.commandside.blog.aggregate;
/**
* A BlogPost aggregate root.
*
* @author idugalic
*
*/
@Aggregate
public class BlogPostAggregate{
private static final Logger LOG = LoggerFactory.getLogger(BlogPostAggregate.class);
/**
* Aggregates that are managed by Axon must have a unique identifier. Strategies
* similar to GUID are often used. The annotation 'AggregateIdentifier' identifies the
* id field as such.
*/
@AggregateIdentifier
private String id;
private String title;
private String rawContent;
private String publicSlug;
private Boolean draft;
private Boolean broadcast;
private Date publishAt;
private BlogPostCategory category;
private String authorId;
/**
* This default constructor is used by the Repository to construct a prototype
* BlogPostAggregate. Events are then used to set properties such as the
* BlogPostAggregate's Id in order to make the Aggregate reflect it's true logical
* state.
*/
public BlogPostAggregate() {
}
/**
* This constructor is marked as a 'CommandHandler' for the AddProductCommand. This
* command can be used to construct new instances of the Aggregate. If successful a
* new BlogPostAggregate is 'applied' to the aggregate using the Axon 'apply' method.
* The apply method appears to also propagate the Event to any other registered 'Event
* Listeners', who may take further action.
*
* @param command
*/
@CommandHandler | public BlogPostAggregate(CreateBlogPostCommand command) { |
idugalic/micro-company | command-side-blog/src/main/java/com/idugalic/commandside/blog/aggregate/BlogPostAggregate.java | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/aggregate/exception/PublishBlogPostException.java
// public class PublishBlogPostException extends IllegalStateException {
//
// private static final long serialVersionUID = 2680537715575935263L;
//
// public PublishBlogPostException() {
// }
//
// public PublishBlogPostException(String s) {
// super(s);
// }
//
// public PublishBlogPostException(Throwable cause) {
// super(cause);
// }
//
// public PublishBlogPostException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/CreateBlogPostCommand.java
// public class CreateBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Title is mandatory")
// @NotBlank(message = "Title is mandatory")
// private String title;
// @NotNull(message = "rawContent is mandatory")
// @NotBlank(message = "rawContent is mandatory")
// private String rawContent;
// @NotNull(message = "PublicSlug is mandatory")
// @NotBlank(message = "PublicSlug is mandatory")
// private String publicSlug;
// @NotNull
// private Boolean draft;
// @NotNull
// private Boolean broadcast;
// @Future(message = "Publish at date must be the future")
// @NotNull
// private Date publishAt;
// @NotNull
// private BlogPostCategory category;
// private String authorId;
//
// public CreateBlogPostCommand(AuditEntry auditEntry, String title, String rawContent, String publicSlug,
// Boolean draft, Boolean broadcast, Date publishAt, BlogPostCategory category, String authorId) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.title = title;
// this.rawContent = rawContent;
// this.publicSlug = publicSlug;
// this.draft = draft;
// this.broadcast = broadcast;
// this.publishAt = publishAt;
// this.category = category;
// this.authorId = authorId;
// }
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public String getAuthorId() {
// return authorId;
// }
//
// }
//
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/PublishBlogPostCommand.java
// public class PublishBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// private Date publishAt;
//
// public PublishBlogPostCommand(String id, AuditEntry auditEntry, Date publishAt) {
// this.id = id;
// this.publishAt = publishAt;
// this.setAuditEntry(auditEntry);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
// }
| import com.idugalic.commandside.blog.aggregate.exception.PublishBlogPostException;
import com.idugalic.commandside.blog.command.CreateBlogPostCommand;
import com.idugalic.commandside.blog.command.PublishBlogPostCommand;
import com.idugalic.common.blog.event.BlogPostCreatedEvent;
import com.idugalic.common.blog.event.BlogPostPublishedEvent;
import com.idugalic.common.blog.model.BlogPostCategory;
import java.util.Date;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.model.AggregateIdentifier;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.spring.stereotype.Aggregate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.axonframework.commandhandling.model.AggregateLifecycle.apply; | package com.idugalic.commandside.blog.aggregate;
/**
* A BlogPost aggregate root.
*
* @author idugalic
*
*/
@Aggregate
public class BlogPostAggregate{
private static final Logger LOG = LoggerFactory.getLogger(BlogPostAggregate.class);
/**
* Aggregates that are managed by Axon must have a unique identifier. Strategies
* similar to GUID are often used. The annotation 'AggregateIdentifier' identifies the
* id field as such.
*/
@AggregateIdentifier
private String id;
private String title;
private String rawContent;
private String publicSlug;
private Boolean draft;
private Boolean broadcast;
private Date publishAt;
private BlogPostCategory category;
private String authorId;
/**
* This default constructor is used by the Repository to construct a prototype
* BlogPostAggregate. Events are then used to set properties such as the
* BlogPostAggregate's Id in order to make the Aggregate reflect it's true logical
* state.
*/
public BlogPostAggregate() {
}
/**
* This constructor is marked as a 'CommandHandler' for the AddProductCommand. This
* command can be used to construct new instances of the Aggregate. If successful a
* new BlogPostAggregate is 'applied' to the aggregate using the Axon 'apply' method.
* The apply method appears to also propagate the Event to any other registered 'Event
* Listeners', who may take further action.
*
* @param command
*/
@CommandHandler
public BlogPostAggregate(CreateBlogPostCommand command) {
LOG.debug("Command: 'CreateBlogPostCommand' received.");
LOG.debug("Queuing up a new BlogPostCreatedEvent for blog post '{}'", command.getId());
apply(new BlogPostCreatedEvent(command.getId(), command.getAuditEntry(), command.getTitle(),
command.getRawContent(), command.getPublicSlug(), command.getDraft(), command.getBroadcast(),
command.getPublishAt(), command.getCategory(), command.getAuthorId()));
}
@CommandHandler | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/aggregate/exception/PublishBlogPostException.java
// public class PublishBlogPostException extends IllegalStateException {
//
// private static final long serialVersionUID = 2680537715575935263L;
//
// public PublishBlogPostException() {
// }
//
// public PublishBlogPostException(String s) {
// super(s);
// }
//
// public PublishBlogPostException(Throwable cause) {
// super(cause);
// }
//
// public PublishBlogPostException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/CreateBlogPostCommand.java
// public class CreateBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Title is mandatory")
// @NotBlank(message = "Title is mandatory")
// private String title;
// @NotNull(message = "rawContent is mandatory")
// @NotBlank(message = "rawContent is mandatory")
// private String rawContent;
// @NotNull(message = "PublicSlug is mandatory")
// @NotBlank(message = "PublicSlug is mandatory")
// private String publicSlug;
// @NotNull
// private Boolean draft;
// @NotNull
// private Boolean broadcast;
// @Future(message = "Publish at date must be the future")
// @NotNull
// private Date publishAt;
// @NotNull
// private BlogPostCategory category;
// private String authorId;
//
// public CreateBlogPostCommand(AuditEntry auditEntry, String title, String rawContent, String publicSlug,
// Boolean draft, Boolean broadcast, Date publishAt, BlogPostCategory category, String authorId) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.title = title;
// this.rawContent = rawContent;
// this.publicSlug = publicSlug;
// this.draft = draft;
// this.broadcast = broadcast;
// this.publishAt = publishAt;
// this.category = category;
// this.authorId = authorId;
// }
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public String getAuthorId() {
// return authorId;
// }
//
// }
//
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/PublishBlogPostCommand.java
// public class PublishBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// private Date publishAt;
//
// public PublishBlogPostCommand(String id, AuditEntry auditEntry, Date publishAt) {
// this.id = id;
// this.publishAt = publishAt;
// this.setAuditEntry(auditEntry);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
// }
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/aggregate/BlogPostAggregate.java
import com.idugalic.commandside.blog.aggregate.exception.PublishBlogPostException;
import com.idugalic.commandside.blog.command.CreateBlogPostCommand;
import com.idugalic.commandside.blog.command.PublishBlogPostCommand;
import com.idugalic.common.blog.event.BlogPostCreatedEvent;
import com.idugalic.common.blog.event.BlogPostPublishedEvent;
import com.idugalic.common.blog.model.BlogPostCategory;
import java.util.Date;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.model.AggregateIdentifier;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.spring.stereotype.Aggregate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.axonframework.commandhandling.model.AggregateLifecycle.apply;
package com.idugalic.commandside.blog.aggregate;
/**
* A BlogPost aggregate root.
*
* @author idugalic
*
*/
@Aggregate
public class BlogPostAggregate{
private static final Logger LOG = LoggerFactory.getLogger(BlogPostAggregate.class);
/**
* Aggregates that are managed by Axon must have a unique identifier. Strategies
* similar to GUID are often used. The annotation 'AggregateIdentifier' identifies the
* id field as such.
*/
@AggregateIdentifier
private String id;
private String title;
private String rawContent;
private String publicSlug;
private Boolean draft;
private Boolean broadcast;
private Date publishAt;
private BlogPostCategory category;
private String authorId;
/**
* This default constructor is used by the Repository to construct a prototype
* BlogPostAggregate. Events are then used to set properties such as the
* BlogPostAggregate's Id in order to make the Aggregate reflect it's true logical
* state.
*/
public BlogPostAggregate() {
}
/**
* This constructor is marked as a 'CommandHandler' for the AddProductCommand. This
* command can be used to construct new instances of the Aggregate. If successful a
* new BlogPostAggregate is 'applied' to the aggregate using the Axon 'apply' method.
* The apply method appears to also propagate the Event to any other registered 'Event
* Listeners', who may take further action.
*
* @param command
*/
@CommandHandler
public BlogPostAggregate(CreateBlogPostCommand command) {
LOG.debug("Command: 'CreateBlogPostCommand' received.");
LOG.debug("Queuing up a new BlogPostCreatedEvent for blog post '{}'", command.getId());
apply(new BlogPostCreatedEvent(command.getId(), command.getAuditEntry(), command.getTitle(),
command.getRawContent(), command.getPublicSlug(), command.getDraft(), command.getBroadcast(),
command.getPublishAt(), command.getCategory(), command.getAuthorId()));
}
@CommandHandler | public void publishBlogPost(PublishBlogPostCommand command) { |
idugalic/micro-company | command-side-project/src/main/java/com/idugalic/commandside/project/aggregate/ProjectAggregate.java | // Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/CreateProjectCommand.java
// public class CreateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String category;
// private String description;
//
// public CreateProjectCommand(AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String category, String description) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.category = category;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getCategory() {
// return category;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
//
// Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/UpdateProjectCommand.java
// public class UpdateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String description;
//
// public UpdateProjectCommand(String id, AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String description) {
// super(auditEntry);
// this.id = id;
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
| import com.idugalic.commandside.project.command.CreateProjectCommand;
import com.idugalic.commandside.project.command.UpdateProjectCommand;
import com.idugalic.common.project.event.ProjectCreatedEvent;
import com.idugalic.common.project.event.ProjectUpdatedEvent;
import java.util.ArrayList;
import java.util.List;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.model.AggregateIdentifier;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.spring.stereotype.Aggregate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.axonframework.commandhandling.model.AggregateLifecycle.apply; | package com.idugalic.commandside.project.aggregate;
/**
* A Project aggregate root.
*
* @author idugalic
*
*/
@Aggregate
public class ProjectAggregate {
private static final Logger LOG = LoggerFactory.getLogger(ProjectAggregate.class);
/**
* Aggregates that are managed by Axon must have a unique identifier. Strategies
* similar to GUID are often used. The annotation 'AggregateIdentifier' identifies the
* id field as such.
*/
@AggregateIdentifier
private String id;
private String name;
private String repoUrl;
private String siteUrl;
private String category;
private String description;
private List<ProjectRelease> releaseList = new ArrayList<ProjectRelease>();
/**
* This default constructor is used by the Repository to construct a prototype
* ProjectAggregate. Events are then used to set properties such as the
* ProjectAggregate's Id in order to make the Aggregate reflect it's true logical
* state.
*/
public ProjectAggregate() {
}
/**
* This constructor is marked as a 'CommandHandler' for the AddProductCommand. This
* command can be used to construct new instances of the Aggregate. If successful a
* new ProjectAggregate is 'applied' to the aggregate using the Axon 'apply' method.
* The apply method appears to also propagate the Event to any other registered 'Event
* Listeners', who may take further action.
*
* @param command
*/
@CommandHandler | // Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/CreateProjectCommand.java
// public class CreateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String category;
// private String description;
//
// public CreateProjectCommand(AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String category, String description) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.category = category;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getCategory() {
// return category;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
//
// Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/UpdateProjectCommand.java
// public class UpdateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String description;
//
// public UpdateProjectCommand(String id, AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String description) {
// super(auditEntry);
// this.id = id;
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
// Path: command-side-project/src/main/java/com/idugalic/commandside/project/aggregate/ProjectAggregate.java
import com.idugalic.commandside.project.command.CreateProjectCommand;
import com.idugalic.commandside.project.command.UpdateProjectCommand;
import com.idugalic.common.project.event.ProjectCreatedEvent;
import com.idugalic.common.project.event.ProjectUpdatedEvent;
import java.util.ArrayList;
import java.util.List;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.model.AggregateIdentifier;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.spring.stereotype.Aggregate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.axonframework.commandhandling.model.AggregateLifecycle.apply;
package com.idugalic.commandside.project.aggregate;
/**
* A Project aggregate root.
*
* @author idugalic
*
*/
@Aggregate
public class ProjectAggregate {
private static final Logger LOG = LoggerFactory.getLogger(ProjectAggregate.class);
/**
* Aggregates that are managed by Axon must have a unique identifier. Strategies
* similar to GUID are often used. The annotation 'AggregateIdentifier' identifies the
* id field as such.
*/
@AggregateIdentifier
private String id;
private String name;
private String repoUrl;
private String siteUrl;
private String category;
private String description;
private List<ProjectRelease> releaseList = new ArrayList<ProjectRelease>();
/**
* This default constructor is used by the Repository to construct a prototype
* ProjectAggregate. Events are then used to set properties such as the
* ProjectAggregate's Id in order to make the Aggregate reflect it's true logical
* state.
*/
public ProjectAggregate() {
}
/**
* This constructor is marked as a 'CommandHandler' for the AddProductCommand. This
* command can be used to construct new instances of the Aggregate. If successful a
* new ProjectAggregate is 'applied' to the aggregate using the Axon 'apply' method.
* The apply method appears to also propagate the Event to any other registered 'Event
* Listeners', who may take further action.
*
* @param command
*/
@CommandHandler | public ProjectAggregate(CreateProjectCommand command) { |
idugalic/micro-company | command-side-project/src/main/java/com/idugalic/commandside/project/aggregate/ProjectAggregate.java | // Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/CreateProjectCommand.java
// public class CreateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String category;
// private String description;
//
// public CreateProjectCommand(AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String category, String description) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.category = category;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getCategory() {
// return category;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
//
// Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/UpdateProjectCommand.java
// public class UpdateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String description;
//
// public UpdateProjectCommand(String id, AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String description) {
// super(auditEntry);
// this.id = id;
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
| import com.idugalic.commandside.project.command.CreateProjectCommand;
import com.idugalic.commandside.project.command.UpdateProjectCommand;
import com.idugalic.common.project.event.ProjectCreatedEvent;
import com.idugalic.common.project.event.ProjectUpdatedEvent;
import java.util.ArrayList;
import java.util.List;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.model.AggregateIdentifier;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.spring.stereotype.Aggregate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.axonframework.commandhandling.model.AggregateLifecycle.apply; | package com.idugalic.commandside.project.aggregate;
/**
* A Project aggregate root.
*
* @author idugalic
*
*/
@Aggregate
public class ProjectAggregate {
private static final Logger LOG = LoggerFactory.getLogger(ProjectAggregate.class);
/**
* Aggregates that are managed by Axon must have a unique identifier. Strategies
* similar to GUID are often used. The annotation 'AggregateIdentifier' identifies the
* id field as such.
*/
@AggregateIdentifier
private String id;
private String name;
private String repoUrl;
private String siteUrl;
private String category;
private String description;
private List<ProjectRelease> releaseList = new ArrayList<ProjectRelease>();
/**
* This default constructor is used by the Repository to construct a prototype
* ProjectAggregate. Events are then used to set properties such as the
* ProjectAggregate's Id in order to make the Aggregate reflect it's true logical
* state.
*/
public ProjectAggregate() {
}
/**
* This constructor is marked as a 'CommandHandler' for the AddProductCommand. This
* command can be used to construct new instances of the Aggregate. If successful a
* new ProjectAggregate is 'applied' to the aggregate using the Axon 'apply' method.
* The apply method appears to also propagate the Event to any other registered 'Event
* Listeners', who may take further action.
*
* @param command
*/
@CommandHandler
public ProjectAggregate(CreateProjectCommand command) {
LOG.debug("Command: 'CreateProjectCommand' received.");
LOG.debug("Queuing up a new ProjectCreatedEvent for project '{}'", command.getId());
apply(new ProjectCreatedEvent(command.getId(), command.getAuditEntry(), command.getName(), command.getRepoUrl(), command.getSiteUrl(), command.getCategory(), command
.getDescription()));
}
@CommandHandler | // Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/CreateProjectCommand.java
// public class CreateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String category;
// private String description;
//
// public CreateProjectCommand(AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String category, String description) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.category = category;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getCategory() {
// return category;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
//
// Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/UpdateProjectCommand.java
// public class UpdateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String description;
//
// public UpdateProjectCommand(String id, AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String description) {
// super(auditEntry);
// this.id = id;
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
// Path: command-side-project/src/main/java/com/idugalic/commandside/project/aggregate/ProjectAggregate.java
import com.idugalic.commandside.project.command.CreateProjectCommand;
import com.idugalic.commandside.project.command.UpdateProjectCommand;
import com.idugalic.common.project.event.ProjectCreatedEvent;
import com.idugalic.common.project.event.ProjectUpdatedEvent;
import java.util.ArrayList;
import java.util.List;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.model.AggregateIdentifier;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.spring.stereotype.Aggregate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.axonframework.commandhandling.model.AggregateLifecycle.apply;
package com.idugalic.commandside.project.aggregate;
/**
* A Project aggregate root.
*
* @author idugalic
*
*/
@Aggregate
public class ProjectAggregate {
private static final Logger LOG = LoggerFactory.getLogger(ProjectAggregate.class);
/**
* Aggregates that are managed by Axon must have a unique identifier. Strategies
* similar to GUID are often used. The annotation 'AggregateIdentifier' identifies the
* id field as such.
*/
@AggregateIdentifier
private String id;
private String name;
private String repoUrl;
private String siteUrl;
private String category;
private String description;
private List<ProjectRelease> releaseList = new ArrayList<ProjectRelease>();
/**
* This default constructor is used by the Repository to construct a prototype
* ProjectAggregate. Events are then used to set properties such as the
* ProjectAggregate's Id in order to make the Aggregate reflect it's true logical
* state.
*/
public ProjectAggregate() {
}
/**
* This constructor is marked as a 'CommandHandler' for the AddProductCommand. This
* command can be used to construct new instances of the Aggregate. If successful a
* new ProjectAggregate is 'applied' to the aggregate using the Axon 'apply' method.
* The apply method appears to also propagate the Event to any other registered 'Event
* Listeners', who may take further action.
*
* @param command
*/
@CommandHandler
public ProjectAggregate(CreateProjectCommand command) {
LOG.debug("Command: 'CreateProjectCommand' received.");
LOG.debug("Queuing up a new ProjectCreatedEvent for project '{}'", command.getId());
apply(new ProjectCreatedEvent(command.getId(), command.getAuditEntry(), command.getName(), command.getRepoUrl(), command.getSiteUrl(), command.getCategory(), command
.getDescription()));
}
@CommandHandler | public void updateProject(UpdateProjectCommand command) { |
idugalic/micro-company | command-side-blog/src/main/java/com/idugalic/commandside/blog/web/BlogController.java | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/CreateBlogPostCommand.java
// public class CreateBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Title is mandatory")
// @NotBlank(message = "Title is mandatory")
// private String title;
// @NotNull(message = "rawContent is mandatory")
// @NotBlank(message = "rawContent is mandatory")
// private String rawContent;
// @NotNull(message = "PublicSlug is mandatory")
// @NotBlank(message = "PublicSlug is mandatory")
// private String publicSlug;
// @NotNull
// private Boolean draft;
// @NotNull
// private Boolean broadcast;
// @Future(message = "Publish at date must be the future")
// @NotNull
// private Date publishAt;
// @NotNull
// private BlogPostCategory category;
// private String authorId;
//
// public CreateBlogPostCommand(AuditEntry auditEntry, String title, String rawContent, String publicSlug,
// Boolean draft, Boolean broadcast, Date publishAt, BlogPostCategory category, String authorId) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.title = title;
// this.rawContent = rawContent;
// this.publicSlug = publicSlug;
// this.draft = draft;
// this.broadcast = broadcast;
// this.publishAt = publishAt;
// this.category = category;
// this.authorId = authorId;
// }
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public String getAuthorId() {
// return authorId;
// }
//
// }
//
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/PublishBlogPostCommand.java
// public class PublishBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// private Date publishAt;
//
// public PublishBlogPostCommand(String id, AuditEntry auditEntry, Date publishAt) {
// this.id = id;
// this.publishAt = publishAt;
// this.setAuditEntry(auditEntry);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
// }
| import java.security.Principal;
import javax.servlet.http.HttpServletResponse;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.idugalic.commandside.blog.command.CreateBlogPostCommand;
import com.idugalic.commandside.blog.command.PublishBlogPostCommand;
import com.idugalic.common.model.AuditEntry; | package com.idugalic.commandside.blog.web;
/**
* A web controller for managing {@link BlogPostAggregate} - create/update only.
*
* @author idugalic
*
*/
@RestController
@RequestMapping(value = "/blogpostcommands")
public class BlogController {
private static final Logger LOG = LoggerFactory.getLogger(BlogController.class);
private String getCurrentUser() {
if (SecurityContextHolder.getContext().getAuthentication() != null) {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
return null;
}
private AuditEntry createAudit() {
return new AuditEntry(getCurrentUser());
}
@Autowired
private CommandGateway commandGateway;
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.CREATED)
public void create(@RequestBody CreateBlogPostRequest request, HttpServletResponse response, Principal principal) {
LOG.debug(CreateBlogPostRequest.class.getSimpleName() + " request received");
| // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/CreateBlogPostCommand.java
// public class CreateBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Title is mandatory")
// @NotBlank(message = "Title is mandatory")
// private String title;
// @NotNull(message = "rawContent is mandatory")
// @NotBlank(message = "rawContent is mandatory")
// private String rawContent;
// @NotNull(message = "PublicSlug is mandatory")
// @NotBlank(message = "PublicSlug is mandatory")
// private String publicSlug;
// @NotNull
// private Boolean draft;
// @NotNull
// private Boolean broadcast;
// @Future(message = "Publish at date must be the future")
// @NotNull
// private Date publishAt;
// @NotNull
// private BlogPostCategory category;
// private String authorId;
//
// public CreateBlogPostCommand(AuditEntry auditEntry, String title, String rawContent, String publicSlug,
// Boolean draft, Boolean broadcast, Date publishAt, BlogPostCategory category, String authorId) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.title = title;
// this.rawContent = rawContent;
// this.publicSlug = publicSlug;
// this.draft = draft;
// this.broadcast = broadcast;
// this.publishAt = publishAt;
// this.category = category;
// this.authorId = authorId;
// }
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public String getAuthorId() {
// return authorId;
// }
//
// }
//
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/PublishBlogPostCommand.java
// public class PublishBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// private Date publishAt;
//
// public PublishBlogPostCommand(String id, AuditEntry auditEntry, Date publishAt) {
// this.id = id;
// this.publishAt = publishAt;
// this.setAuditEntry(auditEntry);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
// }
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/web/BlogController.java
import java.security.Principal;
import javax.servlet.http.HttpServletResponse;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.idugalic.commandside.blog.command.CreateBlogPostCommand;
import com.idugalic.commandside.blog.command.PublishBlogPostCommand;
import com.idugalic.common.model.AuditEntry;
package com.idugalic.commandside.blog.web;
/**
* A web controller for managing {@link BlogPostAggregate} - create/update only.
*
* @author idugalic
*
*/
@RestController
@RequestMapping(value = "/blogpostcommands")
public class BlogController {
private static final Logger LOG = LoggerFactory.getLogger(BlogController.class);
private String getCurrentUser() {
if (SecurityContextHolder.getContext().getAuthentication() != null) {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
return null;
}
private AuditEntry createAudit() {
return new AuditEntry(getCurrentUser());
}
@Autowired
private CommandGateway commandGateway;
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.CREATED)
public void create(@RequestBody CreateBlogPostRequest request, HttpServletResponse response, Principal principal) {
LOG.debug(CreateBlogPostRequest.class.getSimpleName() + " request received");
| CreateBlogPostCommand command = new CreateBlogPostCommand(createAudit(), request.getTitle(), |
idugalic/micro-company | command-side-blog/src/main/java/com/idugalic/commandside/blog/web/BlogController.java | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/CreateBlogPostCommand.java
// public class CreateBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Title is mandatory")
// @NotBlank(message = "Title is mandatory")
// private String title;
// @NotNull(message = "rawContent is mandatory")
// @NotBlank(message = "rawContent is mandatory")
// private String rawContent;
// @NotNull(message = "PublicSlug is mandatory")
// @NotBlank(message = "PublicSlug is mandatory")
// private String publicSlug;
// @NotNull
// private Boolean draft;
// @NotNull
// private Boolean broadcast;
// @Future(message = "Publish at date must be the future")
// @NotNull
// private Date publishAt;
// @NotNull
// private BlogPostCategory category;
// private String authorId;
//
// public CreateBlogPostCommand(AuditEntry auditEntry, String title, String rawContent, String publicSlug,
// Boolean draft, Boolean broadcast, Date publishAt, BlogPostCategory category, String authorId) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.title = title;
// this.rawContent = rawContent;
// this.publicSlug = publicSlug;
// this.draft = draft;
// this.broadcast = broadcast;
// this.publishAt = publishAt;
// this.category = category;
// this.authorId = authorId;
// }
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public String getAuthorId() {
// return authorId;
// }
//
// }
//
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/PublishBlogPostCommand.java
// public class PublishBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// private Date publishAt;
//
// public PublishBlogPostCommand(String id, AuditEntry auditEntry, Date publishAt) {
// this.id = id;
// this.publishAt = publishAt;
// this.setAuditEntry(auditEntry);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
// }
| import java.security.Principal;
import javax.servlet.http.HttpServletResponse;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.idugalic.commandside.blog.command.CreateBlogPostCommand;
import com.idugalic.commandside.blog.command.PublishBlogPostCommand;
import com.idugalic.common.model.AuditEntry; | package com.idugalic.commandside.blog.web;
/**
* A web controller for managing {@link BlogPostAggregate} - create/update only.
*
* @author idugalic
*
*/
@RestController
@RequestMapping(value = "/blogpostcommands")
public class BlogController {
private static final Logger LOG = LoggerFactory.getLogger(BlogController.class);
private String getCurrentUser() {
if (SecurityContextHolder.getContext().getAuthentication() != null) {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
return null;
}
private AuditEntry createAudit() {
return new AuditEntry(getCurrentUser());
}
@Autowired
private CommandGateway commandGateway;
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.CREATED)
public void create(@RequestBody CreateBlogPostRequest request, HttpServletResponse response, Principal principal) {
LOG.debug(CreateBlogPostRequest.class.getSimpleName() + " request received");
CreateBlogPostCommand command = new CreateBlogPostCommand(createAudit(), request.getTitle(),
request.getRawContent(), request.getPublicSlug(), request.getDraft(), request.getBroadcast(),
request.getPublishAt(), request.getCategory(), getCurrentUser());
commandGateway.sendAndWait(command);
LOG.debug(CreateBlogPostCommand.class.getSimpleName() + " sent to command gateway: Blog Post [{}] ", command.getId());
}
@RequestMapping(value = "/{id}/publishcommand", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.ACCEPTED)
public void publish(@PathVariable String id, @RequestBody PublishBlogPostRequest request, HttpServletResponse response, Principal principal) {
LOG.debug(PublishBlogPostRequest.class.getSimpleName() + " request received");
| // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/CreateBlogPostCommand.java
// public class CreateBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Title is mandatory")
// @NotBlank(message = "Title is mandatory")
// private String title;
// @NotNull(message = "rawContent is mandatory")
// @NotBlank(message = "rawContent is mandatory")
// private String rawContent;
// @NotNull(message = "PublicSlug is mandatory")
// @NotBlank(message = "PublicSlug is mandatory")
// private String publicSlug;
// @NotNull
// private Boolean draft;
// @NotNull
// private Boolean broadcast;
// @Future(message = "Publish at date must be the future")
// @NotNull
// private Date publishAt;
// @NotNull
// private BlogPostCategory category;
// private String authorId;
//
// public CreateBlogPostCommand(AuditEntry auditEntry, String title, String rawContent, String publicSlug,
// Boolean draft, Boolean broadcast, Date publishAt, BlogPostCategory category, String authorId) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.title = title;
// this.rawContent = rawContent;
// this.publicSlug = publicSlug;
// this.draft = draft;
// this.broadcast = broadcast;
// this.publishAt = publishAt;
// this.category = category;
// this.authorId = authorId;
// }
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public String getAuthorId() {
// return authorId;
// }
//
// }
//
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/PublishBlogPostCommand.java
// public class PublishBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// private Date publishAt;
//
// public PublishBlogPostCommand(String id, AuditEntry auditEntry, Date publishAt) {
// this.id = id;
// this.publishAt = publishAt;
// this.setAuditEntry(auditEntry);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
// }
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/web/BlogController.java
import java.security.Principal;
import javax.servlet.http.HttpServletResponse;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.idugalic.commandside.blog.command.CreateBlogPostCommand;
import com.idugalic.commandside.blog.command.PublishBlogPostCommand;
import com.idugalic.common.model.AuditEntry;
package com.idugalic.commandside.blog.web;
/**
* A web controller for managing {@link BlogPostAggregate} - create/update only.
*
* @author idugalic
*
*/
@RestController
@RequestMapping(value = "/blogpostcommands")
public class BlogController {
private static final Logger LOG = LoggerFactory.getLogger(BlogController.class);
private String getCurrentUser() {
if (SecurityContextHolder.getContext().getAuthentication() != null) {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
return null;
}
private AuditEntry createAudit() {
return new AuditEntry(getCurrentUser());
}
@Autowired
private CommandGateway commandGateway;
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.CREATED)
public void create(@RequestBody CreateBlogPostRequest request, HttpServletResponse response, Principal principal) {
LOG.debug(CreateBlogPostRequest.class.getSimpleName() + " request received");
CreateBlogPostCommand command = new CreateBlogPostCommand(createAudit(), request.getTitle(),
request.getRawContent(), request.getPublicSlug(), request.getDraft(), request.getBroadcast(),
request.getPublishAt(), request.getCategory(), getCurrentUser());
commandGateway.sendAndWait(command);
LOG.debug(CreateBlogPostCommand.class.getSimpleName() + " sent to command gateway: Blog Post [{}] ", command.getId());
}
@RequestMapping(value = "/{id}/publishcommand", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.ACCEPTED)
public void publish(@PathVariable String id, @RequestBody PublishBlogPostRequest request, HttpServletResponse response, Principal principal) {
LOG.debug(PublishBlogPostRequest.class.getSimpleName() + " request received");
| PublishBlogPostCommand command = new PublishBlogPostCommand(id, createAudit(), request.getPublishAt()); |
idugalic/micro-company | monolithic/src/test/java/com/idugalic/commandside/blog/web/BlogControllerTest.java | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/CreateBlogPostCommand.java
// public class CreateBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Title is mandatory")
// @NotBlank(message = "Title is mandatory")
// private String title;
// @NotNull(message = "rawContent is mandatory")
// @NotBlank(message = "rawContent is mandatory")
// private String rawContent;
// @NotNull(message = "PublicSlug is mandatory")
// @NotBlank(message = "PublicSlug is mandatory")
// private String publicSlug;
// @NotNull
// private Boolean draft;
// @NotNull
// private Boolean broadcast;
// @Future(message = "Publish at date must be the future")
// @NotNull
// private Date publishAt;
// @NotNull
// private BlogPostCategory category;
// private String authorId;
//
// public CreateBlogPostCommand(AuditEntry auditEntry, String title, String rawContent, String publicSlug,
// Boolean draft, Boolean broadcast, Date publishAt, BlogPostCategory category, String authorId) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.title = title;
// this.rawContent = rawContent;
// this.publicSlug = publicSlug;
// this.draft = draft;
// this.broadcast = broadcast;
// this.publishAt = publishAt;
// this.category = category;
// this.authorId = authorId;
// }
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public String getAuthorId() {
// return authorId;
// }
//
// }
| import com.idugalic.commandside.blog.command.CreateBlogPostCommand;
import java.nio.charset.Charset;
import java.util.HashSet;
import org.axonframework.commandhandling.CommandExecutionException;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.messaging.interceptors.JSR303ViolationException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.fasterxml.jackson.databind.ObjectMapper;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; | package com.idugalic.commandside.blog.web;
/**
* MVC test for {@link BlogController}
*
* @author idugalic
*
*/
@RunWith(SpringRunner.class)
@WebMvcTest(secure=false, controllers=BlogController.class)
public class BlogControllerTest {
@Autowired
private MockMvc mvc;
private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"));
private JacksonTester<CreateBlogPostRequest> jsonCreate;
@MockBean
private CommandGateway commandGateway;
@Before
public void setup() {
ObjectMapper objectMapper = new ObjectMapper();
// Possibly configure the mapper
JacksonTester.initFields(this, objectMapper);
}
@Test
public void createBlogPostWithValidationErrorTest() throws Exception {
CreateBlogPostRequest request = new CreateBlogPostRequest(); | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/CreateBlogPostCommand.java
// public class CreateBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Title is mandatory")
// @NotBlank(message = "Title is mandatory")
// private String title;
// @NotNull(message = "rawContent is mandatory")
// @NotBlank(message = "rawContent is mandatory")
// private String rawContent;
// @NotNull(message = "PublicSlug is mandatory")
// @NotBlank(message = "PublicSlug is mandatory")
// private String publicSlug;
// @NotNull
// private Boolean draft;
// @NotNull
// private Boolean broadcast;
// @Future(message = "Publish at date must be the future")
// @NotNull
// private Date publishAt;
// @NotNull
// private BlogPostCategory category;
// private String authorId;
//
// public CreateBlogPostCommand(AuditEntry auditEntry, String title, String rawContent, String publicSlug,
// Boolean draft, Boolean broadcast, Date publishAt, BlogPostCategory category, String authorId) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.title = title;
// this.rawContent = rawContent;
// this.publicSlug = publicSlug;
// this.draft = draft;
// this.broadcast = broadcast;
// this.publishAt = publishAt;
// this.category = category;
// this.authorId = authorId;
// }
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public String getAuthorId() {
// return authorId;
// }
//
// }
// Path: monolithic/src/test/java/com/idugalic/commandside/blog/web/BlogControllerTest.java
import com.idugalic.commandside.blog.command.CreateBlogPostCommand;
import java.nio.charset.Charset;
import java.util.HashSet;
import org.axonframework.commandhandling.CommandExecutionException;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.messaging.interceptors.JSR303ViolationException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.fasterxml.jackson.databind.ObjectMapper;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
package com.idugalic.commandside.blog.web;
/**
* MVC test for {@link BlogController}
*
* @author idugalic
*
*/
@RunWith(SpringRunner.class)
@WebMvcTest(secure=false, controllers=BlogController.class)
public class BlogControllerTest {
@Autowired
private MockMvc mvc;
private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"));
private JacksonTester<CreateBlogPostRequest> jsonCreate;
@MockBean
private CommandGateway commandGateway;
@Before
public void setup() {
ObjectMapper objectMapper = new ObjectMapper();
// Possibly configure the mapper
JacksonTester.initFields(this, objectMapper);
}
@Test
public void createBlogPostWithValidationErrorTest() throws Exception {
CreateBlogPostRequest request = new CreateBlogPostRequest(); | given(this.commandGateway.sendAndWait(any(CreateBlogPostCommand.class))).willThrow(new CommandExecutionException("Test", new JSR303ViolationException(new HashSet()))); |
idugalic/micro-company | command-side-project/src/main/java/com/idugalic/commandside/project/web/ProjectController.java | // Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/CreateProjectCommand.java
// public class CreateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String category;
// private String description;
//
// public CreateProjectCommand(AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String category, String description) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.category = category;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getCategory() {
// return category;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
//
// Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/UpdateProjectCommand.java
// public class UpdateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String description;
//
// public UpdateProjectCommand(String id, AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String description) {
// super(auditEntry);
// this.id = id;
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
| import java.security.Principal;
import javax.servlet.http.HttpServletResponse;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.idugalic.commandside.project.command.CreateProjectCommand;
import com.idugalic.commandside.project.command.UpdateProjectCommand;
import com.idugalic.common.model.AuditEntry; | package com.idugalic.commandside.project.web;
/**
* A web controller for managing {@link ProjectAggregate} - create/update only.
*
* @author idugalic
*
*/
@RestController
@RequestMapping(value = "/projectcommands")
public class ProjectController {
private static final Logger LOG = LoggerFactory.getLogger(ProjectController.class);
private String getCurrentUser() {
if (SecurityContextHolder.getContext().getAuthentication() != null) {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
return null;
}
private AuditEntry createAudit() {
return new AuditEntry(getCurrentUser());
}
@Autowired
private CommandGateway commandGateway;
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.CREATED)
public void create(@RequestBody CreateProjectRequest request, HttpServletResponse response, Principal principal) {
LOG.debug(CreateProjectRequest.class.getSimpleName() + " request received"); | // Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/CreateProjectCommand.java
// public class CreateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String category;
// private String description;
//
// public CreateProjectCommand(AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String category, String description) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.category = category;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getCategory() {
// return category;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
//
// Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/UpdateProjectCommand.java
// public class UpdateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String description;
//
// public UpdateProjectCommand(String id, AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String description) {
// super(auditEntry);
// this.id = id;
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
// Path: command-side-project/src/main/java/com/idugalic/commandside/project/web/ProjectController.java
import java.security.Principal;
import javax.servlet.http.HttpServletResponse;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.idugalic.commandside.project.command.CreateProjectCommand;
import com.idugalic.commandside.project.command.UpdateProjectCommand;
import com.idugalic.common.model.AuditEntry;
package com.idugalic.commandside.project.web;
/**
* A web controller for managing {@link ProjectAggregate} - create/update only.
*
* @author idugalic
*
*/
@RestController
@RequestMapping(value = "/projectcommands")
public class ProjectController {
private static final Logger LOG = LoggerFactory.getLogger(ProjectController.class);
private String getCurrentUser() {
if (SecurityContextHolder.getContext().getAuthentication() != null) {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
return null;
}
private AuditEntry createAudit() {
return new AuditEntry(getCurrentUser());
}
@Autowired
private CommandGateway commandGateway;
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.CREATED)
public void create(@RequestBody CreateProjectRequest request, HttpServletResponse response, Principal principal) {
LOG.debug(CreateProjectRequest.class.getSimpleName() + " request received"); | CreateProjectCommand command = new CreateProjectCommand(createAudit(), request.getName(), request.getRepoUrl(), request.getSiteUrl(), request.getCategory(), request |
idugalic/micro-company | command-side-project/src/main/java/com/idugalic/commandside/project/web/ProjectController.java | // Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/CreateProjectCommand.java
// public class CreateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String category;
// private String description;
//
// public CreateProjectCommand(AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String category, String description) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.category = category;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getCategory() {
// return category;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
//
// Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/UpdateProjectCommand.java
// public class UpdateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String description;
//
// public UpdateProjectCommand(String id, AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String description) {
// super(auditEntry);
// this.id = id;
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
| import java.security.Principal;
import javax.servlet.http.HttpServletResponse;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.idugalic.commandside.project.command.CreateProjectCommand;
import com.idugalic.commandside.project.command.UpdateProjectCommand;
import com.idugalic.common.model.AuditEntry; | package com.idugalic.commandside.project.web;
/**
* A web controller for managing {@link ProjectAggregate} - create/update only.
*
* @author idugalic
*
*/
@RestController
@RequestMapping(value = "/projectcommands")
public class ProjectController {
private static final Logger LOG = LoggerFactory.getLogger(ProjectController.class);
private String getCurrentUser() {
if (SecurityContextHolder.getContext().getAuthentication() != null) {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
return null;
}
private AuditEntry createAudit() {
return new AuditEntry(getCurrentUser());
}
@Autowired
private CommandGateway commandGateway;
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.CREATED)
public void create(@RequestBody CreateProjectRequest request, HttpServletResponse response, Principal principal) {
LOG.debug(CreateProjectRequest.class.getSimpleName() + " request received");
CreateProjectCommand command = new CreateProjectCommand(createAudit(), request.getName(), request.getRepoUrl(), request.getSiteUrl(), request.getCategory(), request
.getDescription());
commandGateway.sendAndWait(command);
LOG.debug(CreateProjectCommand.class.getSimpleName() + " sent to command gateway: Project [{}] ", command.getId());
}
@RequestMapping(value = "/{id}/updatecommand", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.ACCEPTED)
public void update(@PathVariable String id, @RequestBody UpdateProjectRequest request, HttpServletResponse response, Principal principal) {
LOG.debug(UpdateProjectRequest.class.getSimpleName() + " request received"); | // Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/CreateProjectCommand.java
// public class CreateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String category;
// private String description;
//
// public CreateProjectCommand(AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String category, String description) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.category = category;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getCategory() {
// return category;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
//
// Path: command-side-project/src/main/java/com/idugalic/commandside/project/command/UpdateProjectCommand.java
// public class UpdateProjectCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Name is mandatory")
// @NotBlank(message = "Name is mandatory")
// private String name;
// @NotNull(message = "Repo Url is mandatory")
// @NotBlank(message = "Repo Url is mandatory")
// private String repoUrl;
// private String siteUrl;
// private String description;
//
// public UpdateProjectCommand(String id, AuditEntry auditEntry, String name, String repoUrl, String siteUrl, String description) {
// super(auditEntry);
// this.id = id;
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public String getDescription() {
// return description;
// }
//
// }
// Path: command-side-project/src/main/java/com/idugalic/commandside/project/web/ProjectController.java
import java.security.Principal;
import javax.servlet.http.HttpServletResponse;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.idugalic.commandside.project.command.CreateProjectCommand;
import com.idugalic.commandside.project.command.UpdateProjectCommand;
import com.idugalic.common.model.AuditEntry;
package com.idugalic.commandside.project.web;
/**
* A web controller for managing {@link ProjectAggregate} - create/update only.
*
* @author idugalic
*
*/
@RestController
@RequestMapping(value = "/projectcommands")
public class ProjectController {
private static final Logger LOG = LoggerFactory.getLogger(ProjectController.class);
private String getCurrentUser() {
if (SecurityContextHolder.getContext().getAuthentication() != null) {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
return null;
}
private AuditEntry createAudit() {
return new AuditEntry(getCurrentUser());
}
@Autowired
private CommandGateway commandGateway;
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.CREATED)
public void create(@RequestBody CreateProjectRequest request, HttpServletResponse response, Principal principal) {
LOG.debug(CreateProjectRequest.class.getSimpleName() + " request received");
CreateProjectCommand command = new CreateProjectCommand(createAudit(), request.getName(), request.getRepoUrl(), request.getSiteUrl(), request.getCategory(), request
.getDescription());
commandGateway.sendAndWait(command);
LOG.debug(CreateProjectCommand.class.getSimpleName() + " sent to command gateway: Project [{}] ", command.getId());
}
@RequestMapping(value = "/{id}/updatecommand", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.ACCEPTED)
public void update(@PathVariable String id, @RequestBody UpdateProjectRequest request, HttpServletResponse response, Principal principal) {
LOG.debug(UpdateProjectRequest.class.getSimpleName() + " request received"); | UpdateProjectCommand command = new UpdateProjectCommand(id, createAudit(), request.getName(), request.getRepoUrl(), request.getSiteUrl(), request.getDescription()); |
idugalic/micro-company | query-side-project/src/main/java/com/idugalic/queryside/project/handler/ProjectViewEventHandler.java | // Path: query-side-project/src/main/java/com/idugalic/queryside/project/domain/Project.java
// @Entity
// public class Project {
// @Id
// private String id;
// @Version
// private Long version;
// private Long aggregateVersion;
// private String name;
// private String repoUrl;
// private String siteUrl;
// private String category;
// private String description;
//
// public Project() {
// }
//
// public Project(ProjectCreatedEvent event, Long aggregateVersion) {
// super();
// this.id = event.getId();
// this.aggregateVersion = aggregateVersion;
// this.name = event.getName();
// this.repoUrl = event.getRepoUrl();
// this.siteUrl = event.getSiteUrl();
// this.category = event.getCategory();
// this.description = event.getDescription();
// }
//
// public Project(String id, Long aggregateVersion, String name, String repoUrl, String siteUrl,
// String category, String description) {
// super();
// this.id = id;
// this.aggregateVersion = aggregateVersion;
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.category = category;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public void setRepoUrl(String repoUrl) {
// this.repoUrl = repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public void setSiteUrl(String siteUrl) {
// this.siteUrl = siteUrl;
// }
//
// public String getCategory() {
// return category;
// }
//
// public void setCategory(String category) {
// this.category = category;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public Long getAggregateVersion() {
// return aggregateVersion;
// }
//
// public void setAggregateVersion(Long aggregateVersion) {
// this.aggregateVersion = aggregateVersion;
// }
//
// }
//
// Path: query-side-project/src/main/java/com/idugalic/queryside/project/repository/ProjectRepository.java
// @RepositoryRestResource(collectionResourceRel = "projects", path = "projects")
// public interface ProjectRepository extends ReadOnlyPagingAndSortingRepository {
// }
| import com.idugalic.common.project.event.ProjectCreatedEvent;
import com.idugalic.queryside.project.domain.Project;
import com.idugalic.queryside.project.repository.ProjectRepository;
import org.axonframework.config.ProcessingGroup;
import org.axonframework.eventhandling.EventHandler;
import org.axonframework.eventsourcing.SequenceNumber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; | package com.idugalic.queryside.project.handler;
/**
* Event handler for {@link ProjrcttCreatedEvent}
*
* @author idugalic
*
*/
@ProcessingGroup("default")
@Component
public class ProjectViewEventHandler{
private static final Logger LOG = LoggerFactory.getLogger(ProjectViewEventHandler.class);
@Autowired | // Path: query-side-project/src/main/java/com/idugalic/queryside/project/domain/Project.java
// @Entity
// public class Project {
// @Id
// private String id;
// @Version
// private Long version;
// private Long aggregateVersion;
// private String name;
// private String repoUrl;
// private String siteUrl;
// private String category;
// private String description;
//
// public Project() {
// }
//
// public Project(ProjectCreatedEvent event, Long aggregateVersion) {
// super();
// this.id = event.getId();
// this.aggregateVersion = aggregateVersion;
// this.name = event.getName();
// this.repoUrl = event.getRepoUrl();
// this.siteUrl = event.getSiteUrl();
// this.category = event.getCategory();
// this.description = event.getDescription();
// }
//
// public Project(String id, Long aggregateVersion, String name, String repoUrl, String siteUrl,
// String category, String description) {
// super();
// this.id = id;
// this.aggregateVersion = aggregateVersion;
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.category = category;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public void setRepoUrl(String repoUrl) {
// this.repoUrl = repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public void setSiteUrl(String siteUrl) {
// this.siteUrl = siteUrl;
// }
//
// public String getCategory() {
// return category;
// }
//
// public void setCategory(String category) {
// this.category = category;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public Long getAggregateVersion() {
// return aggregateVersion;
// }
//
// public void setAggregateVersion(Long aggregateVersion) {
// this.aggregateVersion = aggregateVersion;
// }
//
// }
//
// Path: query-side-project/src/main/java/com/idugalic/queryside/project/repository/ProjectRepository.java
// @RepositoryRestResource(collectionResourceRel = "projects", path = "projects")
// public interface ProjectRepository extends ReadOnlyPagingAndSortingRepository {
// }
// Path: query-side-project/src/main/java/com/idugalic/queryside/project/handler/ProjectViewEventHandler.java
import com.idugalic.common.project.event.ProjectCreatedEvent;
import com.idugalic.queryside.project.domain.Project;
import com.idugalic.queryside.project.repository.ProjectRepository;
import org.axonframework.config.ProcessingGroup;
import org.axonframework.eventhandling.EventHandler;
import org.axonframework.eventsourcing.SequenceNumber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
package com.idugalic.queryside.project.handler;
/**
* Event handler for {@link ProjrcttCreatedEvent}
*
* @author idugalic
*
*/
@ProcessingGroup("default")
@Component
public class ProjectViewEventHandler{
private static final Logger LOG = LoggerFactory.getLogger(ProjectViewEventHandler.class);
@Autowired | private ProjectRepository projectRepository; |
idugalic/micro-company | query-side-project/src/main/java/com/idugalic/queryside/project/handler/ProjectViewEventHandler.java | // Path: query-side-project/src/main/java/com/idugalic/queryside/project/domain/Project.java
// @Entity
// public class Project {
// @Id
// private String id;
// @Version
// private Long version;
// private Long aggregateVersion;
// private String name;
// private String repoUrl;
// private String siteUrl;
// private String category;
// private String description;
//
// public Project() {
// }
//
// public Project(ProjectCreatedEvent event, Long aggregateVersion) {
// super();
// this.id = event.getId();
// this.aggregateVersion = aggregateVersion;
// this.name = event.getName();
// this.repoUrl = event.getRepoUrl();
// this.siteUrl = event.getSiteUrl();
// this.category = event.getCategory();
// this.description = event.getDescription();
// }
//
// public Project(String id, Long aggregateVersion, String name, String repoUrl, String siteUrl,
// String category, String description) {
// super();
// this.id = id;
// this.aggregateVersion = aggregateVersion;
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.category = category;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public void setRepoUrl(String repoUrl) {
// this.repoUrl = repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public void setSiteUrl(String siteUrl) {
// this.siteUrl = siteUrl;
// }
//
// public String getCategory() {
// return category;
// }
//
// public void setCategory(String category) {
// this.category = category;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public Long getAggregateVersion() {
// return aggregateVersion;
// }
//
// public void setAggregateVersion(Long aggregateVersion) {
// this.aggregateVersion = aggregateVersion;
// }
//
// }
//
// Path: query-side-project/src/main/java/com/idugalic/queryside/project/repository/ProjectRepository.java
// @RepositoryRestResource(collectionResourceRel = "projects", path = "projects")
// public interface ProjectRepository extends ReadOnlyPagingAndSortingRepository {
// }
| import com.idugalic.common.project.event.ProjectCreatedEvent;
import com.idugalic.queryside.project.domain.Project;
import com.idugalic.queryside.project.repository.ProjectRepository;
import org.axonframework.config.ProcessingGroup;
import org.axonframework.eventhandling.EventHandler;
import org.axonframework.eventsourcing.SequenceNumber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; | package com.idugalic.queryside.project.handler;
/**
* Event handler for {@link ProjrcttCreatedEvent}
*
* @author idugalic
*
*/
@ProcessingGroup("default")
@Component
public class ProjectViewEventHandler{
private static final Logger LOG = LoggerFactory.getLogger(ProjectViewEventHandler.class);
@Autowired
private ProjectRepository projectRepository;
@EventHandler
public void handle(ProjectCreatedEvent event, @SequenceNumber Long version) {
LOG.info("ProjectCreatedEvent: [{}] ", event.getId()); | // Path: query-side-project/src/main/java/com/idugalic/queryside/project/domain/Project.java
// @Entity
// public class Project {
// @Id
// private String id;
// @Version
// private Long version;
// private Long aggregateVersion;
// private String name;
// private String repoUrl;
// private String siteUrl;
// private String category;
// private String description;
//
// public Project() {
// }
//
// public Project(ProjectCreatedEvent event, Long aggregateVersion) {
// super();
// this.id = event.getId();
// this.aggregateVersion = aggregateVersion;
// this.name = event.getName();
// this.repoUrl = event.getRepoUrl();
// this.siteUrl = event.getSiteUrl();
// this.category = event.getCategory();
// this.description = event.getDescription();
// }
//
// public Project(String id, Long aggregateVersion, String name, String repoUrl, String siteUrl,
// String category, String description) {
// super();
// this.id = id;
// this.aggregateVersion = aggregateVersion;
// this.name = name;
// this.repoUrl = repoUrl;
// this.siteUrl = siteUrl;
// this.category = category;
// this.description = description;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getRepoUrl() {
// return repoUrl;
// }
//
// public void setRepoUrl(String repoUrl) {
// this.repoUrl = repoUrl;
// }
//
// public String getSiteUrl() {
// return siteUrl;
// }
//
// public void setSiteUrl(String siteUrl) {
// this.siteUrl = siteUrl;
// }
//
// public String getCategory() {
// return category;
// }
//
// public void setCategory(String category) {
// this.category = category;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public Long getAggregateVersion() {
// return aggregateVersion;
// }
//
// public void setAggregateVersion(Long aggregateVersion) {
// this.aggregateVersion = aggregateVersion;
// }
//
// }
//
// Path: query-side-project/src/main/java/com/idugalic/queryside/project/repository/ProjectRepository.java
// @RepositoryRestResource(collectionResourceRel = "projects", path = "projects")
// public interface ProjectRepository extends ReadOnlyPagingAndSortingRepository {
// }
// Path: query-side-project/src/main/java/com/idugalic/queryside/project/handler/ProjectViewEventHandler.java
import com.idugalic.common.project.event.ProjectCreatedEvent;
import com.idugalic.queryside.project.domain.Project;
import com.idugalic.queryside.project.repository.ProjectRepository;
import org.axonframework.config.ProcessingGroup;
import org.axonframework.eventhandling.EventHandler;
import org.axonframework.eventsourcing.SequenceNumber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
package com.idugalic.queryside.project.handler;
/**
* Event handler for {@link ProjrcttCreatedEvent}
*
* @author idugalic
*
*/
@ProcessingGroup("default")
@Component
public class ProjectViewEventHandler{
private static final Logger LOG = LoggerFactory.getLogger(ProjectViewEventHandler.class);
@Autowired
private ProjectRepository projectRepository;
@EventHandler
public void handle(ProjectCreatedEvent event, @SequenceNumber Long version) {
LOG.info("ProjectCreatedEvent: [{}] ", event.getId()); | projectRepository.save(new Project(event, version)); |
idugalic/micro-company | query-side-blog/src/main/java/com/idugalic/queryside/blog/repository/BlogPostRepository.java | // Path: query-side-blog/src/main/java/com/idugalic/queryside/blog/domain/BlogPost.java
// @Entity
// public class BlogPost {
// @Id
// private String id;
// @Version
// private Long version;
// private Long aggregateVersion;
// private String title;
// private String rawContent;
// private String renderContent;
// private String publicSlug;
// private Boolean draft;
// private Boolean broadcast;
// private Date publishAt;
// @Enumerated(EnumType.STRING)
// private BlogPostCategory category;
// private String authorId;
//
// public BlogPost() {
// }
//
// public BlogPost(String id, Long aggregateVersion, String title, String rawContent, String renderContent, String publicSlug, Boolean draft,
// Boolean broadcast, Date publishAt, BlogPostCategory category, String authorId) {
// super();
// this.id = id;
// this.aggregateVersion = aggregateVersion;
// this.title = title;
// this.rawContent = rawContent;
// this.renderContent = renderContent;
// this.publicSlug = publicSlug;
// this.draft = draft;
// this.broadcast = broadcast;
// this.publishAt = publishAt;
// this.category = category;
// this.authorId = authorId;
// }
//
// public BlogPost(BlogPostCreatedEvent event, Long aggregateVersion) {
// super();
// this.id = event.getId();
// this.aggregateVersion = aggregateVersion;
// this.title = event.getTitle();
// this.rawContent = event.getRawContent();
// // TODO change this
// this.renderContent = event.getRawContent();
// this.publicSlug = event.getPublicSlug();
// this.draft = event.isDraft();
// this.broadcast = event.isBroadcast();
// this.publishAt = event.getPublishAt();
// this.category = event.getCategory();
// this.authorId = event.getAuthorId();
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public void setRawContent(String rawContent) {
// this.rawContent = rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public void setPublicSlug(String publicSlug) {
// this.publicSlug = publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public void setDraft(Boolean draft) {
// this.draft = draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public void setBroadcast(Boolean broadcast) {
// this.broadcast = broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public void setPublishAt(Date publishAt) {
// this.publishAt = publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public void setCategory(BlogPostCategory category) {
// this.category = category;
// }
//
// public String getRenderContent() {
// return renderContent;
// }
//
// public void setRenderContent(String renderContent) {
// this.renderContent = renderContent;
// }
//
// public String getAuthorId() {
// return authorId;
// }
//
// public void setAuthorId(String authorId) {
// this.authorId = authorId;
// }
//
// public Long getVersion() {
// return aggregateVersion;
// }
//
// public void setVersion(Long version) {
// this.aggregateVersion = version;
// }
//
// public Long getAggregateVersion() {
// return aggregateVersion;
// }
//
// public void setAggregateVersion(Long aggregateVersion) {
// this.aggregateVersion = aggregateVersion;
// }
//
// }
| import com.idugalic.common.blog.model.BlogPostCategory;
import com.idugalic.queryside.blog.domain.BlogPost;
import java.util.Date;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource; | package com.idugalic.queryside.blog.repository;
/**
* A JPA repository for {@link BlogPost}.
*
* @author idugalic
*
*/
@RepositoryRestResource(collectionResourceRel = "blogposts", path = "blogposts")
public interface BlogPostRepository extends ReadOnlyPagingAndSortingRepository { | // Path: query-side-blog/src/main/java/com/idugalic/queryside/blog/domain/BlogPost.java
// @Entity
// public class BlogPost {
// @Id
// private String id;
// @Version
// private Long version;
// private Long aggregateVersion;
// private String title;
// private String rawContent;
// private String renderContent;
// private String publicSlug;
// private Boolean draft;
// private Boolean broadcast;
// private Date publishAt;
// @Enumerated(EnumType.STRING)
// private BlogPostCategory category;
// private String authorId;
//
// public BlogPost() {
// }
//
// public BlogPost(String id, Long aggregateVersion, String title, String rawContent, String renderContent, String publicSlug, Boolean draft,
// Boolean broadcast, Date publishAt, BlogPostCategory category, String authorId) {
// super();
// this.id = id;
// this.aggregateVersion = aggregateVersion;
// this.title = title;
// this.rawContent = rawContent;
// this.renderContent = renderContent;
// this.publicSlug = publicSlug;
// this.draft = draft;
// this.broadcast = broadcast;
// this.publishAt = publishAt;
// this.category = category;
// this.authorId = authorId;
// }
//
// public BlogPost(BlogPostCreatedEvent event, Long aggregateVersion) {
// super();
// this.id = event.getId();
// this.aggregateVersion = aggregateVersion;
// this.title = event.getTitle();
// this.rawContent = event.getRawContent();
// // TODO change this
// this.renderContent = event.getRawContent();
// this.publicSlug = event.getPublicSlug();
// this.draft = event.isDraft();
// this.broadcast = event.isBroadcast();
// this.publishAt = event.getPublishAt();
// this.category = event.getCategory();
// this.authorId = event.getAuthorId();
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public void setRawContent(String rawContent) {
// this.rawContent = rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public void setPublicSlug(String publicSlug) {
// this.publicSlug = publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public void setDraft(Boolean draft) {
// this.draft = draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public void setBroadcast(Boolean broadcast) {
// this.broadcast = broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public void setPublishAt(Date publishAt) {
// this.publishAt = publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public void setCategory(BlogPostCategory category) {
// this.category = category;
// }
//
// public String getRenderContent() {
// return renderContent;
// }
//
// public void setRenderContent(String renderContent) {
// this.renderContent = renderContent;
// }
//
// public String getAuthorId() {
// return authorId;
// }
//
// public void setAuthorId(String authorId) {
// this.authorId = authorId;
// }
//
// public Long getVersion() {
// return aggregateVersion;
// }
//
// public void setVersion(Long version) {
// this.aggregateVersion = version;
// }
//
// public Long getAggregateVersion() {
// return aggregateVersion;
// }
//
// public void setAggregateVersion(Long aggregateVersion) {
// this.aggregateVersion = aggregateVersion;
// }
//
// }
// Path: query-side-blog/src/main/java/com/idugalic/queryside/blog/repository/BlogPostRepository.java
import com.idugalic.common.blog.model.BlogPostCategory;
import com.idugalic.queryside.blog.domain.BlogPost;
import java.util.Date;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
package com.idugalic.queryside.blog.repository;
/**
* A JPA repository for {@link BlogPost}.
*
* @author idugalic
*
*/
@RepositoryRestResource(collectionResourceRel = "blogposts", path = "blogposts")
public interface BlogPostRepository extends ReadOnlyPagingAndSortingRepository { | Page<BlogPost> findByDraftTrue(Pageable pageRequest); |
idugalic/micro-company | command-side-blog-service/src/main/java/com/idugalic/commandside/blog/RestResponseEntityExceptionHandler.java | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/aggregate/exception/PublishBlogPostException.java
// public class PublishBlogPostException extends IllegalStateException {
//
// private static final long serialVersionUID = 2680537715575935263L;
//
// public PublishBlogPostException() {
// }
//
// public PublishBlogPostException(String s) {
// super(s);
// }
//
// public PublishBlogPostException(Throwable cause) {
// super(cause);
// }
//
// public PublishBlogPostException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import com.idugalic.commandside.blog.aggregate.exception.PublishBlogPostException;
import org.axonframework.commandhandling.CommandExecutionException;
import org.axonframework.commandhandling.model.ConcurrencyException;
import org.axonframework.messaging.interceptors.JSR303ViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; | package com.idugalic.commandside.blog;
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger LOG = LoggerFactory.getLogger(RestResponseEntityExceptionHandler.class);
public RestResponseEntityExceptionHandler() {
super();
}
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(final HttpMessageNotReadableException ex, final HttpHeaders headers, final HttpStatus status,
final WebRequest request) {
final String bodyOfResponse = "HttpMessageNotReadableException";
LOG.error(bodyOfResponse, ex);
return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status,
final WebRequest request) {
final String bodyOfResponse = "MethodArgumentNotValidException";
LOG.error(bodyOfResponse, ex);
return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request);
}
// TODO Consider handling validation and other errors/exceptions here
@ExceptionHandler({ CommandExecutionException.class })
protected ResponseEntity<Object> handleCommandExecution(final RuntimeException cex, final WebRequest request) {
final String bodyOfResponse = "CommandExecutionException";
if (null != cex.getCause()) {
LOG.error("CAUSED BY: {} {}", cex.getCause().getClass().getName(), cex.getCause().getMessage());
if (cex.getCause() instanceof ConcurrencyException) {
return handleExceptionInternal(cex, bodyOfResponse + " - Concurrency issue", new HttpHeaders(), HttpStatus.CONFLICT, request);
} | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/aggregate/exception/PublishBlogPostException.java
// public class PublishBlogPostException extends IllegalStateException {
//
// private static final long serialVersionUID = 2680537715575935263L;
//
// public PublishBlogPostException() {
// }
//
// public PublishBlogPostException(String s) {
// super(s);
// }
//
// public PublishBlogPostException(Throwable cause) {
// super(cause);
// }
//
// public PublishBlogPostException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: command-side-blog-service/src/main/java/com/idugalic/commandside/blog/RestResponseEntityExceptionHandler.java
import com.idugalic.commandside.blog.aggregate.exception.PublishBlogPostException;
import org.axonframework.commandhandling.CommandExecutionException;
import org.axonframework.commandhandling.model.ConcurrencyException;
import org.axonframework.messaging.interceptors.JSR303ViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
package com.idugalic.commandside.blog;
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger LOG = LoggerFactory.getLogger(RestResponseEntityExceptionHandler.class);
public RestResponseEntityExceptionHandler() {
super();
}
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(final HttpMessageNotReadableException ex, final HttpHeaders headers, final HttpStatus status,
final WebRequest request) {
final String bodyOfResponse = "HttpMessageNotReadableException";
LOG.error(bodyOfResponse, ex);
return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status,
final WebRequest request) {
final String bodyOfResponse = "MethodArgumentNotValidException";
LOG.error(bodyOfResponse, ex);
return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request);
}
// TODO Consider handling validation and other errors/exceptions here
@ExceptionHandler({ CommandExecutionException.class })
protected ResponseEntity<Object> handleCommandExecution(final RuntimeException cex, final WebRequest request) {
final String bodyOfResponse = "CommandExecutionException";
if (null != cex.getCause()) {
LOG.error("CAUSED BY: {} {}", cex.getCause().getClass().getName(), cex.getCause().getMessage());
if (cex.getCause() instanceof ConcurrencyException) {
return handleExceptionInternal(cex, bodyOfResponse + " - Concurrency issue", new HttpHeaders(), HttpStatus.CONFLICT, request);
} | if (cex.getCause() instanceof PublishBlogPostException) { |
idugalic/micro-company | monolithic/src/test/java/com/idugalic/commandside/blog/aggregate/BlogPostAggregateTest.java | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/CreateBlogPostCommand.java
// public class CreateBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Title is mandatory")
// @NotBlank(message = "Title is mandatory")
// private String title;
// @NotNull(message = "rawContent is mandatory")
// @NotBlank(message = "rawContent is mandatory")
// private String rawContent;
// @NotNull(message = "PublicSlug is mandatory")
// @NotBlank(message = "PublicSlug is mandatory")
// private String publicSlug;
// @NotNull
// private Boolean draft;
// @NotNull
// private Boolean broadcast;
// @Future(message = "Publish at date must be the future")
// @NotNull
// private Date publishAt;
// @NotNull
// private BlogPostCategory category;
// private String authorId;
//
// public CreateBlogPostCommand(AuditEntry auditEntry, String title, String rawContent, String publicSlug,
// Boolean draft, Boolean broadcast, Date publishAt, BlogPostCategory category, String authorId) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.title = title;
// this.rawContent = rawContent;
// this.publicSlug = publicSlug;
// this.draft = draft;
// this.broadcast = broadcast;
// this.publishAt = publishAt;
// this.category = category;
// this.authorId = authorId;
// }
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public String getAuthorId() {
// return authorId;
// }
//
// }
//
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/PublishBlogPostCommand.java
// public class PublishBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// private Date publishAt;
//
// public PublishBlogPostCommand(String id, AuditEntry auditEntry, Date publishAt) {
// this.id = id;
// this.publishAt = publishAt;
// this.setAuditEntry(auditEntry);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
// }
| import com.idugalic.commandside.blog.command.CreateBlogPostCommand;
import com.idugalic.commandside.blog.command.PublishBlogPostCommand;
import com.idugalic.common.blog.event.BlogPostCreatedEvent;
import com.idugalic.common.blog.event.BlogPostPublishedEvent;
import com.idugalic.common.blog.model.BlogPostCategory;
import com.idugalic.common.model.AuditEntry;
import java.util.Calendar;
import java.util.Date;
import org.axonframework.messaging.interceptors.BeanValidationInterceptor;
import org.axonframework.messaging.interceptors.JSR303ViolationException;
import org.axonframework.test.aggregate.AggregateTestFixture;
import org.axonframework.test.aggregate.FixtureConfiguration;
import org.junit.Before;
import org.junit.Test; | package com.idugalic.commandside.blog.aggregate;
/**
* Domain (aggregate) test for {@link BlogPostAggregate}.
*
* @author idugalic
*
*/
public class BlogPostAggregateTest {
private FixtureConfiguration<BlogPostAggregate> fixture;
private AuditEntry auditEntry;
private static final String WHO = "idugalic";
private Calendar future;
@Before
public void setUp() throws Exception {
fixture = new AggregateTestFixture<BlogPostAggregate> (BlogPostAggregate.class);
fixture.registerCommandDispatchInterceptor(new BeanValidationInterceptor());
auditEntry = new AuditEntry(WHO);
future = Calendar.getInstance();
future.add(Calendar.DAY_OF_YEAR, 1);
}
@Test
public void createBlogPostTest() throws Exception { | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/CreateBlogPostCommand.java
// public class CreateBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Title is mandatory")
// @NotBlank(message = "Title is mandatory")
// private String title;
// @NotNull(message = "rawContent is mandatory")
// @NotBlank(message = "rawContent is mandatory")
// private String rawContent;
// @NotNull(message = "PublicSlug is mandatory")
// @NotBlank(message = "PublicSlug is mandatory")
// private String publicSlug;
// @NotNull
// private Boolean draft;
// @NotNull
// private Boolean broadcast;
// @Future(message = "Publish at date must be the future")
// @NotNull
// private Date publishAt;
// @NotNull
// private BlogPostCategory category;
// private String authorId;
//
// public CreateBlogPostCommand(AuditEntry auditEntry, String title, String rawContent, String publicSlug,
// Boolean draft, Boolean broadcast, Date publishAt, BlogPostCategory category, String authorId) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.title = title;
// this.rawContent = rawContent;
// this.publicSlug = publicSlug;
// this.draft = draft;
// this.broadcast = broadcast;
// this.publishAt = publishAt;
// this.category = category;
// this.authorId = authorId;
// }
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public String getAuthorId() {
// return authorId;
// }
//
// }
//
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/PublishBlogPostCommand.java
// public class PublishBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// private Date publishAt;
//
// public PublishBlogPostCommand(String id, AuditEntry auditEntry, Date publishAt) {
// this.id = id;
// this.publishAt = publishAt;
// this.setAuditEntry(auditEntry);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
// }
// Path: monolithic/src/test/java/com/idugalic/commandside/blog/aggregate/BlogPostAggregateTest.java
import com.idugalic.commandside.blog.command.CreateBlogPostCommand;
import com.idugalic.commandside.blog.command.PublishBlogPostCommand;
import com.idugalic.common.blog.event.BlogPostCreatedEvent;
import com.idugalic.common.blog.event.BlogPostPublishedEvent;
import com.idugalic.common.blog.model.BlogPostCategory;
import com.idugalic.common.model.AuditEntry;
import java.util.Calendar;
import java.util.Date;
import org.axonframework.messaging.interceptors.BeanValidationInterceptor;
import org.axonframework.messaging.interceptors.JSR303ViolationException;
import org.axonframework.test.aggregate.AggregateTestFixture;
import org.axonframework.test.aggregate.FixtureConfiguration;
import org.junit.Before;
import org.junit.Test;
package com.idugalic.commandside.blog.aggregate;
/**
* Domain (aggregate) test for {@link BlogPostAggregate}.
*
* @author idugalic
*
*/
public class BlogPostAggregateTest {
private FixtureConfiguration<BlogPostAggregate> fixture;
private AuditEntry auditEntry;
private static final String WHO = "idugalic";
private Calendar future;
@Before
public void setUp() throws Exception {
fixture = new AggregateTestFixture<BlogPostAggregate> (BlogPostAggregate.class);
fixture.registerCommandDispatchInterceptor(new BeanValidationInterceptor());
auditEntry = new AuditEntry(WHO);
future = Calendar.getInstance();
future.add(Calendar.DAY_OF_YEAR, 1);
}
@Test
public void createBlogPostTest() throws Exception { | CreateBlogPostCommand command = new CreateBlogPostCommand(auditEntry, "title", "rowContent", "publicSlug", Boolean.TRUE, Boolean.FALSE, future.getTime(), BlogPostCategory.ENGINEERING, WHO); |
idugalic/micro-company | monolithic/src/test/java/com/idugalic/commandside/blog/aggregate/BlogPostAggregateTest.java | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/CreateBlogPostCommand.java
// public class CreateBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Title is mandatory")
// @NotBlank(message = "Title is mandatory")
// private String title;
// @NotNull(message = "rawContent is mandatory")
// @NotBlank(message = "rawContent is mandatory")
// private String rawContent;
// @NotNull(message = "PublicSlug is mandatory")
// @NotBlank(message = "PublicSlug is mandatory")
// private String publicSlug;
// @NotNull
// private Boolean draft;
// @NotNull
// private Boolean broadcast;
// @Future(message = "Publish at date must be the future")
// @NotNull
// private Date publishAt;
// @NotNull
// private BlogPostCategory category;
// private String authorId;
//
// public CreateBlogPostCommand(AuditEntry auditEntry, String title, String rawContent, String publicSlug,
// Boolean draft, Boolean broadcast, Date publishAt, BlogPostCategory category, String authorId) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.title = title;
// this.rawContent = rawContent;
// this.publicSlug = publicSlug;
// this.draft = draft;
// this.broadcast = broadcast;
// this.publishAt = publishAt;
// this.category = category;
// this.authorId = authorId;
// }
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public String getAuthorId() {
// return authorId;
// }
//
// }
//
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/PublishBlogPostCommand.java
// public class PublishBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// private Date publishAt;
//
// public PublishBlogPostCommand(String id, AuditEntry auditEntry, Date publishAt) {
// this.id = id;
// this.publishAt = publishAt;
// this.setAuditEntry(auditEntry);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
// }
| import com.idugalic.commandside.blog.command.CreateBlogPostCommand;
import com.idugalic.commandside.blog.command.PublishBlogPostCommand;
import com.idugalic.common.blog.event.BlogPostCreatedEvent;
import com.idugalic.common.blog.event.BlogPostPublishedEvent;
import com.idugalic.common.blog.model.BlogPostCategory;
import com.idugalic.common.model.AuditEntry;
import java.util.Calendar;
import java.util.Date;
import org.axonframework.messaging.interceptors.BeanValidationInterceptor;
import org.axonframework.messaging.interceptors.JSR303ViolationException;
import org.axonframework.test.aggregate.AggregateTestFixture;
import org.axonframework.test.aggregate.FixtureConfiguration;
import org.junit.Before;
import org.junit.Test; | package com.idugalic.commandside.blog.aggregate;
/**
* Domain (aggregate) test for {@link BlogPostAggregate}.
*
* @author idugalic
*
*/
public class BlogPostAggregateTest {
private FixtureConfiguration<BlogPostAggregate> fixture;
private AuditEntry auditEntry;
private static final String WHO = "idugalic";
private Calendar future;
@Before
public void setUp() throws Exception {
fixture = new AggregateTestFixture<BlogPostAggregate> (BlogPostAggregate.class);
fixture.registerCommandDispatchInterceptor(new BeanValidationInterceptor());
auditEntry = new AuditEntry(WHO);
future = Calendar.getInstance();
future.add(Calendar.DAY_OF_YEAR, 1);
}
@Test
public void createBlogPostTest() throws Exception {
CreateBlogPostCommand command = new CreateBlogPostCommand(auditEntry, "title", "rowContent", "publicSlug", Boolean.TRUE, Boolean.FALSE, future.getTime(), BlogPostCategory.ENGINEERING, WHO);
fixture.given().when(command).expectEvents(new BlogPostCreatedEvent(command.getId(), command.getAuditEntry(), command.getTitle(), command.getRawContent(), command
.getPublicSlug(), command.getDraft(), command.getBroadcast(), command.getPublishAt(), BlogPostCategory.ENGINEERING, WHO));
}
@Test(expected = JSR303ViolationException.class)
public void createBlogPostWithWrongTitleTest() {
CreateBlogPostCommand command = new CreateBlogPostCommand(auditEntry, null, null, "publicSlug", Boolean.TRUE, Boolean.FALSE, future.getTime(),
BlogPostCategory.ENGINEERING, WHO);
fixture.given().when(command).expectException(JSR303ViolationException.class);
}
@Test
public void publishBlogPostTest() throws Exception { | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/CreateBlogPostCommand.java
// public class CreateBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// @NotNull(message = "Title is mandatory")
// @NotBlank(message = "Title is mandatory")
// private String title;
// @NotNull(message = "rawContent is mandatory")
// @NotBlank(message = "rawContent is mandatory")
// private String rawContent;
// @NotNull(message = "PublicSlug is mandatory")
// @NotBlank(message = "PublicSlug is mandatory")
// private String publicSlug;
// @NotNull
// private Boolean draft;
// @NotNull
// private Boolean broadcast;
// @Future(message = "Publish at date must be the future")
// @NotNull
// private Date publishAt;
// @NotNull
// private BlogPostCategory category;
// private String authorId;
//
// public CreateBlogPostCommand(AuditEntry auditEntry, String title, String rawContent, String publicSlug,
// Boolean draft, Boolean broadcast, Date publishAt, BlogPostCategory category, String authorId) {
// super(auditEntry);
// this.id = UUID.randomUUID().toString();
// this.title = title;
// this.rawContent = rawContent;
// this.publicSlug = publicSlug;
// this.draft = draft;
// this.broadcast = broadcast;
// this.publishAt = publishAt;
// this.category = category;
// this.authorId = authorId;
// }
//
// public String getId() {
// return id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getRawContent() {
// return rawContent;
// }
//
// public String getPublicSlug() {
// return publicSlug;
// }
//
// public Boolean getDraft() {
// return draft;
// }
//
// public Boolean getBroadcast() {
// return broadcast;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
//
// public BlogPostCategory getCategory() {
// return category;
// }
//
// public String getAuthorId() {
// return authorId;
// }
//
// }
//
// Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/command/PublishBlogPostCommand.java
// public class PublishBlogPostCommand extends AuditableAbstractCommand {
//
// @TargetAggregateIdentifier
// private String id;
// private Date publishAt;
//
// public PublishBlogPostCommand(String id, AuditEntry auditEntry, Date publishAt) {
// this.id = id;
// this.publishAt = publishAt;
// this.setAuditEntry(auditEntry);
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Date getPublishAt() {
// return publishAt;
// }
// }
// Path: monolithic/src/test/java/com/idugalic/commandside/blog/aggregate/BlogPostAggregateTest.java
import com.idugalic.commandside.blog.command.CreateBlogPostCommand;
import com.idugalic.commandside.blog.command.PublishBlogPostCommand;
import com.idugalic.common.blog.event.BlogPostCreatedEvent;
import com.idugalic.common.blog.event.BlogPostPublishedEvent;
import com.idugalic.common.blog.model.BlogPostCategory;
import com.idugalic.common.model.AuditEntry;
import java.util.Calendar;
import java.util.Date;
import org.axonframework.messaging.interceptors.BeanValidationInterceptor;
import org.axonframework.messaging.interceptors.JSR303ViolationException;
import org.axonframework.test.aggregate.AggregateTestFixture;
import org.axonframework.test.aggregate.FixtureConfiguration;
import org.junit.Before;
import org.junit.Test;
package com.idugalic.commandside.blog.aggregate;
/**
* Domain (aggregate) test for {@link BlogPostAggregate}.
*
* @author idugalic
*
*/
public class BlogPostAggregateTest {
private FixtureConfiguration<BlogPostAggregate> fixture;
private AuditEntry auditEntry;
private static final String WHO = "idugalic";
private Calendar future;
@Before
public void setUp() throws Exception {
fixture = new AggregateTestFixture<BlogPostAggregate> (BlogPostAggregate.class);
fixture.registerCommandDispatchInterceptor(new BeanValidationInterceptor());
auditEntry = new AuditEntry(WHO);
future = Calendar.getInstance();
future.add(Calendar.DAY_OF_YEAR, 1);
}
@Test
public void createBlogPostTest() throws Exception {
CreateBlogPostCommand command = new CreateBlogPostCommand(auditEntry, "title", "rowContent", "publicSlug", Boolean.TRUE, Boolean.FALSE, future.getTime(), BlogPostCategory.ENGINEERING, WHO);
fixture.given().when(command).expectEvents(new BlogPostCreatedEvent(command.getId(), command.getAuditEntry(), command.getTitle(), command.getRawContent(), command
.getPublicSlug(), command.getDraft(), command.getBroadcast(), command.getPublishAt(), BlogPostCategory.ENGINEERING, WHO));
}
@Test(expected = JSR303ViolationException.class)
public void createBlogPostWithWrongTitleTest() {
CreateBlogPostCommand command = new CreateBlogPostCommand(auditEntry, null, null, "publicSlug", Boolean.TRUE, Boolean.FALSE, future.getTime(),
BlogPostCategory.ENGINEERING, WHO);
fixture.given().when(command).expectException(JSR303ViolationException.class);
}
@Test
public void publishBlogPostTest() throws Exception { | PublishBlogPostCommand command = new PublishBlogPostCommand("id", auditEntry, new Date()); |
idugalic/micro-company | monolithic/src/main/java/com/idugalic/RestResponseEntityExceptionHandler.java | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/aggregate/exception/PublishBlogPostException.java
// public class PublishBlogPostException extends IllegalStateException {
//
// private static final long serialVersionUID = 2680537715575935263L;
//
// public PublishBlogPostException() {
// }
//
// public PublishBlogPostException(String s) {
// super(s);
// }
//
// public PublishBlogPostException(Throwable cause) {
// super(cause);
// }
//
// public PublishBlogPostException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import com.idugalic.commandside.blog.aggregate.exception.PublishBlogPostException;
import org.axonframework.commandhandling.CommandExecutionException;
import org.axonframework.commandhandling.model.ConcurrencyException;
import org.axonframework.messaging.interceptors.JSR303ViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; | package com.idugalic;
/**
* A general exception handler.
* It maps exception type to a response.
*
* @author idugalic
*
*/
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger LOG = LoggerFactory.getLogger(RestResponseEntityExceptionHandler.class);
public RestResponseEntityExceptionHandler() {
super();
}
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(final HttpMessageNotReadableException ex, final HttpHeaders headers, final HttpStatus status,
final WebRequest request) {
final String bodyOfResponse = "HttpMessageNotReadableException";
LOG.error(bodyOfResponse, ex);
return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status,
final WebRequest request) {
final String bodyOfResponse = "MethodArgumentNotValidException";
LOG.error(bodyOfResponse, ex);
return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request);
}
// TODO Consider handling validation and other errors/exceptions here
@ExceptionHandler({ CommandExecutionException.class })
protected ResponseEntity<Object> handleCommandExecution(final RuntimeException cex, final WebRequest request) {
final String bodyOfResponse = "CommandExecutionException";
if (null != cex.getCause()) {
LOG.error("CAUSED BY: {} {}", cex.getCause().getClass().getName(), cex.getCause().getMessage());
if (cex.getCause() instanceof ConcurrencyException) {
return handleExceptionInternal(cex, bodyOfResponse + " - Concurrency issue", new HttpHeaders(), HttpStatus.CONFLICT, request);
} | // Path: command-side-blog/src/main/java/com/idugalic/commandside/blog/aggregate/exception/PublishBlogPostException.java
// public class PublishBlogPostException extends IllegalStateException {
//
// private static final long serialVersionUID = 2680537715575935263L;
//
// public PublishBlogPostException() {
// }
//
// public PublishBlogPostException(String s) {
// super(s);
// }
//
// public PublishBlogPostException(Throwable cause) {
// super(cause);
// }
//
// public PublishBlogPostException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: monolithic/src/main/java/com/idugalic/RestResponseEntityExceptionHandler.java
import com.idugalic.commandside.blog.aggregate.exception.PublishBlogPostException;
import org.axonframework.commandhandling.CommandExecutionException;
import org.axonframework.commandhandling.model.ConcurrencyException;
import org.axonframework.messaging.interceptors.JSR303ViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
package com.idugalic;
/**
* A general exception handler.
* It maps exception type to a response.
*
* @author idugalic
*
*/
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger LOG = LoggerFactory.getLogger(RestResponseEntityExceptionHandler.class);
public RestResponseEntityExceptionHandler() {
super();
}
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(final HttpMessageNotReadableException ex, final HttpHeaders headers, final HttpStatus status,
final WebRequest request) {
final String bodyOfResponse = "HttpMessageNotReadableException";
LOG.error(bodyOfResponse, ex);
return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status,
final WebRequest request) {
final String bodyOfResponse = "MethodArgumentNotValidException";
LOG.error(bodyOfResponse, ex);
return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request);
}
// TODO Consider handling validation and other errors/exceptions here
@ExceptionHandler({ CommandExecutionException.class })
protected ResponseEntity<Object> handleCommandExecution(final RuntimeException cex, final WebRequest request) {
final String bodyOfResponse = "CommandExecutionException";
if (null != cex.getCause()) {
LOG.error("CAUSED BY: {} {}", cex.getCause().getClass().getName(), cex.getCause().getMessage());
if (cex.getCause() instanceof ConcurrencyException) {
return handleExceptionInternal(cex, bodyOfResponse + " - Concurrency issue", new HttpHeaders(), HttpStatus.CONFLICT, request);
} | if (cex.getCause() instanceof PublishBlogPostException) { |
Labs64/NetLicensing-Gateway | src/test/java/com/labs64/netlicensing/gateway/controller/restful/MyCommerceControllerTest.java | // Path: src/main/java/com/labs64/netlicensing/gateway/integrations/mycommerce/MyCommerceController.java
// @Component
// @Produces({ MediaType.TEXT_PLAIN })
// @Path("/" + MyCommerce.MyCommerceConstants.ENDPOINT_BASE_PATH)
// public class MyCommerceController extends AbstractBaseController {
//
// @Autowired
// private MyCommerce myCommerce;
//
// @Autowired
// private PersistingLogger persistingLogger;
//
// @POST
// @Path("/" + Constants.ENDPOINT_PATH_CODEGEN + "/{" + Constants.NetLicensing.PRODUCT_NUMBER + "}")
// @Transactional
// public String codeGenerator(@PathParam(Constants.NetLicensing.PRODUCT_NUMBER) final String productNumber,
// @QueryParam(Constants.NetLicensing.LICENSE_TEMPLATE_NUMBER) final List<String> licenseTemplateList,
// @DefaultValue("true") @QueryParam(Constants.QUANTITY_TO_LICENSEE) final boolean quantityToLicensee,
// @DefaultValue("false") @QueryParam(Constants.SAVE_USER_DATA) final boolean isSaveUserData,
// final MultivaluedMap<String, String> formParams) {
//
// final String purchaseId = formParams.getFirst(MyCommerce.MyCommerceConstants.PURCHASE_ID);
//
// if (purchaseId == null) {
// final String message = "'" + MyCommerce.MyCommerceConstants.PURCHASE_ID + "' is not provided";
// persistingLogger.log(productNumber, null, StoredLog.Severity.ERROR, message);
// throw new BaseException(message);
// }
//
// try {
// final Context context = getSecurityHelper().getContext();
// return myCommerce.codeGenerator(context, purchaseId, productNumber, licenseTemplateList, quantityToLicensee,
// isSaveUserData, formParams);
// } catch (final BaseException e) {
// persistingLogger.log(productNumber, purchaseId, StoredLog.Severity.ERROR,
// e.getResponse().getEntity().toString());
// throw e;
// } catch (final Exception e) {
// persistingLogger.log(productNumber, purchaseId, StoredLog.Severity.ERROR, e.getMessage());
// throw new BaseException(e.getMessage());
// }
// }
//
// @GET
// @Path("/" + Constants.ENDPOINT_PATH_LOG + "/{" + Constants.NetLicensing.PRODUCT_NUMBER + "}")
// public String getErrorLog(@PathParam(Constants.NetLicensing.PRODUCT_NUMBER) final String productNumber,
// @QueryParam(MyCommerce.MyCommerceConstants.PURCHASE_ID) final String purchaseId) {
// try {
// final Context context = getSecurityHelper().getContext();
// return myCommerce.getErrorLog(context, productNumber, purchaseId, MyCommerce.MyCommerceConstants.PURCHASE_ID);
// } catch (final Exception e) {
// throw new BaseException(e.getMessage());
// }
// }
//
// }
| import com.labs64.netlicensing.gateway.integrations.mycommerce.MyCommerceController;
import org.junit.Rule;
import org.junit.rules.ExpectedException; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.gateway.controller.restful;
public class MyCommerceControllerTest extends BaseControllerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Override
protected Class<?> getResourceClass() { | // Path: src/main/java/com/labs64/netlicensing/gateway/integrations/mycommerce/MyCommerceController.java
// @Component
// @Produces({ MediaType.TEXT_PLAIN })
// @Path("/" + MyCommerce.MyCommerceConstants.ENDPOINT_BASE_PATH)
// public class MyCommerceController extends AbstractBaseController {
//
// @Autowired
// private MyCommerce myCommerce;
//
// @Autowired
// private PersistingLogger persistingLogger;
//
// @POST
// @Path("/" + Constants.ENDPOINT_PATH_CODEGEN + "/{" + Constants.NetLicensing.PRODUCT_NUMBER + "}")
// @Transactional
// public String codeGenerator(@PathParam(Constants.NetLicensing.PRODUCT_NUMBER) final String productNumber,
// @QueryParam(Constants.NetLicensing.LICENSE_TEMPLATE_NUMBER) final List<String> licenseTemplateList,
// @DefaultValue("true") @QueryParam(Constants.QUANTITY_TO_LICENSEE) final boolean quantityToLicensee,
// @DefaultValue("false") @QueryParam(Constants.SAVE_USER_DATA) final boolean isSaveUserData,
// final MultivaluedMap<String, String> formParams) {
//
// final String purchaseId = formParams.getFirst(MyCommerce.MyCommerceConstants.PURCHASE_ID);
//
// if (purchaseId == null) {
// final String message = "'" + MyCommerce.MyCommerceConstants.PURCHASE_ID + "' is not provided";
// persistingLogger.log(productNumber, null, StoredLog.Severity.ERROR, message);
// throw new BaseException(message);
// }
//
// try {
// final Context context = getSecurityHelper().getContext();
// return myCommerce.codeGenerator(context, purchaseId, productNumber, licenseTemplateList, quantityToLicensee,
// isSaveUserData, formParams);
// } catch (final BaseException e) {
// persistingLogger.log(productNumber, purchaseId, StoredLog.Severity.ERROR,
// e.getResponse().getEntity().toString());
// throw e;
// } catch (final Exception e) {
// persistingLogger.log(productNumber, purchaseId, StoredLog.Severity.ERROR, e.getMessage());
// throw new BaseException(e.getMessage());
// }
// }
//
// @GET
// @Path("/" + Constants.ENDPOINT_PATH_LOG + "/{" + Constants.NetLicensing.PRODUCT_NUMBER + "}")
// public String getErrorLog(@PathParam(Constants.NetLicensing.PRODUCT_NUMBER) final String productNumber,
// @QueryParam(MyCommerce.MyCommerceConstants.PURCHASE_ID) final String purchaseId) {
// try {
// final Context context = getSecurityHelper().getContext();
// return myCommerce.getErrorLog(context, productNumber, purchaseId, MyCommerce.MyCommerceConstants.PURCHASE_ID);
// } catch (final Exception e) {
// throw new BaseException(e.getMessage());
// }
// }
//
// }
// Path: src/test/java/com/labs64/netlicensing/gateway/controller/restful/MyCommerceControllerTest.java
import com.labs64.netlicensing.gateway.integrations.mycommerce.MyCommerceController;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.gateway.controller.restful;
public class MyCommerceControllerTest extends BaseControllerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Override
protected Class<?> getResourceClass() { | return MyCommerceController.class; |
Labs64/NetLicensing-Gateway | src/test/java/com/labs64/netlicensing/gateway/controller/restful/FastSpringControllerTest.java | // Path: src/main/java/com/labs64/netlicensing/gateway/integrations/fastspring/FastSpringController.java
// @Component
// @Produces({ MediaType.TEXT_PLAIN })
// @Path("/" + FastSpring.FastSpringConstants.ENDPOINT_BASE_PATH)
// public class FastSpringController extends AbstractBaseController {
//
// @Autowired
// private FastSpring fastSpring;
//
// @Autowired
// private PersistingLogger persistingLogger;
//
// @POST
// @Path("/" + Constants.ENDPOINT_PATH_CODEGEN)
// @Transactional
// public String codeGenerator(final MultivaluedMap<String, String> formParams) throws NetLicensingException {
//
// final Context context = getSecurityHelper().getContext();
//
// final String apiKey = formParams.getFirst(FastSpring.FastSpringConstants.API_KEY);
// if (StringUtils.isBlank(apiKey)) {
// throw new BaseException("'" + FastSpring.FastSpringConstants.API_KEY + "' parameter is required");
// }
// context.setSecurityMode(SecurityMode.APIKEY_IDENTIFICATION);
// context.setApiKey(apiKey);
//
// if (!fastSpring.isPrivateKeyValid(context, formParams)) {
// throw new BaseException("Property '" + FastSpring.FastSpringConstants.PRIVATE_KEY + "' do not match");
// }
//
// if (!SecurityHelper.checkContextConnection(context)) {
// throw new BaseException("Wrong " + FastSpring.FastSpringConstants.API_KEY + " provided");
// }
//
// final String reference = formParams.getFirst(FastSpring.FastSpringConstants.REFERENCE);
// final String productNumber = formParams.getFirst(Constants.NetLicensing.PRODUCT_NUMBER);
//
// final List<String> licenseTemplateList = Arrays.asList(
// formParams.getFirst(FastSpring.FastSpringConstants.LICENSE_TEMPLATE_LIST).split("\\s*,\\s*"));
//
// if (StringUtils.isBlank(productNumber) || licenseTemplateList.isEmpty()) {
// throw new BaseException("Required parameters not provided");
// }
//
// if (StringUtils.isBlank(reference)) {
// final String message = "'" + FastSpring.FastSpringConstants.REFERENCE + "' is not provided";
// persistingLogger.log(productNumber, null, StoredLog.Severity.ERROR, message);
// throw new BaseException(message);
// }
//
// //default false
// final boolean isSaveUserData = Boolean.parseBoolean(formParams.getFirst(Constants.SAVE_USER_DATA));
// //default true
// String quantityToLicenseeParam = formParams.getFirst(Constants.QUANTITY_TO_LICENSEE);
// boolean quantityToLicensee = quantityToLicenseeParam == null || Boolean.parseBoolean(quantityToLicenseeParam);
//
// try {
// return fastSpring.codeGenerator(context, reference, productNumber, licenseTemplateList, quantityToLicensee,
// isSaveUserData, formParams);
// } catch (final BaseException e) {
// persistingLogger.log(productNumber, reference, StoredLog.Severity.ERROR,
// e.getResponse().getEntity().toString());
// throw e;
// } catch (final Exception e) {
// persistingLogger.log(productNumber, reference, StoredLog.Severity.ERROR, e.getMessage());
// throw new BaseException(e.getMessage());
// }
// }
//
// @GET
// @Path("/" + Constants.ENDPOINT_PATH_LOG + "/{" + Constants.NetLicensing.PRODUCT_NUMBER + "}")
// public String getErrorLog(@PathParam(Constants.NetLicensing.PRODUCT_NUMBER) final String productNumber,
// @QueryParam(FastSpring.FastSpringConstants.REFERENCE) final String reference) {
// try {
// final Context context = getSecurityHelper().getContext();
// return fastSpring.getErrorLog(context, productNumber, reference, FastSpring.FastSpringConstants.REFERENCE);
// } catch (final Exception e) {
// throw new BaseException(e.getMessage());
// }
// }
// }
| import com.labs64.netlicensing.gateway.integrations.fastspring.FastSpringController;
import org.junit.Rule;
import org.junit.rules.ExpectedException; | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.gateway.controller.restful;
public class FastSpringControllerTest extends BaseControllerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Override
protected Class<?> getResourceClass() { | // Path: src/main/java/com/labs64/netlicensing/gateway/integrations/fastspring/FastSpringController.java
// @Component
// @Produces({ MediaType.TEXT_PLAIN })
// @Path("/" + FastSpring.FastSpringConstants.ENDPOINT_BASE_PATH)
// public class FastSpringController extends AbstractBaseController {
//
// @Autowired
// private FastSpring fastSpring;
//
// @Autowired
// private PersistingLogger persistingLogger;
//
// @POST
// @Path("/" + Constants.ENDPOINT_PATH_CODEGEN)
// @Transactional
// public String codeGenerator(final MultivaluedMap<String, String> formParams) throws NetLicensingException {
//
// final Context context = getSecurityHelper().getContext();
//
// final String apiKey = formParams.getFirst(FastSpring.FastSpringConstants.API_KEY);
// if (StringUtils.isBlank(apiKey)) {
// throw new BaseException("'" + FastSpring.FastSpringConstants.API_KEY + "' parameter is required");
// }
// context.setSecurityMode(SecurityMode.APIKEY_IDENTIFICATION);
// context.setApiKey(apiKey);
//
// if (!fastSpring.isPrivateKeyValid(context, formParams)) {
// throw new BaseException("Property '" + FastSpring.FastSpringConstants.PRIVATE_KEY + "' do not match");
// }
//
// if (!SecurityHelper.checkContextConnection(context)) {
// throw new BaseException("Wrong " + FastSpring.FastSpringConstants.API_KEY + " provided");
// }
//
// final String reference = formParams.getFirst(FastSpring.FastSpringConstants.REFERENCE);
// final String productNumber = formParams.getFirst(Constants.NetLicensing.PRODUCT_NUMBER);
//
// final List<String> licenseTemplateList = Arrays.asList(
// formParams.getFirst(FastSpring.FastSpringConstants.LICENSE_TEMPLATE_LIST).split("\\s*,\\s*"));
//
// if (StringUtils.isBlank(productNumber) || licenseTemplateList.isEmpty()) {
// throw new BaseException("Required parameters not provided");
// }
//
// if (StringUtils.isBlank(reference)) {
// final String message = "'" + FastSpring.FastSpringConstants.REFERENCE + "' is not provided";
// persistingLogger.log(productNumber, null, StoredLog.Severity.ERROR, message);
// throw new BaseException(message);
// }
//
// //default false
// final boolean isSaveUserData = Boolean.parseBoolean(formParams.getFirst(Constants.SAVE_USER_DATA));
// //default true
// String quantityToLicenseeParam = formParams.getFirst(Constants.QUANTITY_TO_LICENSEE);
// boolean quantityToLicensee = quantityToLicenseeParam == null || Boolean.parseBoolean(quantityToLicenseeParam);
//
// try {
// return fastSpring.codeGenerator(context, reference, productNumber, licenseTemplateList, quantityToLicensee,
// isSaveUserData, formParams);
// } catch (final BaseException e) {
// persistingLogger.log(productNumber, reference, StoredLog.Severity.ERROR,
// e.getResponse().getEntity().toString());
// throw e;
// } catch (final Exception e) {
// persistingLogger.log(productNumber, reference, StoredLog.Severity.ERROR, e.getMessage());
// throw new BaseException(e.getMessage());
// }
// }
//
// @GET
// @Path("/" + Constants.ENDPOINT_PATH_LOG + "/{" + Constants.NetLicensing.PRODUCT_NUMBER + "}")
// public String getErrorLog(@PathParam(Constants.NetLicensing.PRODUCT_NUMBER) final String productNumber,
// @QueryParam(FastSpring.FastSpringConstants.REFERENCE) final String reference) {
// try {
// final Context context = getSecurityHelper().getContext();
// return fastSpring.getErrorLog(context, productNumber, reference, FastSpring.FastSpringConstants.REFERENCE);
// } catch (final Exception e) {
// throw new BaseException(e.getMessage());
// }
// }
// }
// Path: src/test/java/com/labs64/netlicensing/gateway/controller/restful/FastSpringControllerTest.java
import com.labs64.netlicensing.gateway.integrations.fastspring.FastSpringController;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.gateway.controller.restful;
public class FastSpringControllerTest extends BaseControllerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Override
protected Class<?> getResourceClass() { | return FastSpringController.class; |
Labs64/NetLicensing-Gateway | src/main/java/com/labs64/netlicensing/gateway/controller/restful/MonitoringController.java | // Path: src/main/java/com/labs64/netlicensing/gateway/controller/exception/MonitoringException.java
// public class MonitoringException extends GatewayException {
//
// private static final long serialVersionUID = 3032494846331391138L;
//
// public MonitoringException(final String message) {
// super(Response.status(Response.Status.SERVICE_UNAVAILABLE).entity(message).type(MediaType.TEXT_PLAIN)
// .build());
// }
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/domain/repositories/TimeStampRepository.java
// public interface TimeStampRepository extends CrudRepository<TimeStamp, String> {
//
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/util/Constants.java
// public class Constants {
//
// private Constants() {
// }
//
// public static final String NEXT_CLEANUP_LOGGING_TAG = "NEXT_CLEANUP_LOGGING";
// public static final int CLEANUP_PERIOD_MINUTES = 60;
// public static final int LOG_PERSIST_DAYS = 30;
//
// public static final String QUANTITY_TO_LICENSEE = "quantityToLicensee";
// public static final String ENDPOINT_PATH_CODEGEN = "codegen";
// public static final String ENDPOINT_PATH_LOG = "log";
// public static final String SAVE_USER_DATA = "saveUserData";
//
// public static final class NetLicensing {
// public static final String PRODUCT_NUMBER = "productNumber";
// public static final String LICENSE_TEMPLATE_NUMBER = "licenseTemplateNumber";
// public static final String LICENSEE_NUMBER = "licenseeNumber";
// public static final String LICENSEE_NAME = "name";
// public static final String PROP_MARKED_FOR_TRANSFER = "markedForTransfer";
// public static final String PROP_START_DATE = "startDate";
// }
//
// public static final class Monitoring {
// public static final String ENDPOINT_BASE_PATH = "monitoring";
// }
// }
| import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.labs64.netlicensing.domain.vo.Context;
import com.labs64.netlicensing.gateway.controller.exception.MonitoringException;
import com.labs64.netlicensing.gateway.domain.repositories.TimeStampRepository;
import com.labs64.netlicensing.gateway.util.Constants;
import com.labs64.netlicensing.service.UtilityService; | package com.labs64.netlicensing.gateway.controller.restful;
@Component
@Path("/" + Constants.Monitoring.ENDPOINT_BASE_PATH)
public class MonitoringController extends AbstractBaseController {
private static final Logger LOGGER = LogManager.getLogger(MonitoringController.class);
@Autowired | // Path: src/main/java/com/labs64/netlicensing/gateway/controller/exception/MonitoringException.java
// public class MonitoringException extends GatewayException {
//
// private static final long serialVersionUID = 3032494846331391138L;
//
// public MonitoringException(final String message) {
// super(Response.status(Response.Status.SERVICE_UNAVAILABLE).entity(message).type(MediaType.TEXT_PLAIN)
// .build());
// }
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/domain/repositories/TimeStampRepository.java
// public interface TimeStampRepository extends CrudRepository<TimeStamp, String> {
//
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/util/Constants.java
// public class Constants {
//
// private Constants() {
// }
//
// public static final String NEXT_CLEANUP_LOGGING_TAG = "NEXT_CLEANUP_LOGGING";
// public static final int CLEANUP_PERIOD_MINUTES = 60;
// public static final int LOG_PERSIST_DAYS = 30;
//
// public static final String QUANTITY_TO_LICENSEE = "quantityToLicensee";
// public static final String ENDPOINT_PATH_CODEGEN = "codegen";
// public static final String ENDPOINT_PATH_LOG = "log";
// public static final String SAVE_USER_DATA = "saveUserData";
//
// public static final class NetLicensing {
// public static final String PRODUCT_NUMBER = "productNumber";
// public static final String LICENSE_TEMPLATE_NUMBER = "licenseTemplateNumber";
// public static final String LICENSEE_NUMBER = "licenseeNumber";
// public static final String LICENSEE_NAME = "name";
// public static final String PROP_MARKED_FOR_TRANSFER = "markedForTransfer";
// public static final String PROP_START_DATE = "startDate";
// }
//
// public static final class Monitoring {
// public static final String ENDPOINT_BASE_PATH = "monitoring";
// }
// }
// Path: src/main/java/com/labs64/netlicensing/gateway/controller/restful/MonitoringController.java
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.labs64.netlicensing.domain.vo.Context;
import com.labs64.netlicensing.gateway.controller.exception.MonitoringException;
import com.labs64.netlicensing.gateway.domain.repositories.TimeStampRepository;
import com.labs64.netlicensing.gateway.util.Constants;
import com.labs64.netlicensing.service.UtilityService;
package com.labs64.netlicensing.gateway.controller.restful;
@Component
@Path("/" + Constants.Monitoring.ENDPOINT_BASE_PATH)
public class MonitoringController extends AbstractBaseController {
private static final Logger LOGGER = LogManager.getLogger(MonitoringController.class);
@Autowired | private TimeStampRepository timeStampRepository; |
Labs64/NetLicensing-Gateway | src/main/java/com/labs64/netlicensing/gateway/controller/restful/MonitoringController.java | // Path: src/main/java/com/labs64/netlicensing/gateway/controller/exception/MonitoringException.java
// public class MonitoringException extends GatewayException {
//
// private static final long serialVersionUID = 3032494846331391138L;
//
// public MonitoringException(final String message) {
// super(Response.status(Response.Status.SERVICE_UNAVAILABLE).entity(message).type(MediaType.TEXT_PLAIN)
// .build());
// }
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/domain/repositories/TimeStampRepository.java
// public interface TimeStampRepository extends CrudRepository<TimeStamp, String> {
//
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/util/Constants.java
// public class Constants {
//
// private Constants() {
// }
//
// public static final String NEXT_CLEANUP_LOGGING_TAG = "NEXT_CLEANUP_LOGGING";
// public static final int CLEANUP_PERIOD_MINUTES = 60;
// public static final int LOG_PERSIST_DAYS = 30;
//
// public static final String QUANTITY_TO_LICENSEE = "quantityToLicensee";
// public static final String ENDPOINT_PATH_CODEGEN = "codegen";
// public static final String ENDPOINT_PATH_LOG = "log";
// public static final String SAVE_USER_DATA = "saveUserData";
//
// public static final class NetLicensing {
// public static final String PRODUCT_NUMBER = "productNumber";
// public static final String LICENSE_TEMPLATE_NUMBER = "licenseTemplateNumber";
// public static final String LICENSEE_NUMBER = "licenseeNumber";
// public static final String LICENSEE_NAME = "name";
// public static final String PROP_MARKED_FOR_TRANSFER = "markedForTransfer";
// public static final String PROP_START_DATE = "startDate";
// }
//
// public static final class Monitoring {
// public static final String ENDPOINT_BASE_PATH = "monitoring";
// }
// }
| import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.labs64.netlicensing.domain.vo.Context;
import com.labs64.netlicensing.gateway.controller.exception.MonitoringException;
import com.labs64.netlicensing.gateway.domain.repositories.TimeStampRepository;
import com.labs64.netlicensing.gateway.util.Constants;
import com.labs64.netlicensing.service.UtilityService; | package com.labs64.netlicensing.gateway.controller.restful;
@Component
@Path("/" + Constants.Monitoring.ENDPOINT_BASE_PATH)
public class MonitoringController extends AbstractBaseController {
private static final Logger LOGGER = LogManager.getLogger(MonitoringController.class);
@Autowired
private TimeStampRepository timeStampRepository;
@Value("${project.name}")
private String projectName;
@Value("${project.version}")
private String projectVersion;
@GET
@Path("/")
public String monitoring() {
checkNetLicensingAvailability();
checkDatabaseAvailability();
LOGGER.debug("{} v{} is up and running.", projectName, projectVersion);
return projectName + " v" + projectVersion + " is up and running.";
}
private void checkNetLicensingAvailability() {
try {
final Context context = getSecurityHelper().getMonitoringContext();
UtilityService.listLicenseTypes(context);
} catch (final Exception e) {
LOGGER.error("Monitoring: NetLicensing Error", e); | // Path: src/main/java/com/labs64/netlicensing/gateway/controller/exception/MonitoringException.java
// public class MonitoringException extends GatewayException {
//
// private static final long serialVersionUID = 3032494846331391138L;
//
// public MonitoringException(final String message) {
// super(Response.status(Response.Status.SERVICE_UNAVAILABLE).entity(message).type(MediaType.TEXT_PLAIN)
// .build());
// }
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/domain/repositories/TimeStampRepository.java
// public interface TimeStampRepository extends CrudRepository<TimeStamp, String> {
//
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/util/Constants.java
// public class Constants {
//
// private Constants() {
// }
//
// public static final String NEXT_CLEANUP_LOGGING_TAG = "NEXT_CLEANUP_LOGGING";
// public static final int CLEANUP_PERIOD_MINUTES = 60;
// public static final int LOG_PERSIST_DAYS = 30;
//
// public static final String QUANTITY_TO_LICENSEE = "quantityToLicensee";
// public static final String ENDPOINT_PATH_CODEGEN = "codegen";
// public static final String ENDPOINT_PATH_LOG = "log";
// public static final String SAVE_USER_DATA = "saveUserData";
//
// public static final class NetLicensing {
// public static final String PRODUCT_NUMBER = "productNumber";
// public static final String LICENSE_TEMPLATE_NUMBER = "licenseTemplateNumber";
// public static final String LICENSEE_NUMBER = "licenseeNumber";
// public static final String LICENSEE_NAME = "name";
// public static final String PROP_MARKED_FOR_TRANSFER = "markedForTransfer";
// public static final String PROP_START_DATE = "startDate";
// }
//
// public static final class Monitoring {
// public static final String ENDPOINT_BASE_PATH = "monitoring";
// }
// }
// Path: src/main/java/com/labs64/netlicensing/gateway/controller/restful/MonitoringController.java
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.labs64.netlicensing.domain.vo.Context;
import com.labs64.netlicensing.gateway.controller.exception.MonitoringException;
import com.labs64.netlicensing.gateway.domain.repositories.TimeStampRepository;
import com.labs64.netlicensing.gateway.util.Constants;
import com.labs64.netlicensing.service.UtilityService;
package com.labs64.netlicensing.gateway.controller.restful;
@Component
@Path("/" + Constants.Monitoring.ENDPOINT_BASE_PATH)
public class MonitoringController extends AbstractBaseController {
private static final Logger LOGGER = LogManager.getLogger(MonitoringController.class);
@Autowired
private TimeStampRepository timeStampRepository;
@Value("${project.name}")
private String projectName;
@Value("${project.version}")
private String projectVersion;
@GET
@Path("/")
public String monitoring() {
checkNetLicensingAvailability();
checkDatabaseAvailability();
LOGGER.debug("{} v{} is up and running.", projectName, projectVersion);
return projectName + " v" + projectVersion + " is up and running.";
}
private void checkNetLicensingAvailability() {
try {
final Context context = getSecurityHelper().getMonitoringContext();
UtilityService.listLicenseTypes(context);
} catch (final Exception e) {
LOGGER.error("Monitoring: NetLicensing Error", e); | throw new MonitoringException("NetLicensing is not reachable."); |
Labs64/NetLicensing-Gateway | src/main/java/com/labs64/netlicensing/gateway/bl/PersistingLogger.java | // Path: src/main/java/com/labs64/netlicensing/gateway/domain/entity/StoredLog.java
// @Entity
// @Table(name = "LOGGING")
// public class StoredLog extends AbstractPersistable<String> {
//
// private static final long serialVersionUID = -8835218729902563568L;
//
// public enum Severity {
// INFO, WARNING, ERROR
// }
//
// public StoredLog() {
// }
//
// @Column(name = "KEY", nullable = true)
// private String key;
//
// @Column(name = "SECONDARY_KEY", nullable = true)
// private String secondaryKey;
//
// @Column(name = "MESSAGE", nullable = true)
// private String message;
//
// @Column(name = "SEVERITY", nullable = true)
// private Severity severity;
//
// @Column(name = "TIMESTAMP", nullable = false)
// @Temporal(value = TemporalType.TIMESTAMP)
// private Date timestamp;
//
// public String getKey() {
// return key;
// }
//
// public void setKey(final String key) {
// this.key = key;
// }
//
// public String getSecondaryKey() {
// return secondaryKey;
// }
//
// public void setSecondaryKey(final String secondaryKey) {
// this.secondaryKey = secondaryKey;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(final String message) {
// this.message = message;
// }
//
// public Severity getSeverity() {
// return severity;
// }
//
// public void setSeverity(final Severity severity) {
// this.severity = severity;
// }
//
// public Date getTimestamp() {
// if (timestamp == null) {
// return null;
// } else {
// return new Date(timestamp.getTime());
// }
// }
//
// public void setTimestamp(final Date timestamp) {
// if (timestamp == null) {
// this.timestamp = new Date();
// } else {
// this.timestamp = new Date(timestamp.getTime());
// }
// }
//
// @Override
// public String toString() {
// final StringBuilder builder = new StringBuilder();
// builder.append("key=");
// builder.append(getKey());
// builder.append(", severity=");
// builder.append(getSeverity());
// builder.append(", message=");
// builder.append(getMessage());
// builder.append(", timestamp=");
// builder.append(getTimestamp());
// return builder.toString();
// }
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/domain/repositories/LogRepository.java
// public interface LogRepository extends CrudRepository<StoredLog, String> {
//
// List<StoredLog> findByKey(String key);
//
// List<StoredLog> findByKeyAndSecondaryKey(String key, String secondaryKey);
//
// void deleteByTimestampBefore(@Temporal(TemporalType.TIMESTAMP) Date date);
//
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/util/Constants.java
// public class Constants {
//
// private Constants() {
// }
//
// public static final String NEXT_CLEANUP_LOGGING_TAG = "NEXT_CLEANUP_LOGGING";
// public static final int CLEANUP_PERIOD_MINUTES = 60;
// public static final int LOG_PERSIST_DAYS = 30;
//
// public static final String QUANTITY_TO_LICENSEE = "quantityToLicensee";
// public static final String ENDPOINT_PATH_CODEGEN = "codegen";
// public static final String ENDPOINT_PATH_LOG = "log";
// public static final String SAVE_USER_DATA = "saveUserData";
//
// public static final class NetLicensing {
// public static final String PRODUCT_NUMBER = "productNumber";
// public static final String LICENSE_TEMPLATE_NUMBER = "licenseTemplateNumber";
// public static final String LICENSEE_NUMBER = "licenseeNumber";
// public static final String LICENSEE_NAME = "name";
// public static final String PROP_MARKED_FOR_TRANSFER = "markedForTransfer";
// public static final String PROP_START_DATE = "startDate";
// }
//
// public static final class Monitoring {
// public static final String ENDPOINT_BASE_PATH = "monitoring";
// }
// }
| import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.labs64.netlicensing.gateway.domain.entity.StoredLog;
import com.labs64.netlicensing.gateway.domain.repositories.LogRepository;
import com.labs64.netlicensing.gateway.util.Constants; | package com.labs64.netlicensing.gateway.bl;
@Component
public class PersistingLogger {
@Autowired | // Path: src/main/java/com/labs64/netlicensing/gateway/domain/entity/StoredLog.java
// @Entity
// @Table(name = "LOGGING")
// public class StoredLog extends AbstractPersistable<String> {
//
// private static final long serialVersionUID = -8835218729902563568L;
//
// public enum Severity {
// INFO, WARNING, ERROR
// }
//
// public StoredLog() {
// }
//
// @Column(name = "KEY", nullable = true)
// private String key;
//
// @Column(name = "SECONDARY_KEY", nullable = true)
// private String secondaryKey;
//
// @Column(name = "MESSAGE", nullable = true)
// private String message;
//
// @Column(name = "SEVERITY", nullable = true)
// private Severity severity;
//
// @Column(name = "TIMESTAMP", nullable = false)
// @Temporal(value = TemporalType.TIMESTAMP)
// private Date timestamp;
//
// public String getKey() {
// return key;
// }
//
// public void setKey(final String key) {
// this.key = key;
// }
//
// public String getSecondaryKey() {
// return secondaryKey;
// }
//
// public void setSecondaryKey(final String secondaryKey) {
// this.secondaryKey = secondaryKey;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(final String message) {
// this.message = message;
// }
//
// public Severity getSeverity() {
// return severity;
// }
//
// public void setSeverity(final Severity severity) {
// this.severity = severity;
// }
//
// public Date getTimestamp() {
// if (timestamp == null) {
// return null;
// } else {
// return new Date(timestamp.getTime());
// }
// }
//
// public void setTimestamp(final Date timestamp) {
// if (timestamp == null) {
// this.timestamp = new Date();
// } else {
// this.timestamp = new Date(timestamp.getTime());
// }
// }
//
// @Override
// public String toString() {
// final StringBuilder builder = new StringBuilder();
// builder.append("key=");
// builder.append(getKey());
// builder.append(", severity=");
// builder.append(getSeverity());
// builder.append(", message=");
// builder.append(getMessage());
// builder.append(", timestamp=");
// builder.append(getTimestamp());
// return builder.toString();
// }
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/domain/repositories/LogRepository.java
// public interface LogRepository extends CrudRepository<StoredLog, String> {
//
// List<StoredLog> findByKey(String key);
//
// List<StoredLog> findByKeyAndSecondaryKey(String key, String secondaryKey);
//
// void deleteByTimestampBefore(@Temporal(TemporalType.TIMESTAMP) Date date);
//
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/util/Constants.java
// public class Constants {
//
// private Constants() {
// }
//
// public static final String NEXT_CLEANUP_LOGGING_TAG = "NEXT_CLEANUP_LOGGING";
// public static final int CLEANUP_PERIOD_MINUTES = 60;
// public static final int LOG_PERSIST_DAYS = 30;
//
// public static final String QUANTITY_TO_LICENSEE = "quantityToLicensee";
// public static final String ENDPOINT_PATH_CODEGEN = "codegen";
// public static final String ENDPOINT_PATH_LOG = "log";
// public static final String SAVE_USER_DATA = "saveUserData";
//
// public static final class NetLicensing {
// public static final String PRODUCT_NUMBER = "productNumber";
// public static final String LICENSE_TEMPLATE_NUMBER = "licenseTemplateNumber";
// public static final String LICENSEE_NUMBER = "licenseeNumber";
// public static final String LICENSEE_NAME = "name";
// public static final String PROP_MARKED_FOR_TRANSFER = "markedForTransfer";
// public static final String PROP_START_DATE = "startDate";
// }
//
// public static final class Monitoring {
// public static final String ENDPOINT_BASE_PATH = "monitoring";
// }
// }
// Path: src/main/java/com/labs64/netlicensing/gateway/bl/PersistingLogger.java
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.labs64.netlicensing.gateway.domain.entity.StoredLog;
import com.labs64.netlicensing.gateway.domain.repositories.LogRepository;
import com.labs64.netlicensing.gateway.util.Constants;
package com.labs64.netlicensing.gateway.bl;
@Component
public class PersistingLogger {
@Autowired | private LogRepository logRepository; |
Labs64/NetLicensing-Gateway | src/main/java/com/labs64/netlicensing/gateway/bl/PersistingLogger.java | // Path: src/main/java/com/labs64/netlicensing/gateway/domain/entity/StoredLog.java
// @Entity
// @Table(name = "LOGGING")
// public class StoredLog extends AbstractPersistable<String> {
//
// private static final long serialVersionUID = -8835218729902563568L;
//
// public enum Severity {
// INFO, WARNING, ERROR
// }
//
// public StoredLog() {
// }
//
// @Column(name = "KEY", nullable = true)
// private String key;
//
// @Column(name = "SECONDARY_KEY", nullable = true)
// private String secondaryKey;
//
// @Column(name = "MESSAGE", nullable = true)
// private String message;
//
// @Column(name = "SEVERITY", nullable = true)
// private Severity severity;
//
// @Column(name = "TIMESTAMP", nullable = false)
// @Temporal(value = TemporalType.TIMESTAMP)
// private Date timestamp;
//
// public String getKey() {
// return key;
// }
//
// public void setKey(final String key) {
// this.key = key;
// }
//
// public String getSecondaryKey() {
// return secondaryKey;
// }
//
// public void setSecondaryKey(final String secondaryKey) {
// this.secondaryKey = secondaryKey;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(final String message) {
// this.message = message;
// }
//
// public Severity getSeverity() {
// return severity;
// }
//
// public void setSeverity(final Severity severity) {
// this.severity = severity;
// }
//
// public Date getTimestamp() {
// if (timestamp == null) {
// return null;
// } else {
// return new Date(timestamp.getTime());
// }
// }
//
// public void setTimestamp(final Date timestamp) {
// if (timestamp == null) {
// this.timestamp = new Date();
// } else {
// this.timestamp = new Date(timestamp.getTime());
// }
// }
//
// @Override
// public String toString() {
// final StringBuilder builder = new StringBuilder();
// builder.append("key=");
// builder.append(getKey());
// builder.append(", severity=");
// builder.append(getSeverity());
// builder.append(", message=");
// builder.append(getMessage());
// builder.append(", timestamp=");
// builder.append(getTimestamp());
// return builder.toString();
// }
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/domain/repositories/LogRepository.java
// public interface LogRepository extends CrudRepository<StoredLog, String> {
//
// List<StoredLog> findByKey(String key);
//
// List<StoredLog> findByKeyAndSecondaryKey(String key, String secondaryKey);
//
// void deleteByTimestampBefore(@Temporal(TemporalType.TIMESTAMP) Date date);
//
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/util/Constants.java
// public class Constants {
//
// private Constants() {
// }
//
// public static final String NEXT_CLEANUP_LOGGING_TAG = "NEXT_CLEANUP_LOGGING";
// public static final int CLEANUP_PERIOD_MINUTES = 60;
// public static final int LOG_PERSIST_DAYS = 30;
//
// public static final String QUANTITY_TO_LICENSEE = "quantityToLicensee";
// public static final String ENDPOINT_PATH_CODEGEN = "codegen";
// public static final String ENDPOINT_PATH_LOG = "log";
// public static final String SAVE_USER_DATA = "saveUserData";
//
// public static final class NetLicensing {
// public static final String PRODUCT_NUMBER = "productNumber";
// public static final String LICENSE_TEMPLATE_NUMBER = "licenseTemplateNumber";
// public static final String LICENSEE_NUMBER = "licenseeNumber";
// public static final String LICENSEE_NAME = "name";
// public static final String PROP_MARKED_FOR_TRANSFER = "markedForTransfer";
// public static final String PROP_START_DATE = "startDate";
// }
//
// public static final class Monitoring {
// public static final String ENDPOINT_BASE_PATH = "monitoring";
// }
// }
| import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.labs64.netlicensing.gateway.domain.entity.StoredLog;
import com.labs64.netlicensing.gateway.domain.repositories.LogRepository;
import com.labs64.netlicensing.gateway.util.Constants; | package com.labs64.netlicensing.gateway.bl;
@Component
public class PersistingLogger {
@Autowired
private LogRepository logRepository;
@Autowired
private TimeStampTracker timeStampTracker;
@Transactional(propagation = Propagation.NOT_SUPPORTED) | // Path: src/main/java/com/labs64/netlicensing/gateway/domain/entity/StoredLog.java
// @Entity
// @Table(name = "LOGGING")
// public class StoredLog extends AbstractPersistable<String> {
//
// private static final long serialVersionUID = -8835218729902563568L;
//
// public enum Severity {
// INFO, WARNING, ERROR
// }
//
// public StoredLog() {
// }
//
// @Column(name = "KEY", nullable = true)
// private String key;
//
// @Column(name = "SECONDARY_KEY", nullable = true)
// private String secondaryKey;
//
// @Column(name = "MESSAGE", nullable = true)
// private String message;
//
// @Column(name = "SEVERITY", nullable = true)
// private Severity severity;
//
// @Column(name = "TIMESTAMP", nullable = false)
// @Temporal(value = TemporalType.TIMESTAMP)
// private Date timestamp;
//
// public String getKey() {
// return key;
// }
//
// public void setKey(final String key) {
// this.key = key;
// }
//
// public String getSecondaryKey() {
// return secondaryKey;
// }
//
// public void setSecondaryKey(final String secondaryKey) {
// this.secondaryKey = secondaryKey;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(final String message) {
// this.message = message;
// }
//
// public Severity getSeverity() {
// return severity;
// }
//
// public void setSeverity(final Severity severity) {
// this.severity = severity;
// }
//
// public Date getTimestamp() {
// if (timestamp == null) {
// return null;
// } else {
// return new Date(timestamp.getTime());
// }
// }
//
// public void setTimestamp(final Date timestamp) {
// if (timestamp == null) {
// this.timestamp = new Date();
// } else {
// this.timestamp = new Date(timestamp.getTime());
// }
// }
//
// @Override
// public String toString() {
// final StringBuilder builder = new StringBuilder();
// builder.append("key=");
// builder.append(getKey());
// builder.append(", severity=");
// builder.append(getSeverity());
// builder.append(", message=");
// builder.append(getMessage());
// builder.append(", timestamp=");
// builder.append(getTimestamp());
// return builder.toString();
// }
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/domain/repositories/LogRepository.java
// public interface LogRepository extends CrudRepository<StoredLog, String> {
//
// List<StoredLog> findByKey(String key);
//
// List<StoredLog> findByKeyAndSecondaryKey(String key, String secondaryKey);
//
// void deleteByTimestampBefore(@Temporal(TemporalType.TIMESTAMP) Date date);
//
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/util/Constants.java
// public class Constants {
//
// private Constants() {
// }
//
// public static final String NEXT_CLEANUP_LOGGING_TAG = "NEXT_CLEANUP_LOGGING";
// public static final int CLEANUP_PERIOD_MINUTES = 60;
// public static final int LOG_PERSIST_DAYS = 30;
//
// public static final String QUANTITY_TO_LICENSEE = "quantityToLicensee";
// public static final String ENDPOINT_PATH_CODEGEN = "codegen";
// public static final String ENDPOINT_PATH_LOG = "log";
// public static final String SAVE_USER_DATA = "saveUserData";
//
// public static final class NetLicensing {
// public static final String PRODUCT_NUMBER = "productNumber";
// public static final String LICENSE_TEMPLATE_NUMBER = "licenseTemplateNumber";
// public static final String LICENSEE_NUMBER = "licenseeNumber";
// public static final String LICENSEE_NAME = "name";
// public static final String PROP_MARKED_FOR_TRANSFER = "markedForTransfer";
// public static final String PROP_START_DATE = "startDate";
// }
//
// public static final class Monitoring {
// public static final String ENDPOINT_BASE_PATH = "monitoring";
// }
// }
// Path: src/main/java/com/labs64/netlicensing/gateway/bl/PersistingLogger.java
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.labs64.netlicensing.gateway.domain.entity.StoredLog;
import com.labs64.netlicensing.gateway.domain.repositories.LogRepository;
import com.labs64.netlicensing.gateway.util.Constants;
package com.labs64.netlicensing.gateway.bl;
@Component
public class PersistingLogger {
@Autowired
private LogRepository logRepository;
@Autowired
private TimeStampTracker timeStampTracker;
@Transactional(propagation = Propagation.NOT_SUPPORTED) | public void log(final String key, final String secondaryKey, final StoredLog.Severity severity, final String msg) { |
Labs64/NetLicensing-Gateway | src/main/java/com/labs64/netlicensing/gateway/bl/PersistingLogger.java | // Path: src/main/java/com/labs64/netlicensing/gateway/domain/entity/StoredLog.java
// @Entity
// @Table(name = "LOGGING")
// public class StoredLog extends AbstractPersistable<String> {
//
// private static final long serialVersionUID = -8835218729902563568L;
//
// public enum Severity {
// INFO, WARNING, ERROR
// }
//
// public StoredLog() {
// }
//
// @Column(name = "KEY", nullable = true)
// private String key;
//
// @Column(name = "SECONDARY_KEY", nullable = true)
// private String secondaryKey;
//
// @Column(name = "MESSAGE", nullable = true)
// private String message;
//
// @Column(name = "SEVERITY", nullable = true)
// private Severity severity;
//
// @Column(name = "TIMESTAMP", nullable = false)
// @Temporal(value = TemporalType.TIMESTAMP)
// private Date timestamp;
//
// public String getKey() {
// return key;
// }
//
// public void setKey(final String key) {
// this.key = key;
// }
//
// public String getSecondaryKey() {
// return secondaryKey;
// }
//
// public void setSecondaryKey(final String secondaryKey) {
// this.secondaryKey = secondaryKey;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(final String message) {
// this.message = message;
// }
//
// public Severity getSeverity() {
// return severity;
// }
//
// public void setSeverity(final Severity severity) {
// this.severity = severity;
// }
//
// public Date getTimestamp() {
// if (timestamp == null) {
// return null;
// } else {
// return new Date(timestamp.getTime());
// }
// }
//
// public void setTimestamp(final Date timestamp) {
// if (timestamp == null) {
// this.timestamp = new Date();
// } else {
// this.timestamp = new Date(timestamp.getTime());
// }
// }
//
// @Override
// public String toString() {
// final StringBuilder builder = new StringBuilder();
// builder.append("key=");
// builder.append(getKey());
// builder.append(", severity=");
// builder.append(getSeverity());
// builder.append(", message=");
// builder.append(getMessage());
// builder.append(", timestamp=");
// builder.append(getTimestamp());
// return builder.toString();
// }
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/domain/repositories/LogRepository.java
// public interface LogRepository extends CrudRepository<StoredLog, String> {
//
// List<StoredLog> findByKey(String key);
//
// List<StoredLog> findByKeyAndSecondaryKey(String key, String secondaryKey);
//
// void deleteByTimestampBefore(@Temporal(TemporalType.TIMESTAMP) Date date);
//
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/util/Constants.java
// public class Constants {
//
// private Constants() {
// }
//
// public static final String NEXT_CLEANUP_LOGGING_TAG = "NEXT_CLEANUP_LOGGING";
// public static final int CLEANUP_PERIOD_MINUTES = 60;
// public static final int LOG_PERSIST_DAYS = 30;
//
// public static final String QUANTITY_TO_LICENSEE = "quantityToLicensee";
// public static final String ENDPOINT_PATH_CODEGEN = "codegen";
// public static final String ENDPOINT_PATH_LOG = "log";
// public static final String SAVE_USER_DATA = "saveUserData";
//
// public static final class NetLicensing {
// public static final String PRODUCT_NUMBER = "productNumber";
// public static final String LICENSE_TEMPLATE_NUMBER = "licenseTemplateNumber";
// public static final String LICENSEE_NUMBER = "licenseeNumber";
// public static final String LICENSEE_NAME = "name";
// public static final String PROP_MARKED_FOR_TRANSFER = "markedForTransfer";
// public static final String PROP_START_DATE = "startDate";
// }
//
// public static final class Monitoring {
// public static final String ENDPOINT_BASE_PATH = "monitoring";
// }
// }
| import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.labs64.netlicensing.gateway.domain.entity.StoredLog;
import com.labs64.netlicensing.gateway.domain.repositories.LogRepository;
import com.labs64.netlicensing.gateway.util.Constants; |
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void log(final String key, final String secondaryKey, final StoredLog.Severity severity, final String msg) {
log(key, secondaryKey, severity, msg, null);
}
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void log(final String key, final String secondaryKey, final StoredLog.Severity severity, final String msg,
final Logger logger) {
if (logger != null) {
switch (severity) {
case ERROR:
logger.error(msg);
break;
case WARNING:
logger.warn(msg);
break;
case INFO:
logger.info(msg);
break;
}
}
final StoredLog requestResponse = new StoredLog();
requestResponse.setKey(key);
requestResponse.setSecondaryKey(secondaryKey);
requestResponse.setSeverity(severity);
requestResponse.setMessage(msg);
requestResponse.setTimestamp(new Date());
logRepository.save(requestResponse);
| // Path: src/main/java/com/labs64/netlicensing/gateway/domain/entity/StoredLog.java
// @Entity
// @Table(name = "LOGGING")
// public class StoredLog extends AbstractPersistable<String> {
//
// private static final long serialVersionUID = -8835218729902563568L;
//
// public enum Severity {
// INFO, WARNING, ERROR
// }
//
// public StoredLog() {
// }
//
// @Column(name = "KEY", nullable = true)
// private String key;
//
// @Column(name = "SECONDARY_KEY", nullable = true)
// private String secondaryKey;
//
// @Column(name = "MESSAGE", nullable = true)
// private String message;
//
// @Column(name = "SEVERITY", nullable = true)
// private Severity severity;
//
// @Column(name = "TIMESTAMP", nullable = false)
// @Temporal(value = TemporalType.TIMESTAMP)
// private Date timestamp;
//
// public String getKey() {
// return key;
// }
//
// public void setKey(final String key) {
// this.key = key;
// }
//
// public String getSecondaryKey() {
// return secondaryKey;
// }
//
// public void setSecondaryKey(final String secondaryKey) {
// this.secondaryKey = secondaryKey;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(final String message) {
// this.message = message;
// }
//
// public Severity getSeverity() {
// return severity;
// }
//
// public void setSeverity(final Severity severity) {
// this.severity = severity;
// }
//
// public Date getTimestamp() {
// if (timestamp == null) {
// return null;
// } else {
// return new Date(timestamp.getTime());
// }
// }
//
// public void setTimestamp(final Date timestamp) {
// if (timestamp == null) {
// this.timestamp = new Date();
// } else {
// this.timestamp = new Date(timestamp.getTime());
// }
// }
//
// @Override
// public String toString() {
// final StringBuilder builder = new StringBuilder();
// builder.append("key=");
// builder.append(getKey());
// builder.append(", severity=");
// builder.append(getSeverity());
// builder.append(", message=");
// builder.append(getMessage());
// builder.append(", timestamp=");
// builder.append(getTimestamp());
// return builder.toString();
// }
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/domain/repositories/LogRepository.java
// public interface LogRepository extends CrudRepository<StoredLog, String> {
//
// List<StoredLog> findByKey(String key);
//
// List<StoredLog> findByKeyAndSecondaryKey(String key, String secondaryKey);
//
// void deleteByTimestampBefore(@Temporal(TemporalType.TIMESTAMP) Date date);
//
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/util/Constants.java
// public class Constants {
//
// private Constants() {
// }
//
// public static final String NEXT_CLEANUP_LOGGING_TAG = "NEXT_CLEANUP_LOGGING";
// public static final int CLEANUP_PERIOD_MINUTES = 60;
// public static final int LOG_PERSIST_DAYS = 30;
//
// public static final String QUANTITY_TO_LICENSEE = "quantityToLicensee";
// public static final String ENDPOINT_PATH_CODEGEN = "codegen";
// public static final String ENDPOINT_PATH_LOG = "log";
// public static final String SAVE_USER_DATA = "saveUserData";
//
// public static final class NetLicensing {
// public static final String PRODUCT_NUMBER = "productNumber";
// public static final String LICENSE_TEMPLATE_NUMBER = "licenseTemplateNumber";
// public static final String LICENSEE_NUMBER = "licenseeNumber";
// public static final String LICENSEE_NAME = "name";
// public static final String PROP_MARKED_FOR_TRANSFER = "markedForTransfer";
// public static final String PROP_START_DATE = "startDate";
// }
//
// public static final class Monitoring {
// public static final String ENDPOINT_BASE_PATH = "monitoring";
// }
// }
// Path: src/main/java/com/labs64/netlicensing/gateway/bl/PersistingLogger.java
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.labs64.netlicensing.gateway.domain.entity.StoredLog;
import com.labs64.netlicensing.gateway.domain.repositories.LogRepository;
import com.labs64.netlicensing.gateway.util.Constants;
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void log(final String key, final String secondaryKey, final StoredLog.Severity severity, final String msg) {
log(key, secondaryKey, severity, msg, null);
}
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void log(final String key, final String secondaryKey, final StoredLog.Severity severity, final String msg,
final Logger logger) {
if (logger != null) {
switch (severity) {
case ERROR:
logger.error(msg);
break;
case WARNING:
logger.warn(msg);
break;
case INFO:
logger.info(msg);
break;
}
}
final StoredLog requestResponse = new StoredLog();
requestResponse.setKey(key);
requestResponse.setSecondaryKey(secondaryKey);
requestResponse.setSeverity(severity);
requestResponse.setMessage(msg);
requestResponse.setTimestamp(new Date());
logRepository.save(requestResponse);
| if (timeStampTracker.isExpired(Constants.NEXT_CLEANUP_LOGGING_TAG, Constants.CLEANUP_PERIOD_MINUTES)) { |
Labs64/NetLicensing-Gateway | src/main/java/com/labs64/netlicensing/gateway/bl/TimeStampTracker.java | // Path: src/main/java/com/labs64/netlicensing/gateway/domain/entity/TimeStamp.java
// @Entity
// @Table(name = "TIMESTAMPS")
// public class TimeStamp implements Serializable {
//
// private static final long serialVersionUID = 642517696016632591L;
//
// public TimeStamp() {
// }
//
// public TimeStamp(final String id) {
// this.id = id;
// }
//
// @Id
// private String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(final String id) {
// this.id = id;
// }
//
// @Column(name = "TIMESTAMP", nullable = false)
// @Temporal(value = TemporalType.TIMESTAMP)
// private Date timestamp;
//
// public Date getTimestamp() {
// if (timestamp == null) {
// return null;
// } else {
// return new Date(timestamp.getTime());
// }
// }
//
// public void setTimestamp(final Date timestamp) {
// if (timestamp == null) {
// this.timestamp = new Date();
// } else {
// this.timestamp = new Date(timestamp.getTime());
// }
// }
//
// @Override
// public String toString() {
// final StringBuilder builder = new StringBuilder();
// builder.append("id=");
// builder.append(getId());
// builder.append(", timestamp=");
// builder.append(getTimestamp());
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/domain/repositories/TimeStampRepository.java
// public interface TimeStampRepository extends CrudRepository<TimeStamp, String> {
//
// }
| import java.util.Calendar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.labs64.netlicensing.gateway.domain.entity.TimeStamp;
import com.labs64.netlicensing.gateway.domain.repositories.TimeStampRepository; | package com.labs64.netlicensing.gateway.bl;
@Component
public class TimeStampTracker {
@Autowired | // Path: src/main/java/com/labs64/netlicensing/gateway/domain/entity/TimeStamp.java
// @Entity
// @Table(name = "TIMESTAMPS")
// public class TimeStamp implements Serializable {
//
// private static final long serialVersionUID = 642517696016632591L;
//
// public TimeStamp() {
// }
//
// public TimeStamp(final String id) {
// this.id = id;
// }
//
// @Id
// private String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(final String id) {
// this.id = id;
// }
//
// @Column(name = "TIMESTAMP", nullable = false)
// @Temporal(value = TemporalType.TIMESTAMP)
// private Date timestamp;
//
// public Date getTimestamp() {
// if (timestamp == null) {
// return null;
// } else {
// return new Date(timestamp.getTime());
// }
// }
//
// public void setTimestamp(final Date timestamp) {
// if (timestamp == null) {
// this.timestamp = new Date();
// } else {
// this.timestamp = new Date(timestamp.getTime());
// }
// }
//
// @Override
// public String toString() {
// final StringBuilder builder = new StringBuilder();
// builder.append("id=");
// builder.append(getId());
// builder.append(", timestamp=");
// builder.append(getTimestamp());
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/domain/repositories/TimeStampRepository.java
// public interface TimeStampRepository extends CrudRepository<TimeStamp, String> {
//
// }
// Path: src/main/java/com/labs64/netlicensing/gateway/bl/TimeStampTracker.java
import java.util.Calendar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.labs64.netlicensing.gateway.domain.entity.TimeStamp;
import com.labs64.netlicensing.gateway.domain.repositories.TimeStampRepository;
package com.labs64.netlicensing.gateway.bl;
@Component
public class TimeStampTracker {
@Autowired | private TimeStampRepository timeStampRepository; |
Labs64/NetLicensing-Gateway | src/main/java/com/labs64/netlicensing/gateway/bl/TimeStampTracker.java | // Path: src/main/java/com/labs64/netlicensing/gateway/domain/entity/TimeStamp.java
// @Entity
// @Table(name = "TIMESTAMPS")
// public class TimeStamp implements Serializable {
//
// private static final long serialVersionUID = 642517696016632591L;
//
// public TimeStamp() {
// }
//
// public TimeStamp(final String id) {
// this.id = id;
// }
//
// @Id
// private String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(final String id) {
// this.id = id;
// }
//
// @Column(name = "TIMESTAMP", nullable = false)
// @Temporal(value = TemporalType.TIMESTAMP)
// private Date timestamp;
//
// public Date getTimestamp() {
// if (timestamp == null) {
// return null;
// } else {
// return new Date(timestamp.getTime());
// }
// }
//
// public void setTimestamp(final Date timestamp) {
// if (timestamp == null) {
// this.timestamp = new Date();
// } else {
// this.timestamp = new Date(timestamp.getTime());
// }
// }
//
// @Override
// public String toString() {
// final StringBuilder builder = new StringBuilder();
// builder.append("id=");
// builder.append(getId());
// builder.append(", timestamp=");
// builder.append(getTimestamp());
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/domain/repositories/TimeStampRepository.java
// public interface TimeStampRepository extends CrudRepository<TimeStamp, String> {
//
// }
| import java.util.Calendar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.labs64.netlicensing.gateway.domain.entity.TimeStamp;
import com.labs64.netlicensing.gateway.domain.repositories.TimeStampRepository; | package com.labs64.netlicensing.gateway.bl;
@Component
public class TimeStampTracker {
@Autowired
private TimeStampRepository timeStampRepository;
public boolean isExpired(final String tsTag, final int timeOutMinutes) { | // Path: src/main/java/com/labs64/netlicensing/gateway/domain/entity/TimeStamp.java
// @Entity
// @Table(name = "TIMESTAMPS")
// public class TimeStamp implements Serializable {
//
// private static final long serialVersionUID = 642517696016632591L;
//
// public TimeStamp() {
// }
//
// public TimeStamp(final String id) {
// this.id = id;
// }
//
// @Id
// private String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(final String id) {
// this.id = id;
// }
//
// @Column(name = "TIMESTAMP", nullable = false)
// @Temporal(value = TemporalType.TIMESTAMP)
// private Date timestamp;
//
// public Date getTimestamp() {
// if (timestamp == null) {
// return null;
// } else {
// return new Date(timestamp.getTime());
// }
// }
//
// public void setTimestamp(final Date timestamp) {
// if (timestamp == null) {
// this.timestamp = new Date();
// } else {
// this.timestamp = new Date(timestamp.getTime());
// }
// }
//
// @Override
// public String toString() {
// final StringBuilder builder = new StringBuilder();
// builder.append("id=");
// builder.append(getId());
// builder.append(", timestamp=");
// builder.append(getTimestamp());
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/labs64/netlicensing/gateway/domain/repositories/TimeStampRepository.java
// public interface TimeStampRepository extends CrudRepository<TimeStamp, String> {
//
// }
// Path: src/main/java/com/labs64/netlicensing/gateway/bl/TimeStampTracker.java
import java.util.Calendar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.labs64.netlicensing.gateway.domain.entity.TimeStamp;
import com.labs64.netlicensing.gateway.domain.repositories.TimeStampRepository;
package com.labs64.netlicensing.gateway.bl;
@Component
public class TimeStampTracker {
@Autowired
private TimeStampRepository timeStampRepository;
public boolean isExpired(final String tsTag, final int timeOutMinutes) { | TimeStamp nextCheckTS = timeStampRepository.findById(tsTag).orElse(null); |
Labs64/NetLicensing-Gateway | src/main/java/com/labs64/netlicensing/gateway/controller/restful/AbstractBaseController.java | // Path: src/main/java/com/labs64/netlicensing/gateway/util/security/SecurityHelper.java
// public final class SecurityHelper {
//
// private String nlicBaseUrl;
// private String nlicMonitoringUser;
// private String nlicMonitoringPass;
//
// public static class GWClientConfiguration implements RestProvider.Configuration {
//
// @Override
// public String getUserAgent() {
// return "NetLicensing/Java " + System.getProperty("java.version") + " (Gateway)";
// }
//
// @Override
// public boolean isLoggingEnabled() {
// return false;
// }
//
// }
//
// @Required
// public void setNlicBaseUrl(final String nlicBaseUrl) {
// this.nlicBaseUrl = nlicBaseUrl;
// }
//
// @Required
// public void setNlicMonitoringUser(final String nlicMonitoringUser) {
// this.nlicMonitoringUser = nlicMonitoringUser;
// }
//
// @Required
// public void setNlicMonitoringPass(final String nlicMonitoringPass) {
// this.nlicMonitoringPass = nlicMonitoringPass;
// }
//
// public Context getContext() {
// final Context context = new Context();
// context.setBaseUrl(nlicBaseUrl);
// context.setSecurityMode(SecurityMode.BASIC_AUTHENTICATION);
// context.setObject(RestProvider.Configuration.class, new GWClientConfiguration());
//
// final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// if (authentication != null) {
// if (authentication instanceof AnonymousAuthenticationToken) {
// // TODO(2K): handle missing authentication (no cases so far)
// context.setUsername("");
// context.setPassword("");
// } else {
// context.setUsername(authentication.getPrincipal().toString());
// context.setPassword(authentication.getCredentials().toString());
// }
// }
// return context;
// }
//
// public Context getMonitoringContext() {
// final Context context = new Context();
// context.setBaseUrl(nlicBaseUrl);
// context.setSecurityMode(SecurityMode.BASIC_AUTHENTICATION);
// context.setUsername(nlicMonitoringUser);
// context.setPassword(nlicMonitoringPass);
// context.setObject(RestProvider.Configuration.class, new GWClientConfiguration());
// return context;
// }
//
// public static boolean checkContextConnection(final Context context) {
// try {
// UtilityService.listLicenseTypes(context);
// } catch (NetLicensingException e) {
// return false;
// }
// return true;
// }
//
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import com.labs64.netlicensing.gateway.util.security.SecurityHelper; | package com.labs64.netlicensing.gateway.controller.restful;
public abstract class AbstractBaseController {
@Autowired
private ApplicationContext applicationContext;
@Autowired | // Path: src/main/java/com/labs64/netlicensing/gateway/util/security/SecurityHelper.java
// public final class SecurityHelper {
//
// private String nlicBaseUrl;
// private String nlicMonitoringUser;
// private String nlicMonitoringPass;
//
// public static class GWClientConfiguration implements RestProvider.Configuration {
//
// @Override
// public String getUserAgent() {
// return "NetLicensing/Java " + System.getProperty("java.version") + " (Gateway)";
// }
//
// @Override
// public boolean isLoggingEnabled() {
// return false;
// }
//
// }
//
// @Required
// public void setNlicBaseUrl(final String nlicBaseUrl) {
// this.nlicBaseUrl = nlicBaseUrl;
// }
//
// @Required
// public void setNlicMonitoringUser(final String nlicMonitoringUser) {
// this.nlicMonitoringUser = nlicMonitoringUser;
// }
//
// @Required
// public void setNlicMonitoringPass(final String nlicMonitoringPass) {
// this.nlicMonitoringPass = nlicMonitoringPass;
// }
//
// public Context getContext() {
// final Context context = new Context();
// context.setBaseUrl(nlicBaseUrl);
// context.setSecurityMode(SecurityMode.BASIC_AUTHENTICATION);
// context.setObject(RestProvider.Configuration.class, new GWClientConfiguration());
//
// final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// if (authentication != null) {
// if (authentication instanceof AnonymousAuthenticationToken) {
// // TODO(2K): handle missing authentication (no cases so far)
// context.setUsername("");
// context.setPassword("");
// } else {
// context.setUsername(authentication.getPrincipal().toString());
// context.setPassword(authentication.getCredentials().toString());
// }
// }
// return context;
// }
//
// public Context getMonitoringContext() {
// final Context context = new Context();
// context.setBaseUrl(nlicBaseUrl);
// context.setSecurityMode(SecurityMode.BASIC_AUTHENTICATION);
// context.setUsername(nlicMonitoringUser);
// context.setPassword(nlicMonitoringPass);
// context.setObject(RestProvider.Configuration.class, new GWClientConfiguration());
// return context;
// }
//
// public static boolean checkContextConnection(final Context context) {
// try {
// UtilityService.listLicenseTypes(context);
// } catch (NetLicensingException e) {
// return false;
// }
// return true;
// }
//
// }
// Path: src/main/java/com/labs64/netlicensing/gateway/controller/restful/AbstractBaseController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import com.labs64.netlicensing.gateway.util.security.SecurityHelper;
package com.labs64.netlicensing.gateway.controller.restful;
public abstract class AbstractBaseController {
@Autowired
private ApplicationContext applicationContext;
@Autowired | private SecurityHelper securityHelper; |
nextgis/nextgislogger | app/src/main/java/com/nextgis/logger/util/ApkDownloader.java | // Path: app/src/main/java/com/nextgis/logger/UI/activity/PreferencesActivity.java
// public class PreferencesActivity extends PreferenceActivity implements ServiceConnection {
// private ArduinoEngine mArduinoEngine;
// private AudioEngine mAudioEngine;
//
// @Override
// protected void onCreate(Bundle savedInstance) {
// super.onCreate(savedInstance);
//
// Intent intent = getIntent();
// if (intent != null) {
// String action = intent.getAction();
// if (action != null && action.equalsIgnoreCase(Intent.ACTION_GET_CONTENT)) {
// SimpleFileChooser sfcDialog = new SimpleFileChooser();
//
// sfcDialog.setOnChosenListener(new SimpleFileChooser.SimpleFileChooserListener() {
// String info = getString(R.string.error_no_file);
//
// @Override
// public void onFileChosen(File file) {
// Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("file://" + file.getPath()));
// setResult(Activity.RESULT_OK, result);
// finish();
// }
//
// @Override
// public void onDirectoryChosen(File directory) {
// finishWithError();
// }
//
// @Override
// public void onCancel() {
// finishWithError();
// }
//
// private void finishWithError() {
// Toast.makeText(getApplicationContext(), info, Toast.LENGTH_SHORT).show();
// Intent result = new Intent("com.example.RESULT_ACTION");
// setResult(Activity.RESULT_OK, result);
// finish();
// }
// });
//
// if (getActionBar() != null)
// getActionBar().hide();
//
// getWindow().setBackgroundDrawable(null);
//
// sfcDialog.show(getFragmentManager(), "SimpleFileChooserDialog");
// return;
// }
// }
//
// ProgressBarActivity.startLoggerService(this, null);
// Intent connection = new Intent(this, LoggerService.class);
// bindService(connection, this, 0);
//
// if (getActionBar() != null)
// getActionBar().setDisplayHomeAsUpEnabled(true);
// }
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
// try {
// onServiceDisconnected(null);
// unbindService(this);
// } catch (IllegalArgumentException ignored) {}
// }
//
// public void onBuildHeaders(List<Header> target) {
// loadHeadersFromResource(R.xml.headers, target);
// }
//
// @Override
// protected boolean isValidFragment(String fragmentName) {
// return true;
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case android.R.id.home:
// finish();
// return true;
// default:
// return super.onOptionsItemSelected(item);
// }
// }
//
// @Override
// public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
// mArduinoEngine = ((LoggerService.LocalBinder) iBinder).getArduinoEngine();
// mAudioEngine = ((LoggerService.LocalBinder) iBinder).getSensorEngine().getAudioEngine();
// }
//
// @Override
// public void onServiceDisconnected(ComponentName componentName) {
// mArduinoEngine = null;
// mAudioEngine = null;
// }
//
// public ArduinoEngine getArduinoEngine() {
// return mArduinoEngine;
// }
//
// public AudioEngine getAudioEngine() {
// return mAudioEngine;
// }
//
// @Override
// public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
// switch (requestCode) {
// case ProgressBarActivity.PERMISSION_STORAGE:
// if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
// ApkDownloader.check(this, true);
// break;
// default:
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// }
// }
// }
| import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.widget.Toast;
import com.nextgis.logger.BuildConfig;
import com.nextgis.logger.R;
import com.nextgis.logger.ui.activity.PreferencesActivity;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Locale; | uri = FileProvider.getUriForFile(mActivity, "com.nextgis.logger.file_provider", apk);
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else
uri = Uri.fromFile(apk);
install.setDataAndType(uri, "application/vnd.android.package-archive");
mActivity.startActivity(install);
} else
Toast.makeText(mActivity, result, Toast.LENGTH_LONG).show();
if (mAutoClose)
mActivity.finish();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (mProgress.isIndeterminate()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
mProgress.setProgressNumberFormat(String.format(Locale.getDefault(), "%.2f Mb", values[1] / 1024f));
mProgress.setIndeterminate(false);
mProgress.setMax(values[1]);
}
mProgress.setProgress(values[0]);
}
public static void check(final Activity activity, final boolean showToast) {
final String token = PreferenceManager.getDefaultSharedPreferences(activity).getString(NGIDUtils.PREF_ACCESS_TOKEN, ""); | // Path: app/src/main/java/com/nextgis/logger/UI/activity/PreferencesActivity.java
// public class PreferencesActivity extends PreferenceActivity implements ServiceConnection {
// private ArduinoEngine mArduinoEngine;
// private AudioEngine mAudioEngine;
//
// @Override
// protected void onCreate(Bundle savedInstance) {
// super.onCreate(savedInstance);
//
// Intent intent = getIntent();
// if (intent != null) {
// String action = intent.getAction();
// if (action != null && action.equalsIgnoreCase(Intent.ACTION_GET_CONTENT)) {
// SimpleFileChooser sfcDialog = new SimpleFileChooser();
//
// sfcDialog.setOnChosenListener(new SimpleFileChooser.SimpleFileChooserListener() {
// String info = getString(R.string.error_no_file);
//
// @Override
// public void onFileChosen(File file) {
// Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("file://" + file.getPath()));
// setResult(Activity.RESULT_OK, result);
// finish();
// }
//
// @Override
// public void onDirectoryChosen(File directory) {
// finishWithError();
// }
//
// @Override
// public void onCancel() {
// finishWithError();
// }
//
// private void finishWithError() {
// Toast.makeText(getApplicationContext(), info, Toast.LENGTH_SHORT).show();
// Intent result = new Intent("com.example.RESULT_ACTION");
// setResult(Activity.RESULT_OK, result);
// finish();
// }
// });
//
// if (getActionBar() != null)
// getActionBar().hide();
//
// getWindow().setBackgroundDrawable(null);
//
// sfcDialog.show(getFragmentManager(), "SimpleFileChooserDialog");
// return;
// }
// }
//
// ProgressBarActivity.startLoggerService(this, null);
// Intent connection = new Intent(this, LoggerService.class);
// bindService(connection, this, 0);
//
// if (getActionBar() != null)
// getActionBar().setDisplayHomeAsUpEnabled(true);
// }
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
// try {
// onServiceDisconnected(null);
// unbindService(this);
// } catch (IllegalArgumentException ignored) {}
// }
//
// public void onBuildHeaders(List<Header> target) {
// loadHeadersFromResource(R.xml.headers, target);
// }
//
// @Override
// protected boolean isValidFragment(String fragmentName) {
// return true;
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case android.R.id.home:
// finish();
// return true;
// default:
// return super.onOptionsItemSelected(item);
// }
// }
//
// @Override
// public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
// mArduinoEngine = ((LoggerService.LocalBinder) iBinder).getArduinoEngine();
// mAudioEngine = ((LoggerService.LocalBinder) iBinder).getSensorEngine().getAudioEngine();
// }
//
// @Override
// public void onServiceDisconnected(ComponentName componentName) {
// mArduinoEngine = null;
// mAudioEngine = null;
// }
//
// public ArduinoEngine getArduinoEngine() {
// return mArduinoEngine;
// }
//
// public AudioEngine getAudioEngine() {
// return mAudioEngine;
// }
//
// @Override
// public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
// switch (requestCode) {
// case ProgressBarActivity.PERMISSION_STORAGE:
// if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
// ApkDownloader.check(this, true);
// break;
// default:
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// }
// }
// }
// Path: app/src/main/java/com/nextgis/logger/util/ApkDownloader.java
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.widget.Toast;
import com.nextgis.logger.BuildConfig;
import com.nextgis.logger.R;
import com.nextgis.logger.ui.activity.PreferencesActivity;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Locale;
uri = FileProvider.getUriForFile(mActivity, "com.nextgis.logger.file_provider", apk);
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else
uri = Uri.fromFile(apk);
install.setDataAndType(uri, "application/vnd.android.package-archive");
mActivity.startActivity(install);
} else
Toast.makeText(mActivity, result, Toast.LENGTH_LONG).show();
if (mAutoClose)
mActivity.finish();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (mProgress.isIndeterminate()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
mProgress.setProgressNumberFormat(String.format(Locale.getDefault(), "%.2f Mb", values[1] / 1024f));
mProgress.setIndeterminate(false);
mProgress.setMax(values[1]);
}
mProgress.setProgress(values[0]);
}
public static void check(final Activity activity, final boolean showToast) {
final String token = PreferenceManager.getDefaultSharedPreferences(activity).getString(NGIDUtils.PREF_ACCESS_TOKEN, ""); | final boolean isMultiPane = activity instanceof PreferencesActivity && ((PreferencesActivity) activity).onIsMultiPane(); |
nextgis/nextgislogger | app/src/main/java/com/nextgis/logger/UI/fragment/NGWLoginFragment.java | // Path: app/src/main/java/com/nextgis/logger/util/UiUtil.java
// public final class UiUtil {
// public static int darkerColor(int color, float percent) {
// int r = Color.red(color);
// int b = Color.blue(color);
// int g = Color.green(color);
//
// return Color.rgb((int) (r * percent), (int) (g * percent), (int) (b * percent));
// }
//
// public static boolean isPermissionGranted(Context context, String permission) {
// return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
// }
//
// public static void highlightText(TextView textView) {
// final CharSequence text = textView.getText();
// final SpannableString spannableString = new SpannableString(text);
// spannableString.setSpan(new URLSpan(""), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// textView.setText(spannableString, TextView.BufferType.SPANNABLE);
// }
//
// }
| import android.accounts.Account;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.content.Loader;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.nextgis.logger.R;
import com.nextgis.logger.util.UiUtil;
import com.nextgis.maplib.api.IGISApplication;
import com.nextgis.maplib.api.INGWLayer;
import com.nextgis.maplib.map.MapContentProviderHelper;
import com.nextgis.maplib.util.NGWUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; | mChangeAccountUrl = changeAccountUrl;
}
public void setChangeAccountLogin(boolean changeAccountLogin) {
mChangeAccountLogin = changeAccountLogin;
}
public void setUrlText(String urlText) {
mUrlText = urlText;
}
public void setLoginText(String loginText) {
mLoginText = loginText;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_ngw_login, container, false);
mURL = (EditText) view.findViewById(R.id.url);
mLogin = (EditText) view.findViewById(R.id.login);
mPassword = (EditText) view.findViewById(R.id.password);
mSignInButton = (Button) view.findViewById(R.id.signin);
TextWatcher watcher = new LocalTextWatcher();
mURL.addTextChangedListener(watcher);
mLoginTitle = (TextView) view.findViewById(R.id.login_title);
mTip = (TextView) view.findViewById(R.id.tip);
mManual = (TextView) view.findViewById(R.id.manual);
mManual.setOnClickListener(this); | // Path: app/src/main/java/com/nextgis/logger/util/UiUtil.java
// public final class UiUtil {
// public static int darkerColor(int color, float percent) {
// int r = Color.red(color);
// int b = Color.blue(color);
// int g = Color.green(color);
//
// return Color.rgb((int) (r * percent), (int) (g * percent), (int) (b * percent));
// }
//
// public static boolean isPermissionGranted(Context context, String permission) {
// return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
// }
//
// public static void highlightText(TextView textView) {
// final CharSequence text = textView.getText();
// final SpannableString spannableString = new SpannableString(text);
// spannableString.setSpan(new URLSpan(""), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// textView.setText(spannableString, TextView.BufferType.SPANNABLE);
// }
//
// }
// Path: app/src/main/java/com/nextgis/logger/UI/fragment/NGWLoginFragment.java
import android.accounts.Account;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.content.Loader;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.nextgis.logger.R;
import com.nextgis.logger.util.UiUtil;
import com.nextgis.maplib.api.IGISApplication;
import com.nextgis.maplib.api.INGWLayer;
import com.nextgis.maplib.map.MapContentProviderHelper;
import com.nextgis.maplib.util.NGWUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
mChangeAccountUrl = changeAccountUrl;
}
public void setChangeAccountLogin(boolean changeAccountLogin) {
mChangeAccountLogin = changeAccountLogin;
}
public void setUrlText(String urlText) {
mUrlText = urlText;
}
public void setLoginText(String loginText) {
mLoginText = loginText;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_ngw_login, container, false);
mURL = (EditText) view.findViewById(R.id.url);
mLogin = (EditText) view.findViewById(R.id.login);
mPassword = (EditText) view.findViewById(R.id.password);
mSignInButton = (Button) view.findViewById(R.id.signin);
TextWatcher watcher = new LocalTextWatcher();
mURL.addTextChangedListener(watcher);
mLoginTitle = (TextView) view.findViewById(R.id.login_title);
mTip = (TextView) view.findViewById(R.id.tip);
mManual = (TextView) view.findViewById(R.id.manual);
mManual.setOnClickListener(this); | UiUtil.highlightText(mManual); |
djpowell/lcdjni | java-examples/src/net/djpowell/lcdjni/examples/HelloWorldMono.java | // Path: java/src/net/djpowell/lcdjni/LcdMonoBitmap.java
// public class LcdMonoBitmap implements LcdBitmap {
//
// private LcdDevice device;
// private ByteBuffer buffer;
// private NioMonoImage image;
//
// /**
// * Black on first-gen G15, orange on second-gen G15, and white on G19
// */
// public final Color LIT;
//
// /**
// * White on first-gen G15, dark on second-gen G15, and black on G19
// */
// public final Color UNLIT;
//
// LcdMonoBitmap(LcdDevice device, PixelColor pixelColor) {
// this.device = device;
// this.buffer = Native.makelgLcdBitmapHeader(Native.cLGLCD_BMP_FORMAT_160x43x1);
// this.image = new NioMonoImage(buffer, Native.cPixelsOffset, 160, 43, pixelColor);
// boolean setIsDark = pixelColor.isSetDark();
// LIT = setIsDark ? Color.black : Color.white;
// UNLIT = setIsDark ? Color.white : Color.black;
// }
//
// @Override
// public NioMonoImage getImage() {
// return image;
// }
//
// @Override
// public Graphics getGraphics() {
// return image.getGraphics();
// }
//
// @Override
// public void updateScreen(Priority priority, SyncType syncType) {
// Native.lgLcdUpdateBitmap(device.getDevice(), buffer, priority.getCode() | syncType.getCode());
// }
//
// @Override
// public void close() throws IOException {
// ByteBuffer bb = this.buffer;
// this.device = null;
// this.buffer = null;
// this.image = null;
// Native.freelgLcdBitmapHeader(bb);
// }
//
// }
| import net.djpowell.lcdjni.*;
import net.djpowell.lcdjni.LcdMonoBitmap;
import java.awt.*;
| package net.djpowell.lcdjni.examples;
/**
* Monochrome HelloWorld demo.
*
* @author David Powell
* @since 05-Apr-2010
*/
public class HelloWorldMono {
public static void main(String[] args) throws Exception {
LcdConnection con = new LcdConnection("HelloWorldMono", false, AppletCapability.getCaps(AppletCapability.BW), null, null);
try {
LcdDevice device = con.openDevice(DeviceType.BW, null);
try {
| // Path: java/src/net/djpowell/lcdjni/LcdMonoBitmap.java
// public class LcdMonoBitmap implements LcdBitmap {
//
// private LcdDevice device;
// private ByteBuffer buffer;
// private NioMonoImage image;
//
// /**
// * Black on first-gen G15, orange on second-gen G15, and white on G19
// */
// public final Color LIT;
//
// /**
// * White on first-gen G15, dark on second-gen G15, and black on G19
// */
// public final Color UNLIT;
//
// LcdMonoBitmap(LcdDevice device, PixelColor pixelColor) {
// this.device = device;
// this.buffer = Native.makelgLcdBitmapHeader(Native.cLGLCD_BMP_FORMAT_160x43x1);
// this.image = new NioMonoImage(buffer, Native.cPixelsOffset, 160, 43, pixelColor);
// boolean setIsDark = pixelColor.isSetDark();
// LIT = setIsDark ? Color.black : Color.white;
// UNLIT = setIsDark ? Color.white : Color.black;
// }
//
// @Override
// public NioMonoImage getImage() {
// return image;
// }
//
// @Override
// public Graphics getGraphics() {
// return image.getGraphics();
// }
//
// @Override
// public void updateScreen(Priority priority, SyncType syncType) {
// Native.lgLcdUpdateBitmap(device.getDevice(), buffer, priority.getCode() | syncType.getCode());
// }
//
// @Override
// public void close() throws IOException {
// ByteBuffer bb = this.buffer;
// this.device = null;
// this.buffer = null;
// this.image = null;
// Native.freelgLcdBitmapHeader(bb);
// }
//
// }
// Path: java-examples/src/net/djpowell/lcdjni/examples/HelloWorldMono.java
import net.djpowell.lcdjni.*;
import net.djpowell.lcdjni.LcdMonoBitmap;
import java.awt.*;
package net.djpowell.lcdjni.examples;
/**
* Monochrome HelloWorld demo.
*
* @author David Powell
* @since 05-Apr-2010
*/
public class HelloWorldMono {
public static void main(String[] args) throws Exception {
LcdConnection con = new LcdConnection("HelloWorldMono", false, AppletCapability.getCaps(AppletCapability.BW), null, null);
try {
LcdDevice device = con.openDevice(DeviceType.BW, null);
try {
| LcdMonoBitmap bmp = device.createMonoBitmap(PixelColor.G15_REV_2);
|
djpowell/lcdjni | java/src/net/djpowell/lcdjni/LcdMonoBitmap.java | // Path: java/src/net/djpowell/nioimage/NioMonoImage.java
// public class NioMonoImage extends BufferedImage {
//
// /**
// * Construct a BufferedImage for mono images, backed by a NIO ByteBuffer.
// * @param bb NIO ByteBuffer
// * @param headerLen number of bytes to skip before the image data when writing to the ByteBuffer
// * @param width width of the image in pixels
// * @param height height of the image in pixels
// * @param pixelColor indicates whether set pixels are dark or light
// */
// public NioMonoImage(ByteBuffer bb, int headerLen, int width, int height, PixelColor pixelColor) {
// this(pixelColor.isSetDark() ? new DirectInvertedMonoColorModel() : new DirectMonoColorModel(),
// bb, headerLen, width, height);
// }
//
// /*
// * Helper constructor
// */
// private NioMonoImage(ColorModel cm, ByteBuffer bb, int headerLen, int width, int height) {
// super(cm,
// new NioWritableRaster(
// NioMonoImage.class,
// new SinglePixelPackedSampleModel(
// DataBuffer.TYPE_BYTE,
// width, height,
// new int[] { 0 }),
// new NioDataBuffer(bb, headerLen)
// ),
// false, new Hashtable());
// }
//
// }
| import net.djpowell.nioimage.NioMonoImage;
import java.awt.*;
import java.io.IOException;
import java.nio.ByteBuffer;
| package net.djpowell.lcdjni;
/**
* Monochrome bitmap.
*
* @author David Powell
* @since 05-Apr-2010
*/
public class LcdMonoBitmap implements LcdBitmap {
private LcdDevice device;
private ByteBuffer buffer;
| // Path: java/src/net/djpowell/nioimage/NioMonoImage.java
// public class NioMonoImage extends BufferedImage {
//
// /**
// * Construct a BufferedImage for mono images, backed by a NIO ByteBuffer.
// * @param bb NIO ByteBuffer
// * @param headerLen number of bytes to skip before the image data when writing to the ByteBuffer
// * @param width width of the image in pixels
// * @param height height of the image in pixels
// * @param pixelColor indicates whether set pixels are dark or light
// */
// public NioMonoImage(ByteBuffer bb, int headerLen, int width, int height, PixelColor pixelColor) {
// this(pixelColor.isSetDark() ? new DirectInvertedMonoColorModel() : new DirectMonoColorModel(),
// bb, headerLen, width, height);
// }
//
// /*
// * Helper constructor
// */
// private NioMonoImage(ColorModel cm, ByteBuffer bb, int headerLen, int width, int height) {
// super(cm,
// new NioWritableRaster(
// NioMonoImage.class,
// new SinglePixelPackedSampleModel(
// DataBuffer.TYPE_BYTE,
// width, height,
// new int[] { 0 }),
// new NioDataBuffer(bb, headerLen)
// ),
// false, new Hashtable());
// }
//
// }
// Path: java/src/net/djpowell/lcdjni/LcdMonoBitmap.java
import net.djpowell.nioimage.NioMonoImage;
import java.awt.*;
import java.io.IOException;
import java.nio.ByteBuffer;
package net.djpowell.lcdjni;
/**
* Monochrome bitmap.
*
* @author David Powell
* @since 05-Apr-2010
*/
public class LcdMonoBitmap implements LcdBitmap {
private LcdDevice device;
private ByteBuffer buffer;
| private NioMonoImage image;
|
djpowell/lcdjni | java/src/net/djpowell/lcdjni/LcdRGBABitmap.java | // Path: java/src/net/djpowell/nioimage/NioRGBAImage.java
// public class NioRGBAImage extends BufferedImage {
//
// /**
// * Construct a BufferedImage for RGBA32 images, backed by a NIO ByteBuffer.
// * @param bb NIO ByteBuffer
// * @param headerLen number of bytes to skip before the image data when writing to the ByteBuffer
// * @param width width of the image in pixels
// * @param height height of the image in pixels
// */
// public NioRGBAImage(ByteBuffer bb, int headerLen, int width, int height) {
// this(new DirectRGBAColorModel(), bb, headerLen, width, height);
// }
//
// /*
// * Helper constructor taking ColorModel
// */
// private NioRGBAImage(ColorModel cm, ByteBuffer bb, int headerLen, int width, int height) {
// super(cm,
// new NioWritableRaster(
// NioRGBAImage.class,
// new PixelInterleavedSampleModel(
// DataBuffer.TYPE_BYTE,
// width, height,
// cm.getPixelSize() / 8,
// width * cm.getPixelSize() / 8,
// new int[] { 3, 2, 1, 0 }),
// new NioDataBuffer(bb, headerLen)
// ),
// false, new Hashtable());
// }
//
// }
| import net.djpowell.nioimage.NioRGBAImage;
import java.awt.*;
import java.io.IOException;
import java.nio.ByteBuffer;
| package net.djpowell.lcdjni;
/**
* Color bitmap.
*
* @author David Powell
* @since 05-Apr-2010
*/
public class LcdRGBABitmap implements LcdBitmap {
private LcdDevice device;
private ByteBuffer buffer;
| // Path: java/src/net/djpowell/nioimage/NioRGBAImage.java
// public class NioRGBAImage extends BufferedImage {
//
// /**
// * Construct a BufferedImage for RGBA32 images, backed by a NIO ByteBuffer.
// * @param bb NIO ByteBuffer
// * @param headerLen number of bytes to skip before the image data when writing to the ByteBuffer
// * @param width width of the image in pixels
// * @param height height of the image in pixels
// */
// public NioRGBAImage(ByteBuffer bb, int headerLen, int width, int height) {
// this(new DirectRGBAColorModel(), bb, headerLen, width, height);
// }
//
// /*
// * Helper constructor taking ColorModel
// */
// private NioRGBAImage(ColorModel cm, ByteBuffer bb, int headerLen, int width, int height) {
// super(cm,
// new NioWritableRaster(
// NioRGBAImage.class,
// new PixelInterleavedSampleModel(
// DataBuffer.TYPE_BYTE,
// width, height,
// cm.getPixelSize() / 8,
// width * cm.getPixelSize() / 8,
// new int[] { 3, 2, 1, 0 }),
// new NioDataBuffer(bb, headerLen)
// ),
// false, new Hashtable());
// }
//
// }
// Path: java/src/net/djpowell/lcdjni/LcdRGBABitmap.java
import net.djpowell.nioimage.NioRGBAImage;
import java.awt.*;
import java.io.IOException;
import java.nio.ByteBuffer;
package net.djpowell.lcdjni;
/**
* Color bitmap.
*
* @author David Powell
* @since 05-Apr-2010
*/
public class LcdRGBABitmap implements LcdBitmap {
private LcdDevice device;
private ByteBuffer buffer;
| private NioRGBAImage image;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.