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
projectodd/wunderboss
messaging/src/main/java/org/projectodd/wunderboss/messaging/Queue.java
// Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codec.java // public interface Codec<E,D> { // // E encode(D data); // // D decode(E encoded); // // Class<E> encodesTo(); // // String name(); // // String contentType(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codecs.java // public class Codecs { // // public Codecs add(Codec codec) { // codecs.put(codec.name(), codec); // codecs.put(codec.contentType(), codec); // // return this; // } // // public Codec forName(String name) { // return codecs.get(name); // } // // public Codec forContentType(String contentType) { // return codecs.get(contentType); // } // // public Set<Codec> codecs() { // return Collections.unmodifiableSet(new HashSet<>(codecs.values())); // } // // private final Map<String, Codec> codecs = new HashMap<>(); // }
import org.projectodd.wunderboss.codecs.Codec; import org.projectodd.wunderboss.codecs.Codecs; import java.util.Map;
/* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging; public interface Queue extends Destination { class RespondOption extends ListenOption { public static final RespondOption TTL = opt("ttl", 60000, RespondOption.class); } Listener respond(MessageHandler handler,
// Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codec.java // public interface Codec<E,D> { // // E encode(D data); // // D decode(E encoded); // // Class<E> encodesTo(); // // String name(); // // String contentType(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codecs.java // public class Codecs { // // public Codecs add(Codec codec) { // codecs.put(codec.name(), codec); // codecs.put(codec.contentType(), codec); // // return this; // } // // public Codec forName(String name) { // return codecs.get(name); // } // // public Codec forContentType(String contentType) { // return codecs.get(contentType); // } // // public Set<Codec> codecs() { // return Collections.unmodifiableSet(new HashSet<>(codecs.values())); // } // // private final Map<String, Codec> codecs = new HashMap<>(); // } // Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/Queue.java import org.projectodd.wunderboss.codecs.Codec; import org.projectodd.wunderboss.codecs.Codecs; import java.util.Map; /* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging; public interface Queue extends Destination { class RespondOption extends ListenOption { public static final RespondOption TTL = opt("ttl", 60000, RespondOption.class); } Listener respond(MessageHandler handler,
Codecs codecs,
projectodd/wunderboss
messaging/src/main/java/org/projectodd/wunderboss/messaging/Queue.java
// Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codec.java // public interface Codec<E,D> { // // E encode(D data); // // D decode(E encoded); // // Class<E> encodesTo(); // // String name(); // // String contentType(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codecs.java // public class Codecs { // // public Codecs add(Codec codec) { // codecs.put(codec.name(), codec); // codecs.put(codec.contentType(), codec); // // return this; // } // // public Codec forName(String name) { // return codecs.get(name); // } // // public Codec forContentType(String contentType) { // return codecs.get(contentType); // } // // public Set<Codec> codecs() { // return Collections.unmodifiableSet(new HashSet<>(codecs.values())); // } // // private final Map<String, Codec> codecs = new HashMap<>(); // }
import org.projectodd.wunderboss.codecs.Codec; import org.projectodd.wunderboss.codecs.Codecs; import java.util.Map;
/* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging; public interface Queue extends Destination { class RespondOption extends ListenOption { public static final RespondOption TTL = opt("ttl", 60000, RespondOption.class); } Listener respond(MessageHandler handler, Codecs codecs, Map<ListenOption, Object> options) throws Exception; class RequestOption extends PublishOption {}
// Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codec.java // public interface Codec<E,D> { // // E encode(D data); // // D decode(E encoded); // // Class<E> encodesTo(); // // String name(); // // String contentType(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codecs.java // public class Codecs { // // public Codecs add(Codec codec) { // codecs.put(codec.name(), codec); // codecs.put(codec.contentType(), codec); // // return this; // } // // public Codec forName(String name) { // return codecs.get(name); // } // // public Codec forContentType(String contentType) { // return codecs.get(contentType); // } // // public Set<Codec> codecs() { // return Collections.unmodifiableSet(new HashSet<>(codecs.values())); // } // // private final Map<String, Codec> codecs = new HashMap<>(); // } // Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/Queue.java import org.projectodd.wunderboss.codecs.Codec; import org.projectodd.wunderboss.codecs.Codecs; import java.util.Map; /* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging; public interface Queue extends Destination { class RespondOption extends ListenOption { public static final RespondOption TTL = opt("ttl", 60000, RespondOption.class); } Listener respond(MessageHandler handler, Codecs codecs, Map<ListenOption, Object> options) throws Exception; class RequestOption extends PublishOption {}
Response request(Object content, Codec codec, Codecs codecs,
projectodd/wunderboss
wildfly/singletons/src/main/java/org/projectodd/wunderboss/as/singletons/ImmediateContextProvider.java
// Path: core/src/main/java/org/projectodd/wunderboss/ec/ClusterParticipant.java // public interface ClusterParticipant { // boolean isMaster(); // // void whenMasterAcquired(Runnable r); // // void whenMasterLost(Runnable r); // }
import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceRegistry; import org.jboss.msc.service.ServiceTarget; import org.projectodd.wunderboss.as.ASUtils; import org.projectodd.wunderboss.ec.AlwaysMasterClusterParticipant; import org.projectodd.wunderboss.ec.ClusterParticipant;
/* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.as.singletons; public class ImmediateContextProvider extends org.projectodd.wunderboss.ec.ImmediateContextProvider { public ImmediateContextProvider(final ServiceRegistry registry, final ServiceTarget target) { this.registry = registry; this.target = target; } @Override
// Path: core/src/main/java/org/projectodd/wunderboss/ec/ClusterParticipant.java // public interface ClusterParticipant { // boolean isMaster(); // // void whenMasterAcquired(Runnable r); // // void whenMasterLost(Runnable r); // } // Path: wildfly/singletons/src/main/java/org/projectodd/wunderboss/as/singletons/ImmediateContextProvider.java import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceRegistry; import org.jboss.msc.service.ServiceTarget; import org.projectodd.wunderboss.as.ASUtils; import org.projectodd.wunderboss.ec.AlwaysMasterClusterParticipant; import org.projectodd.wunderboss.ec.ClusterParticipant; /* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.as.singletons; public class ImmediateContextProvider extends org.projectodd.wunderboss.ec.ImmediateContextProvider { public ImmediateContextProvider(final ServiceRegistry registry, final ServiceTarget target) { this.registry = registry; this.target = target; } @Override
protected ClusterParticipant clusterParticipant(final String name, final boolean singleton) {
projectodd/wunderboss
transactions/src/main/java/org/projectodd/wunderboss/transactions/TransactionProvider.java
// Path: core/src/main/java/org/projectodd/wunderboss/Options.java // public class Options<T> extends HashMap<T, Object> { // // public Options() { // this(null); // } // // public Options(Map<T, Object> options) { // if (options != null) { // putAll(options); // } // } // // /** // * Looks up key in the options. // * // * If key is an Option, its default value will be returned if the key // * isn't found. // * // * @param key // * @return // */ // public Object get(Object key) { // Object val = super.get(key); // if (val == null && key instanceof Option) { // val = ((Option)key).defaultValue; // } // // return val; // } // // public Object get(T key, Object defaultValue) { // return get(key) != null ? get(key) : defaultValue; // } // // public Boolean getBoolean(T key) { // return getBoolean(key, null); // } // // public Boolean getBoolean(T key, Boolean defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Boolean)) { // value = Boolean.parseBoolean(value.toString()); // } // // return (Boolean)value; // } // // public Integer getInt(T key) { // return getInt(key, null); // } // // public Integer getInt(T key, Integer defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Integer)) { // value = Integer.parseInt(value.toString()); // } // // return (Integer)value; // } // // public Long getLong(T key) { // return getLong(key, null); // } // // public Long getLong(T key, Long defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Long)) { // value = Long.parseLong(value.toString()); // } // // return (Long)value; // } // // public Double getDouble(T key) { // return getDouble(key, null); // } // // public Double getDouble(T key, Double defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Double)) { // value = Double.parseDouble(value.toString()); // } // // return (Double)value; // } // // public String getString(T key) { // return getString(key, null); // } // // public String getString(T key, String defaultValue) { // return get(key) != null ? get(key).toString() : defaultValue; // } // // public Date getDate(T key) { // return getDate(key, null); // } // // public Date getDate(T key, Date defaultValue) { // return get(key) != null ? (Date)get(key) : defaultValue; // } // // public List getList(T key) { // Object v = get(key); // if (v instanceof List || v == null) { // return (List) v; // } // return Arrays.asList(v); // } // // public Options put(T key, Object value) { // super.put(key, value); // // return this; // } // // /** // * Returns true if key resolves to a *non-null value* (considering // * a possible default), false otherwise. // */ // public boolean has(T key) { // return get(key) != null; // } // // public Options<T> merge(Options<T> otherOptions) { // Options mergedOptions = new Options(); // for (T key : this.keySet()) { // mergedOptions.put(key, this.get(key)); // } // for (T key : otherOptions.keySet()) { // mergedOptions.put(key, otherOptions.get(key)); // } // return mergedOptions; // } // }
import org.projectodd.wunderboss.ComponentProvider; import org.projectodd.wunderboss.Options;
/* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.transactions; public class TransactionProvider implements ComponentProvider<Transaction> { @Override
// Path: core/src/main/java/org/projectodd/wunderboss/Options.java // public class Options<T> extends HashMap<T, Object> { // // public Options() { // this(null); // } // // public Options(Map<T, Object> options) { // if (options != null) { // putAll(options); // } // } // // /** // * Looks up key in the options. // * // * If key is an Option, its default value will be returned if the key // * isn't found. // * // * @param key // * @return // */ // public Object get(Object key) { // Object val = super.get(key); // if (val == null && key instanceof Option) { // val = ((Option)key).defaultValue; // } // // return val; // } // // public Object get(T key, Object defaultValue) { // return get(key) != null ? get(key) : defaultValue; // } // // public Boolean getBoolean(T key) { // return getBoolean(key, null); // } // // public Boolean getBoolean(T key, Boolean defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Boolean)) { // value = Boolean.parseBoolean(value.toString()); // } // // return (Boolean)value; // } // // public Integer getInt(T key) { // return getInt(key, null); // } // // public Integer getInt(T key, Integer defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Integer)) { // value = Integer.parseInt(value.toString()); // } // // return (Integer)value; // } // // public Long getLong(T key) { // return getLong(key, null); // } // // public Long getLong(T key, Long defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Long)) { // value = Long.parseLong(value.toString()); // } // // return (Long)value; // } // // public Double getDouble(T key) { // return getDouble(key, null); // } // // public Double getDouble(T key, Double defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Double)) { // value = Double.parseDouble(value.toString()); // } // // return (Double)value; // } // // public String getString(T key) { // return getString(key, null); // } // // public String getString(T key, String defaultValue) { // return get(key) != null ? get(key).toString() : defaultValue; // } // // public Date getDate(T key) { // return getDate(key, null); // } // // public Date getDate(T key, Date defaultValue) { // return get(key) != null ? (Date)get(key) : defaultValue; // } // // public List getList(T key) { // Object v = get(key); // if (v instanceof List || v == null) { // return (List) v; // } // return Arrays.asList(v); // } // // public Options put(T key, Object value) { // super.put(key, value); // // return this; // } // // /** // * Returns true if key resolves to a *non-null value* (considering // * a possible default), false otherwise. // */ // public boolean has(T key) { // return get(key) != null; // } // // public Options<T> merge(Options<T> otherOptions) { // Options mergedOptions = new Options(); // for (T key : this.keySet()) { // mergedOptions.put(key, this.get(key)); // } // for (T key : otherOptions.keySet()) { // mergedOptions.put(key, otherOptions.get(key)); // } // return mergedOptions; // } // } // Path: transactions/src/main/java/org/projectodd/wunderboss/transactions/TransactionProvider.java import org.projectodd.wunderboss.ComponentProvider; import org.projectodd.wunderboss.Options; /* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.transactions; public class TransactionProvider implements ComponentProvider<Transaction> { @Override
public Transaction create(String name, Options opts) {
projectodd/wunderboss
wildfly/singletons/src/main/java/org/projectodd/wunderboss/as/singletons/DaemonContextProvider.java
// Path: core/src/main/java/org/projectodd/wunderboss/ec/ClusterParticipant.java // public interface ClusterParticipant { // boolean isMaster(); // // void whenMasterAcquired(Runnable r); // // void whenMasterLost(Runnable r); // }
import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceRegistry; import org.jboss.msc.service.ServiceTarget; import org.projectodd.wunderboss.as.ASUtils; import org.projectodd.wunderboss.ec.AlwaysMasterClusterParticipant; import org.projectodd.wunderboss.ec.ClusterParticipant;
/* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.as.singletons; public class DaemonContextProvider extends org.projectodd.wunderboss.ec.DaemonContextProvider { public DaemonContextProvider(final ServiceRegistry registry, final ServiceTarget target) { this.registry = registry; this.target = target; } @Override
// Path: core/src/main/java/org/projectodd/wunderboss/ec/ClusterParticipant.java // public interface ClusterParticipant { // boolean isMaster(); // // void whenMasterAcquired(Runnable r); // // void whenMasterLost(Runnable r); // } // Path: wildfly/singletons/src/main/java/org/projectodd/wunderboss/as/singletons/DaemonContextProvider.java import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceRegistry; import org.jboss.msc.service.ServiceTarget; import org.projectodd.wunderboss.as.ASUtils; import org.projectodd.wunderboss.ec.AlwaysMasterClusterParticipant; import org.projectodd.wunderboss.ec.ClusterParticipant; /* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.as.singletons; public class DaemonContextProvider extends org.projectodd.wunderboss.ec.DaemonContextProvider { public DaemonContextProvider(final ServiceRegistry registry, final ServiceTarget target) { this.registry = registry; this.target = target; } @Override
protected ClusterParticipant clusterParticipant(final String name, final boolean singleton) {
projectodd/wunderboss
caching/src/main/java/org/projectodd/wunderboss/caching/InfinispanCaching.java
// Path: core/src/main/java/org/projectodd/wunderboss/Options.java // public class Options<T> extends HashMap<T, Object> { // // public Options() { // this(null); // } // // public Options(Map<T, Object> options) { // if (options != null) { // putAll(options); // } // } // // /** // * Looks up key in the options. // * // * If key is an Option, its default value will be returned if the key // * isn't found. // * // * @param key // * @return // */ // public Object get(Object key) { // Object val = super.get(key); // if (val == null && key instanceof Option) { // val = ((Option)key).defaultValue; // } // // return val; // } // // public Object get(T key, Object defaultValue) { // return get(key) != null ? get(key) : defaultValue; // } // // public Boolean getBoolean(T key) { // return getBoolean(key, null); // } // // public Boolean getBoolean(T key, Boolean defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Boolean)) { // value = Boolean.parseBoolean(value.toString()); // } // // return (Boolean)value; // } // // public Integer getInt(T key) { // return getInt(key, null); // } // // public Integer getInt(T key, Integer defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Integer)) { // value = Integer.parseInt(value.toString()); // } // // return (Integer)value; // } // // public Long getLong(T key) { // return getLong(key, null); // } // // public Long getLong(T key, Long defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Long)) { // value = Long.parseLong(value.toString()); // } // // return (Long)value; // } // // public Double getDouble(T key) { // return getDouble(key, null); // } // // public Double getDouble(T key, Double defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Double)) { // value = Double.parseDouble(value.toString()); // } // // return (Double)value; // } // // public String getString(T key) { // return getString(key, null); // } // // public String getString(T key, String defaultValue) { // return get(key) != null ? get(key).toString() : defaultValue; // } // // public Date getDate(T key) { // return getDate(key, null); // } // // public Date getDate(T key, Date defaultValue) { // return get(key) != null ? (Date)get(key) : defaultValue; // } // // public List getList(T key) { // Object v = get(key); // if (v instanceof List || v == null) { // return (List) v; // } // return Arrays.asList(v); // } // // public Options put(T key, Object value) { // super.put(key, value); // // return this; // } // // /** // * Returns true if key resolves to a *non-null value* (considering // * a possible default), false otherwise. // */ // public boolean has(T key) { // return get(key) != null; // } // // public Options<T> merge(Options<T> otherOptions) { // Options mergedOptions = new Options(); // for (T key : this.keySet()) { // mergedOptions.put(key, this.get(key)); // } // for (T key : otherOptions.keySet()) { // mergedOptions.put(key, otherOptions.get(key)); // } // return mergedOptions; // } // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codec.java // public interface Codec<E,D> { // // E encode(D data); // // D decode(E encoded); // // Class<E> encodesTo(); // // String name(); // // String contentType(); // }
import org.infinispan.Cache; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.jboss.logging.Logger; import org.projectodd.wunderboss.Options; import org.projectodd.wunderboss.codecs.Codec; import java.util.Map;
Cache result = null; if (manager().isRunning(name)) { result = manager().getCache(name); if (!result.getStatus().allowInvocations()) { result.start(); } } return result; } @Override public Cache findOrCreate(String name, Map<CreateOption,Object> options) { Cache result = find(name); if (result == null) { manager().defineConfiguration(name, Config.uration(validate(options))); log.info("Creating cache: "+name); result = manager().getCache(name); } return result; } @Override public boolean stop(String name) { EmbeddedCacheManager mgr = manager(); boolean before = mgr.isRunning(name); mgr.removeCache(name); return before != mgr.isRunning(name); } @Override
// Path: core/src/main/java/org/projectodd/wunderboss/Options.java // public class Options<T> extends HashMap<T, Object> { // // public Options() { // this(null); // } // // public Options(Map<T, Object> options) { // if (options != null) { // putAll(options); // } // } // // /** // * Looks up key in the options. // * // * If key is an Option, its default value will be returned if the key // * isn't found. // * // * @param key // * @return // */ // public Object get(Object key) { // Object val = super.get(key); // if (val == null && key instanceof Option) { // val = ((Option)key).defaultValue; // } // // return val; // } // // public Object get(T key, Object defaultValue) { // return get(key) != null ? get(key) : defaultValue; // } // // public Boolean getBoolean(T key) { // return getBoolean(key, null); // } // // public Boolean getBoolean(T key, Boolean defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Boolean)) { // value = Boolean.parseBoolean(value.toString()); // } // // return (Boolean)value; // } // // public Integer getInt(T key) { // return getInt(key, null); // } // // public Integer getInt(T key, Integer defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Integer)) { // value = Integer.parseInt(value.toString()); // } // // return (Integer)value; // } // // public Long getLong(T key) { // return getLong(key, null); // } // // public Long getLong(T key, Long defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Long)) { // value = Long.parseLong(value.toString()); // } // // return (Long)value; // } // // public Double getDouble(T key) { // return getDouble(key, null); // } // // public Double getDouble(T key, Double defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Double)) { // value = Double.parseDouble(value.toString()); // } // // return (Double)value; // } // // public String getString(T key) { // return getString(key, null); // } // // public String getString(T key, String defaultValue) { // return get(key) != null ? get(key).toString() : defaultValue; // } // // public Date getDate(T key) { // return getDate(key, null); // } // // public Date getDate(T key, Date defaultValue) { // return get(key) != null ? (Date)get(key) : defaultValue; // } // // public List getList(T key) { // Object v = get(key); // if (v instanceof List || v == null) { // return (List) v; // } // return Arrays.asList(v); // } // // public Options put(T key, Object value) { // super.put(key, value); // // return this; // } // // /** // * Returns true if key resolves to a *non-null value* (considering // * a possible default), false otherwise. // */ // public boolean has(T key) { // return get(key) != null; // } // // public Options<T> merge(Options<T> otherOptions) { // Options mergedOptions = new Options(); // for (T key : this.keySet()) { // mergedOptions.put(key, this.get(key)); // } // for (T key : otherOptions.keySet()) { // mergedOptions.put(key, otherOptions.get(key)); // } // return mergedOptions; // } // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codec.java // public interface Codec<E,D> { // // E encode(D data); // // D decode(E encoded); // // Class<E> encodesTo(); // // String name(); // // String contentType(); // } // Path: caching/src/main/java/org/projectodd/wunderboss/caching/InfinispanCaching.java import org.infinispan.Cache; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.jboss.logging.Logger; import org.projectodd.wunderboss.Options; import org.projectodd.wunderboss.codecs.Codec; import java.util.Map; Cache result = null; if (manager().isRunning(name)) { result = manager().getCache(name); if (!result.getStatus().allowInvocations()) { result.start(); } } return result; } @Override public Cache findOrCreate(String name, Map<CreateOption,Object> options) { Cache result = find(name); if (result == null) { manager().defineConfiguration(name, Config.uration(validate(options))); log.info("Creating cache: "+name); result = manager().getCache(name); } return result; } @Override public boolean stop(String name) { EmbeddedCacheManager mgr = manager(); boolean before = mgr.isRunning(name); mgr.removeCache(name); return before != mgr.isRunning(name); } @Override
public Cache withCodec(Cache cache, Codec codec) {
projectodd/wunderboss
messaging/src/main/java/org/projectodd/wunderboss/messaging/jms/JMSContext.java
// Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/Messaging.java // public interface Messaging extends Component { // // class CreateOption extends Option { // public static final CreateOption HOST = opt("host", CreateOption.class); // public static final CreateOption PORT = opt("port", CreateOption.class); // } // // class CreateQueueOption extends Option { // public static final CreateQueueOption CONTEXT = opt("context", CreateQueueOption.class); // public static final CreateQueueOption DURABLE = opt("durable", true, CreateQueueOption.class); // public static final CreateQueueOption SELECTOR = opt("selector", CreateQueueOption.class); // } // // Queue findOrCreateQueue(String name, // Map<CreateQueueOption, Object> options) throws Exception; // // class CreateTopicOption extends Option { // public static final CreateTopicOption CONTEXT = opt("context", CreateTopicOption.class); // } // // Topic findOrCreateTopic(String name, // Map<CreateTopicOption, Object> options) throws Exception; // // class CreateContextOption extends Option { // public static final CreateContextOption HOST = opt("host", CreateContextOption.class); // public static final CreateContextOption PORT = opt("port", 5445, CreateContextOption.class); // public static final CreateContextOption CLIENT_ID = opt("client_id", CreateContextOption.class); // public static final CreateContextOption USERNAME = opt("username", CreateContextOption.class); // public static final CreateContextOption PASSWORD = opt("password", CreateContextOption.class); // public static final CreateContextOption REMOTE_TYPE = opt("remote_type", CreateContextOption.class); // public static final CreateContextOption MODE = opt("mode", Context.Mode.AUTO_ACK, CreateContextOption.class); // // /** // * If true, an xa Context is returned. // */ // public static final CreateContextOption XA = opt("xa", false, CreateContextOption.class); // // public static final CreateContextOption RECONNECT_RETRY_INTERVAL = // opt("reconnect_retry_interval", 2000, CreateContextOption.class); // public static final CreateContextOption RECONNECT_RETRY_INTERVAL_MULTIPLIER = // opt("reconnect_retry_interval_multiplier", 1.0, CreateContextOption.class); // public static final CreateContextOption RECONNECT_MAX_RETRY_INTERVAL = // opt("reconnect_max_retry_interval", 2000, CreateContextOption.class); // public static final CreateContextOption RECONNECT_ATTEMPTS = // opt("reconnect_attempts", 0, CreateContextOption.class); // } // // Context createContext(Map<CreateContextOption, Object> options) throws Exception; // } // // Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/WithCloseables.java // public class WithCloseables implements HasCloseables { // @Override // public void addCloseable(Object closeable) { // this.closeables.add(closeable); // } // // @Override // public void closeCloseables() throws Exception { // for(Object each: this.closeables) { // if (each instanceof AutoCloseable) { // ((AutoCloseable) each).close(); // } else { // try { // Method close = each.getClass().getMethod("close"); // close.invoke(each); // } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // // throw new RuntimeException("Can't close object of class " + each.getClass().getName(), e); // } // } // } // // this.closeables.clear(); // } // // private final List<Object> closeables = new ArrayList<>(); // }
import org.jboss.logging.Logger; import org.projectodd.wunderboss.messaging.Messaging; import org.projectodd.wunderboss.messaging.WithCloseables; import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.Session; import java.util.UUID; import java.util.concurrent.Callable;
/* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging.jms; public class JMSContext extends WithCloseables implements JMSSpecificContext { public static final ThreadLocal<JMSSpecificContext> currentContext = new ThreadLocal<>(); public JMSContext(final Connection jmsConnection,
// Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/Messaging.java // public interface Messaging extends Component { // // class CreateOption extends Option { // public static final CreateOption HOST = opt("host", CreateOption.class); // public static final CreateOption PORT = opt("port", CreateOption.class); // } // // class CreateQueueOption extends Option { // public static final CreateQueueOption CONTEXT = opt("context", CreateQueueOption.class); // public static final CreateQueueOption DURABLE = opt("durable", true, CreateQueueOption.class); // public static final CreateQueueOption SELECTOR = opt("selector", CreateQueueOption.class); // } // // Queue findOrCreateQueue(String name, // Map<CreateQueueOption, Object> options) throws Exception; // // class CreateTopicOption extends Option { // public static final CreateTopicOption CONTEXT = opt("context", CreateTopicOption.class); // } // // Topic findOrCreateTopic(String name, // Map<CreateTopicOption, Object> options) throws Exception; // // class CreateContextOption extends Option { // public static final CreateContextOption HOST = opt("host", CreateContextOption.class); // public static final CreateContextOption PORT = opt("port", 5445, CreateContextOption.class); // public static final CreateContextOption CLIENT_ID = opt("client_id", CreateContextOption.class); // public static final CreateContextOption USERNAME = opt("username", CreateContextOption.class); // public static final CreateContextOption PASSWORD = opt("password", CreateContextOption.class); // public static final CreateContextOption REMOTE_TYPE = opt("remote_type", CreateContextOption.class); // public static final CreateContextOption MODE = opt("mode", Context.Mode.AUTO_ACK, CreateContextOption.class); // // /** // * If true, an xa Context is returned. // */ // public static final CreateContextOption XA = opt("xa", false, CreateContextOption.class); // // public static final CreateContextOption RECONNECT_RETRY_INTERVAL = // opt("reconnect_retry_interval", 2000, CreateContextOption.class); // public static final CreateContextOption RECONNECT_RETRY_INTERVAL_MULTIPLIER = // opt("reconnect_retry_interval_multiplier", 1.0, CreateContextOption.class); // public static final CreateContextOption RECONNECT_MAX_RETRY_INTERVAL = // opt("reconnect_max_retry_interval", 2000, CreateContextOption.class); // public static final CreateContextOption RECONNECT_ATTEMPTS = // opt("reconnect_attempts", 0, CreateContextOption.class); // } // // Context createContext(Map<CreateContextOption, Object> options) throws Exception; // } // // Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/WithCloseables.java // public class WithCloseables implements HasCloseables { // @Override // public void addCloseable(Object closeable) { // this.closeables.add(closeable); // } // // @Override // public void closeCloseables() throws Exception { // for(Object each: this.closeables) { // if (each instanceof AutoCloseable) { // ((AutoCloseable) each).close(); // } else { // try { // Method close = each.getClass().getMethod("close"); // close.invoke(each); // } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // // throw new RuntimeException("Can't close object of class " + each.getClass().getName(), e); // } // } // } // // this.closeables.clear(); // } // // private final List<Object> closeables = new ArrayList<>(); // } // Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/jms/JMSContext.java import org.jboss.logging.Logger; import org.projectodd.wunderboss.messaging.Messaging; import org.projectodd.wunderboss.messaging.WithCloseables; import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.Session; import java.util.UUID; import java.util.concurrent.Callable; /* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging.jms; public class JMSContext extends WithCloseables implements JMSSpecificContext { public static final ThreadLocal<JMSSpecificContext> currentContext = new ThreadLocal<>(); public JMSContext(final Connection jmsConnection,
final Messaging broker,
projectodd/wunderboss
web/src/main/java/org/projectodd/wunderboss/web/async/websocket/JavaxWebsocketChannel.java
// Path: web/src/main/java/org/projectodd/wunderboss/web/async/WebsocketUtil.java // public class WebsocketUtil { // // // Overcomes the problem of Clojure's reify being incompatible with // // generics and Undertow's dependence on ParameterizedType // static public MessageHandler.Whole<String> createTextHandler(final MessageHandler.Whole proxy) { // return new MessageHandler.Whole<String>() { // public void onMessage(String msg) { // proxy.onMessage(msg); // }}; // } // // // The binary version of createTextHandler // static public MessageHandler.Whole<byte[]> createBinaryHandler(final MessageHandler.Whole proxy) { // return new MessageHandler.Whole<byte[]>() { // public void onMessage(byte[] msg) { // proxy.onMessage(msg); // }}; // } // // static public RuntimeException wrongMessageType(Class clazz) { // return new IllegalArgumentException("message is neither a String or byte[], but is " + // clazz.getName()); // } // // static public void notifyComplete(Channel channel, Channel.OnComplete callback, Throwable error) { // if (callback != null) { // try { // callback.handle(error); // } catch (Exception e) { // channel.notifyError(e); // } // } else if (error != null) { // channel.notifyError(error); // } // } // }
import org.projectodd.wunderboss.web.async.WebsocketUtil; import javax.websocket.CloseReason; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; import javax.websocket.MessageHandler; import javax.websocket.SendHandler; import javax.websocket.SendResult; import javax.websocket.Session; import java.io.IOException; import java.nio.ByteBuffer;
final boolean shouldClose, final OnComplete onComplete) throws Exception { if (!isOpen()) { return false; } SendHandler handler = new SendHandler() { @Override public void onResult(SendResult sendResult) { Throwable ex = sendResult.getException(); if (sendResult.isOK()) { if (shouldClose) { try { close(); } catch (IOException e) { ex = e; } } } notifyComplete(onComplete, ex); } }; if (message == null) { handler.onResult(new SendResult()); } else if (message instanceof String) { this.session.getAsyncRemote().sendText((String)message, handler); } else if (message instanceof byte[]) { this.session.getAsyncRemote().sendBinary(ByteBuffer.wrap((byte[])message), handler); } else {
// Path: web/src/main/java/org/projectodd/wunderboss/web/async/WebsocketUtil.java // public class WebsocketUtil { // // // Overcomes the problem of Clojure's reify being incompatible with // // generics and Undertow's dependence on ParameterizedType // static public MessageHandler.Whole<String> createTextHandler(final MessageHandler.Whole proxy) { // return new MessageHandler.Whole<String>() { // public void onMessage(String msg) { // proxy.onMessage(msg); // }}; // } // // // The binary version of createTextHandler // static public MessageHandler.Whole<byte[]> createBinaryHandler(final MessageHandler.Whole proxy) { // return new MessageHandler.Whole<byte[]>() { // public void onMessage(byte[] msg) { // proxy.onMessage(msg); // }}; // } // // static public RuntimeException wrongMessageType(Class clazz) { // return new IllegalArgumentException("message is neither a String or byte[], but is " + // clazz.getName()); // } // // static public void notifyComplete(Channel channel, Channel.OnComplete callback, Throwable error) { // if (callback != null) { // try { // callback.handle(error); // } catch (Exception e) { // channel.notifyError(e); // } // } else if (error != null) { // channel.notifyError(error); // } // } // } // Path: web/src/main/java/org/projectodd/wunderboss/web/async/websocket/JavaxWebsocketChannel.java import org.projectodd.wunderboss.web.async.WebsocketUtil; import javax.websocket.CloseReason; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; import javax.websocket.MessageHandler; import javax.websocket.SendHandler; import javax.websocket.SendResult; import javax.websocket.Session; import java.io.IOException; import java.nio.ByteBuffer; final boolean shouldClose, final OnComplete onComplete) throws Exception { if (!isOpen()) { return false; } SendHandler handler = new SendHandler() { @Override public void onResult(SendResult sendResult) { Throwable ex = sendResult.getException(); if (sendResult.isOK()) { if (shouldClose) { try { close(); } catch (IOException e) { ex = e; } } } notifyComplete(onComplete, ex); } }; if (message == null) { handler.onResult(new SendResult()); } else if (message instanceof String) { this.session.getAsyncRemote().sendText((String)message, handler); } else if (message instanceof byte[]) { this.session.getAsyncRemote().sendBinary(ByteBuffer.wrap((byte[])message), handler); } else {
throw WebsocketUtil.wrongMessageType(message.getClass());
projectodd/wunderboss
wildfly/core/src/main/java/org/projectodd/wunderboss/as/web/ServletWebProvider.java
// Path: core/src/main/java/org/projectodd/wunderboss/Options.java // public class Options<T> extends HashMap<T, Object> { // // public Options() { // this(null); // } // // public Options(Map<T, Object> options) { // if (options != null) { // putAll(options); // } // } // // /** // * Looks up key in the options. // * // * If key is an Option, its default value will be returned if the key // * isn't found. // * // * @param key // * @return // */ // public Object get(Object key) { // Object val = super.get(key); // if (val == null && key instanceof Option) { // val = ((Option)key).defaultValue; // } // // return val; // } // // public Object get(T key, Object defaultValue) { // return get(key) != null ? get(key) : defaultValue; // } // // public Boolean getBoolean(T key) { // return getBoolean(key, null); // } // // public Boolean getBoolean(T key, Boolean defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Boolean)) { // value = Boolean.parseBoolean(value.toString()); // } // // return (Boolean)value; // } // // public Integer getInt(T key) { // return getInt(key, null); // } // // public Integer getInt(T key, Integer defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Integer)) { // value = Integer.parseInt(value.toString()); // } // // return (Integer)value; // } // // public Long getLong(T key) { // return getLong(key, null); // } // // public Long getLong(T key, Long defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Long)) { // value = Long.parseLong(value.toString()); // } // // return (Long)value; // } // // public Double getDouble(T key) { // return getDouble(key, null); // } // // public Double getDouble(T key, Double defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Double)) { // value = Double.parseDouble(value.toString()); // } // // return (Double)value; // } // // public String getString(T key) { // return getString(key, null); // } // // public String getString(T key, String defaultValue) { // return get(key) != null ? get(key).toString() : defaultValue; // } // // public Date getDate(T key) { // return getDate(key, null); // } // // public Date getDate(T key, Date defaultValue) { // return get(key) != null ? (Date)get(key) : defaultValue; // } // // public List getList(T key) { // Object v = get(key); // if (v instanceof List || v == null) { // return (List) v; // } // return Arrays.asList(v); // } // // public Options put(T key, Object value) { // super.put(key, value); // // return this; // } // // /** // * Returns true if key resolves to a *non-null value* (considering // * a possible default), false otherwise. // */ // public boolean has(T key) { // return get(key) != null; // } // // public Options<T> merge(Options<T> otherOptions) { // Options mergedOptions = new Options(); // for (T key : this.keySet()) { // mergedOptions.put(key, this.get(key)); // } // for (T key : otherOptions.keySet()) { // mergedOptions.put(key, otherOptions.get(key)); // } // return mergedOptions; // } // } // // Path: wildfly/core/src/main/java/org/projectodd/wunderboss/as/ActionConduit.java // public class ActionConduit { // public synchronized void close() { // if (!queue.isEmpty()) { // throw new RuntimeException("Can't close non-empty conduit"); // } // this.open = false; // } // // public synchronized boolean add(Runnable action) { // if (!isOpen()) { // // return false; // } // // this.queue.add(action); // // return true; // } // // public synchronized Runnable poll() { // return this.queue.poll(); // } // // public synchronized boolean isOpen() { // return this.open; // } // // private final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(); // private boolean open = true; // }
import org.projectodd.wunderboss.ComponentProvider; import org.projectodd.wunderboss.Options; import org.projectodd.wunderboss.as.ActionConduit; import org.projectodd.wunderboss.as.web.ServletWeb; import org.projectodd.wunderboss.web.Web; import javax.servlet.ServletContext; import java.util.concurrent.atomic.AtomicLong;
/* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.as.web; public class ServletWebProvider implements ComponentProvider<Web> { public ServletWebProvider(ServletContext servletContext, ActionConduit actionConduit, AtomicLong sharedTimeout) { this.servletContext = servletContext; this.actionConduit = actionConduit; this.sharedTimeout = sharedTimeout; } @Override
// Path: core/src/main/java/org/projectodd/wunderboss/Options.java // public class Options<T> extends HashMap<T, Object> { // // public Options() { // this(null); // } // // public Options(Map<T, Object> options) { // if (options != null) { // putAll(options); // } // } // // /** // * Looks up key in the options. // * // * If key is an Option, its default value will be returned if the key // * isn't found. // * // * @param key // * @return // */ // public Object get(Object key) { // Object val = super.get(key); // if (val == null && key instanceof Option) { // val = ((Option)key).defaultValue; // } // // return val; // } // // public Object get(T key, Object defaultValue) { // return get(key) != null ? get(key) : defaultValue; // } // // public Boolean getBoolean(T key) { // return getBoolean(key, null); // } // // public Boolean getBoolean(T key, Boolean defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Boolean)) { // value = Boolean.parseBoolean(value.toString()); // } // // return (Boolean)value; // } // // public Integer getInt(T key) { // return getInt(key, null); // } // // public Integer getInt(T key, Integer defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Integer)) { // value = Integer.parseInt(value.toString()); // } // // return (Integer)value; // } // // public Long getLong(T key) { // return getLong(key, null); // } // // public Long getLong(T key, Long defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Long)) { // value = Long.parseLong(value.toString()); // } // // return (Long)value; // } // // public Double getDouble(T key) { // return getDouble(key, null); // } // // public Double getDouble(T key, Double defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Double)) { // value = Double.parseDouble(value.toString()); // } // // return (Double)value; // } // // public String getString(T key) { // return getString(key, null); // } // // public String getString(T key, String defaultValue) { // return get(key) != null ? get(key).toString() : defaultValue; // } // // public Date getDate(T key) { // return getDate(key, null); // } // // public Date getDate(T key, Date defaultValue) { // return get(key) != null ? (Date)get(key) : defaultValue; // } // // public List getList(T key) { // Object v = get(key); // if (v instanceof List || v == null) { // return (List) v; // } // return Arrays.asList(v); // } // // public Options put(T key, Object value) { // super.put(key, value); // // return this; // } // // /** // * Returns true if key resolves to a *non-null value* (considering // * a possible default), false otherwise. // */ // public boolean has(T key) { // return get(key) != null; // } // // public Options<T> merge(Options<T> otherOptions) { // Options mergedOptions = new Options(); // for (T key : this.keySet()) { // mergedOptions.put(key, this.get(key)); // } // for (T key : otherOptions.keySet()) { // mergedOptions.put(key, otherOptions.get(key)); // } // return mergedOptions; // } // } // // Path: wildfly/core/src/main/java/org/projectodd/wunderboss/as/ActionConduit.java // public class ActionConduit { // public synchronized void close() { // if (!queue.isEmpty()) { // throw new RuntimeException("Can't close non-empty conduit"); // } // this.open = false; // } // // public synchronized boolean add(Runnable action) { // if (!isOpen()) { // // return false; // } // // this.queue.add(action); // // return true; // } // // public synchronized Runnable poll() { // return this.queue.poll(); // } // // public synchronized boolean isOpen() { // return this.open; // } // // private final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(); // private boolean open = true; // } // Path: wildfly/core/src/main/java/org/projectodd/wunderboss/as/web/ServletWebProvider.java import org.projectodd.wunderboss.ComponentProvider; import org.projectodd.wunderboss.Options; import org.projectodd.wunderboss.as.ActionConduit; import org.projectodd.wunderboss.as.web.ServletWeb; import org.projectodd.wunderboss.web.Web; import javax.servlet.ServletContext; import java.util.concurrent.atomic.AtomicLong; /* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.as.web; public class ServletWebProvider implements ComponentProvider<Web> { public ServletWebProvider(ServletContext servletContext, ActionConduit actionConduit, AtomicLong sharedTimeout) { this.servletContext = servletContext; this.actionConduit = actionConduit; this.sharedTimeout = sharedTimeout; } @Override
public Web create(String name, Options ignored) {
projectodd/wunderboss
messaging/src/main/java/org/projectodd/wunderboss/messaging/jms/JMSSpecificContext.java
// Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/Context.java // public interface Context extends AutoCloseable, HasCloseables { // // String id(); // // public enum Mode { AUTO_ACK, CLIENT_ACK, TRANSACTED } // // Mode mode(); // // void commit(); // // void rollback(); // // void acknowledge(); // // boolean enlist() throws Exception; // // boolean isRemote(); // } // // Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/Messaging.java // public interface Messaging extends Component { // // class CreateOption extends Option { // public static final CreateOption HOST = opt("host", CreateOption.class); // public static final CreateOption PORT = opt("port", CreateOption.class); // } // // class CreateQueueOption extends Option { // public static final CreateQueueOption CONTEXT = opt("context", CreateQueueOption.class); // public static final CreateQueueOption DURABLE = opt("durable", true, CreateQueueOption.class); // public static final CreateQueueOption SELECTOR = opt("selector", CreateQueueOption.class); // } // // Queue findOrCreateQueue(String name, // Map<CreateQueueOption, Object> options) throws Exception; // // class CreateTopicOption extends Option { // public static final CreateTopicOption CONTEXT = opt("context", CreateTopicOption.class); // } // // Topic findOrCreateTopic(String name, // Map<CreateTopicOption, Object> options) throws Exception; // // class CreateContextOption extends Option { // public static final CreateContextOption HOST = opt("host", CreateContextOption.class); // public static final CreateContextOption PORT = opt("port", 5445, CreateContextOption.class); // public static final CreateContextOption CLIENT_ID = opt("client_id", CreateContextOption.class); // public static final CreateContextOption USERNAME = opt("username", CreateContextOption.class); // public static final CreateContextOption PASSWORD = opt("password", CreateContextOption.class); // public static final CreateContextOption REMOTE_TYPE = opt("remote_type", CreateContextOption.class); // public static final CreateContextOption MODE = opt("mode", Context.Mode.AUTO_ACK, CreateContextOption.class); // // /** // * If true, an xa Context is returned. // */ // public static final CreateContextOption XA = opt("xa", false, CreateContextOption.class); // // public static final CreateContextOption RECONNECT_RETRY_INTERVAL = // opt("reconnect_retry_interval", 2000, CreateContextOption.class); // public static final CreateContextOption RECONNECT_RETRY_INTERVAL_MULTIPLIER = // opt("reconnect_retry_interval_multiplier", 1.0, CreateContextOption.class); // public static final CreateContextOption RECONNECT_MAX_RETRY_INTERVAL = // opt("reconnect_max_retry_interval", 2000, CreateContextOption.class); // public static final CreateContextOption RECONNECT_ATTEMPTS = // opt("reconnect_attempts", 0, CreateContextOption.class); // } // // Context createContext(Map<CreateContextOption, Object> options) throws Exception; // }
import org.projectodd.wunderboss.messaging.Context; import org.projectodd.wunderboss.messaging.Messaging; import javax.jms.Connection; import javax.jms.Session;
/* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging.jms; public interface JMSSpecificContext extends Context { String id(); Connection jmsConnection(); Session jmsSession();
// Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/Context.java // public interface Context extends AutoCloseable, HasCloseables { // // String id(); // // public enum Mode { AUTO_ACK, CLIENT_ACK, TRANSACTED } // // Mode mode(); // // void commit(); // // void rollback(); // // void acknowledge(); // // boolean enlist() throws Exception; // // boolean isRemote(); // } // // Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/Messaging.java // public interface Messaging extends Component { // // class CreateOption extends Option { // public static final CreateOption HOST = opt("host", CreateOption.class); // public static final CreateOption PORT = opt("port", CreateOption.class); // } // // class CreateQueueOption extends Option { // public static final CreateQueueOption CONTEXT = opt("context", CreateQueueOption.class); // public static final CreateQueueOption DURABLE = opt("durable", true, CreateQueueOption.class); // public static final CreateQueueOption SELECTOR = opt("selector", CreateQueueOption.class); // } // // Queue findOrCreateQueue(String name, // Map<CreateQueueOption, Object> options) throws Exception; // // class CreateTopicOption extends Option { // public static final CreateTopicOption CONTEXT = opt("context", CreateTopicOption.class); // } // // Topic findOrCreateTopic(String name, // Map<CreateTopicOption, Object> options) throws Exception; // // class CreateContextOption extends Option { // public static final CreateContextOption HOST = opt("host", CreateContextOption.class); // public static final CreateContextOption PORT = opt("port", 5445, CreateContextOption.class); // public static final CreateContextOption CLIENT_ID = opt("client_id", CreateContextOption.class); // public static final CreateContextOption USERNAME = opt("username", CreateContextOption.class); // public static final CreateContextOption PASSWORD = opt("password", CreateContextOption.class); // public static final CreateContextOption REMOTE_TYPE = opt("remote_type", CreateContextOption.class); // public static final CreateContextOption MODE = opt("mode", Context.Mode.AUTO_ACK, CreateContextOption.class); // // /** // * If true, an xa Context is returned. // */ // public static final CreateContextOption XA = opt("xa", false, CreateContextOption.class); // // public static final CreateContextOption RECONNECT_RETRY_INTERVAL = // opt("reconnect_retry_interval", 2000, CreateContextOption.class); // public static final CreateContextOption RECONNECT_RETRY_INTERVAL_MULTIPLIER = // opt("reconnect_retry_interval_multiplier", 1.0, CreateContextOption.class); // public static final CreateContextOption RECONNECT_MAX_RETRY_INTERVAL = // opt("reconnect_max_retry_interval", 2000, CreateContextOption.class); // public static final CreateContextOption RECONNECT_ATTEMPTS = // opt("reconnect_attempts", 0, CreateContextOption.class); // } // // Context createContext(Map<CreateContextOption, Object> options) throws Exception; // } // Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/jms/JMSSpecificContext.java import org.projectodd.wunderboss.messaging.Context; import org.projectodd.wunderboss.messaging.Messaging; import javax.jms.Connection; import javax.jms.Session; /* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging.jms; public interface JMSSpecificContext extends Context { String id(); Connection jmsConnection(); Session jmsSession();
Messaging broker();
projectodd/wunderboss
web-undertow/src/main/java/org/projectodd/wunderboss/web/undertow/UndertowWebProvider.java
// Path: core/src/main/java/org/projectodd/wunderboss/Options.java // public class Options<T> extends HashMap<T, Object> { // // public Options() { // this(null); // } // // public Options(Map<T, Object> options) { // if (options != null) { // putAll(options); // } // } // // /** // * Looks up key in the options. // * // * If key is an Option, its default value will be returned if the key // * isn't found. // * // * @param key // * @return // */ // public Object get(Object key) { // Object val = super.get(key); // if (val == null && key instanceof Option) { // val = ((Option)key).defaultValue; // } // // return val; // } // // public Object get(T key, Object defaultValue) { // return get(key) != null ? get(key) : defaultValue; // } // // public Boolean getBoolean(T key) { // return getBoolean(key, null); // } // // public Boolean getBoolean(T key, Boolean defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Boolean)) { // value = Boolean.parseBoolean(value.toString()); // } // // return (Boolean)value; // } // // public Integer getInt(T key) { // return getInt(key, null); // } // // public Integer getInt(T key, Integer defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Integer)) { // value = Integer.parseInt(value.toString()); // } // // return (Integer)value; // } // // public Long getLong(T key) { // return getLong(key, null); // } // // public Long getLong(T key, Long defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Long)) { // value = Long.parseLong(value.toString()); // } // // return (Long)value; // } // // public Double getDouble(T key) { // return getDouble(key, null); // } // // public Double getDouble(T key, Double defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Double)) { // value = Double.parseDouble(value.toString()); // } // // return (Double)value; // } // // public String getString(T key) { // return getString(key, null); // } // // public String getString(T key, String defaultValue) { // return get(key) != null ? get(key).toString() : defaultValue; // } // // public Date getDate(T key) { // return getDate(key, null); // } // // public Date getDate(T key, Date defaultValue) { // return get(key) != null ? (Date)get(key) : defaultValue; // } // // public List getList(T key) { // Object v = get(key); // if (v instanceof List || v == null) { // return (List) v; // } // return Arrays.asList(v); // } // // public Options put(T key, Object value) { // super.put(key, value); // // return this; // } // // /** // * Returns true if key resolves to a *non-null value* (considering // * a possible default), false otherwise. // */ // public boolean has(T key) { // return get(key) != null; // } // // public Options<T> merge(Options<T> otherOptions) { // Options mergedOptions = new Options(); // for (T key : this.keySet()) { // mergedOptions.put(key, this.get(key)); // } // for (T key : otherOptions.keySet()) { // mergedOptions.put(key, otherOptions.get(key)); // } // return mergedOptions; // } // }
import org.projectodd.wunderboss.ComponentProvider; import org.projectodd.wunderboss.Options; import org.projectodd.wunderboss.web.Web;
/* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.web.undertow; public class UndertowWebProvider implements ComponentProvider<Web> { @Override
// Path: core/src/main/java/org/projectodd/wunderboss/Options.java // public class Options<T> extends HashMap<T, Object> { // // public Options() { // this(null); // } // // public Options(Map<T, Object> options) { // if (options != null) { // putAll(options); // } // } // // /** // * Looks up key in the options. // * // * If key is an Option, its default value will be returned if the key // * isn't found. // * // * @param key // * @return // */ // public Object get(Object key) { // Object val = super.get(key); // if (val == null && key instanceof Option) { // val = ((Option)key).defaultValue; // } // // return val; // } // // public Object get(T key, Object defaultValue) { // return get(key) != null ? get(key) : defaultValue; // } // // public Boolean getBoolean(T key) { // return getBoolean(key, null); // } // // public Boolean getBoolean(T key, Boolean defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Boolean)) { // value = Boolean.parseBoolean(value.toString()); // } // // return (Boolean)value; // } // // public Integer getInt(T key) { // return getInt(key, null); // } // // public Integer getInt(T key, Integer defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Integer)) { // value = Integer.parseInt(value.toString()); // } // // return (Integer)value; // } // // public Long getLong(T key) { // return getLong(key, null); // } // // public Long getLong(T key, Long defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Long)) { // value = Long.parseLong(value.toString()); // } // // return (Long)value; // } // // public Double getDouble(T key) { // return getDouble(key, null); // } // // public Double getDouble(T key, Double defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Double)) { // value = Double.parseDouble(value.toString()); // } // // return (Double)value; // } // // public String getString(T key) { // return getString(key, null); // } // // public String getString(T key, String defaultValue) { // return get(key) != null ? get(key).toString() : defaultValue; // } // // public Date getDate(T key) { // return getDate(key, null); // } // // public Date getDate(T key, Date defaultValue) { // return get(key) != null ? (Date)get(key) : defaultValue; // } // // public List getList(T key) { // Object v = get(key); // if (v instanceof List || v == null) { // return (List) v; // } // return Arrays.asList(v); // } // // public Options put(T key, Object value) { // super.put(key, value); // // return this; // } // // /** // * Returns true if key resolves to a *non-null value* (considering // * a possible default), false otherwise. // */ // public boolean has(T key) { // return get(key) != null; // } // // public Options<T> merge(Options<T> otherOptions) { // Options mergedOptions = new Options(); // for (T key : this.keySet()) { // mergedOptions.put(key, this.get(key)); // } // for (T key : otherOptions.keySet()) { // mergedOptions.put(key, otherOptions.get(key)); // } // return mergedOptions; // } // } // Path: web-undertow/src/main/java/org/projectodd/wunderboss/web/undertow/UndertowWebProvider.java import org.projectodd.wunderboss.ComponentProvider; import org.projectodd.wunderboss.Options; import org.projectodd.wunderboss.web.Web; /* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.web.undertow; public class UndertowWebProvider implements ComponentProvider<Web> { @Override
public Web create(String name, Options opts) {
projectodd/wunderboss
messaging/src/main/java/org/projectodd/wunderboss/messaging/Destination.java
// Path: core/src/main/java/org/projectodd/wunderboss/Option.java // public class Option { // // public String name; // public Object defaultValue; // // public Option() {} // // public String toString() { // return "[" + this.getClass().getName() + ": " + name + ", default = " + defaultValue + "]"; // } // // public static <T extends Option> T opt(String name, Class T) { // return opt(name, null, T); // } // // public static <T extends Option> T opt(String name, Object defaultValue, Class T) { // T opt = null; // try { // opt = (T)T.newInstance(); // opt.name = name; // opt.defaultValue = defaultValue; // rememberOption(opt); // } catch (InstantiationException | IllegalAccessException e) { // e.printStackTrace(); // } // // return opt; // } // // public static Set<Option> optsFor(Class clazz) { // Set<Option> opts = new HashSet<>(); // while(Option.class.isAssignableFrom(clazz)) { // if (knownOptions.containsKey(clazz)) { // opts.addAll(knownOptions.get(clazz)); // } // clazz = clazz.getSuperclass(); // } // // return opts; // } // // private static void rememberOption(Option opt) { // Set<Option> opts = knownOptions.get(opt.getClass()); // if (opts == null) { // opts = new HashSet<>(); // knownOptions.put(opt.getClass(), opts); // } // opts.add(opt); // } // // private static final Map<Class, Set<Option>> knownOptions = new HashMap<>(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codec.java // public interface Codec<E,D> { // // E encode(D data); // // D decode(E encoded); // // Class<E> encodesTo(); // // String name(); // // String contentType(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codecs.java // public class Codecs { // // public Codecs add(Codec codec) { // codecs.put(codec.name(), codec); // codecs.put(codec.contentType(), codec); // // return this; // } // // public Codec forName(String name) { // return codecs.get(name); // } // // public Codec forContentType(String contentType) { // return codecs.get(contentType); // } // // public Set<Codec> codecs() { // return Collections.unmodifiableSet(new HashSet<>(codecs.values())); // } // // private final Map<String, Codec> codecs = new HashMap<>(); // }
import org.projectodd.wunderboss.Option; import org.projectodd.wunderboss.codecs.Codec; import org.projectodd.wunderboss.codecs.Codecs; import java.util.Map;
/* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging; public interface Destination extends HasCloseables { String name();
// Path: core/src/main/java/org/projectodd/wunderboss/Option.java // public class Option { // // public String name; // public Object defaultValue; // // public Option() {} // // public String toString() { // return "[" + this.getClass().getName() + ": " + name + ", default = " + defaultValue + "]"; // } // // public static <T extends Option> T opt(String name, Class T) { // return opt(name, null, T); // } // // public static <T extends Option> T opt(String name, Object defaultValue, Class T) { // T opt = null; // try { // opt = (T)T.newInstance(); // opt.name = name; // opt.defaultValue = defaultValue; // rememberOption(opt); // } catch (InstantiationException | IllegalAccessException e) { // e.printStackTrace(); // } // // return opt; // } // // public static Set<Option> optsFor(Class clazz) { // Set<Option> opts = new HashSet<>(); // while(Option.class.isAssignableFrom(clazz)) { // if (knownOptions.containsKey(clazz)) { // opts.addAll(knownOptions.get(clazz)); // } // clazz = clazz.getSuperclass(); // } // // return opts; // } // // private static void rememberOption(Option opt) { // Set<Option> opts = knownOptions.get(opt.getClass()); // if (opts == null) { // opts = new HashSet<>(); // knownOptions.put(opt.getClass(), opts); // } // opts.add(opt); // } // // private static final Map<Class, Set<Option>> knownOptions = new HashMap<>(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codec.java // public interface Codec<E,D> { // // E encode(D data); // // D decode(E encoded); // // Class<E> encodesTo(); // // String name(); // // String contentType(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codecs.java // public class Codecs { // // public Codecs add(Codec codec) { // codecs.put(codec.name(), codec); // codecs.put(codec.contentType(), codec); // // return this; // } // // public Codec forName(String name) { // return codecs.get(name); // } // // public Codec forContentType(String contentType) { // return codecs.get(contentType); // } // // public Set<Codec> codecs() { // return Collections.unmodifiableSet(new HashSet<>(codecs.values())); // } // // private final Map<String, Codec> codecs = new HashMap<>(); // } // Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/Destination.java import org.projectodd.wunderboss.Option; import org.projectodd.wunderboss.codecs.Codec; import org.projectodd.wunderboss.codecs.Codecs; import java.util.Map; /* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging; public interface Destination extends HasCloseables { String name();
class ListenOption extends Option {
projectodd/wunderboss
messaging/src/main/java/org/projectodd/wunderboss/messaging/Destination.java
// Path: core/src/main/java/org/projectodd/wunderboss/Option.java // public class Option { // // public String name; // public Object defaultValue; // // public Option() {} // // public String toString() { // return "[" + this.getClass().getName() + ": " + name + ", default = " + defaultValue + "]"; // } // // public static <T extends Option> T opt(String name, Class T) { // return opt(name, null, T); // } // // public static <T extends Option> T opt(String name, Object defaultValue, Class T) { // T opt = null; // try { // opt = (T)T.newInstance(); // opt.name = name; // opt.defaultValue = defaultValue; // rememberOption(opt); // } catch (InstantiationException | IllegalAccessException e) { // e.printStackTrace(); // } // // return opt; // } // // public static Set<Option> optsFor(Class clazz) { // Set<Option> opts = new HashSet<>(); // while(Option.class.isAssignableFrom(clazz)) { // if (knownOptions.containsKey(clazz)) { // opts.addAll(knownOptions.get(clazz)); // } // clazz = clazz.getSuperclass(); // } // // return opts; // } // // private static void rememberOption(Option opt) { // Set<Option> opts = knownOptions.get(opt.getClass()); // if (opts == null) { // opts = new HashSet<>(); // knownOptions.put(opt.getClass(), opts); // } // opts.add(opt); // } // // private static final Map<Class, Set<Option>> knownOptions = new HashMap<>(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codec.java // public interface Codec<E,D> { // // E encode(D data); // // D decode(E encoded); // // Class<E> encodesTo(); // // String name(); // // String contentType(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codecs.java // public class Codecs { // // public Codecs add(Codec codec) { // codecs.put(codec.name(), codec); // codecs.put(codec.contentType(), codec); // // return this; // } // // public Codec forName(String name) { // return codecs.get(name); // } // // public Codec forContentType(String contentType) { // return codecs.get(contentType); // } // // public Set<Codec> codecs() { // return Collections.unmodifiableSet(new HashSet<>(codecs.values())); // } // // private final Map<String, Codec> codecs = new HashMap<>(); // }
import org.projectodd.wunderboss.Option; import org.projectodd.wunderboss.codecs.Codec; import org.projectodd.wunderboss.codecs.Codecs; import java.util.Map;
/* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging; public interface Destination extends HasCloseables { String name(); class ListenOption extends Option { public static final ListenOption CONTEXT = opt("context", ListenOption.class); public static final ListenOption CONCURRENCY = opt("concurrency", ListenOption.class); public static final ListenOption SELECTOR = opt("selector", ListenOption.class); public static final ListenOption MODE = opt("mode", Context.Mode.TRANSACTED, ListenOption.class); } Listener listen(MessageHandler handler,
// Path: core/src/main/java/org/projectodd/wunderboss/Option.java // public class Option { // // public String name; // public Object defaultValue; // // public Option() {} // // public String toString() { // return "[" + this.getClass().getName() + ": " + name + ", default = " + defaultValue + "]"; // } // // public static <T extends Option> T opt(String name, Class T) { // return opt(name, null, T); // } // // public static <T extends Option> T opt(String name, Object defaultValue, Class T) { // T opt = null; // try { // opt = (T)T.newInstance(); // opt.name = name; // opt.defaultValue = defaultValue; // rememberOption(opt); // } catch (InstantiationException | IllegalAccessException e) { // e.printStackTrace(); // } // // return opt; // } // // public static Set<Option> optsFor(Class clazz) { // Set<Option> opts = new HashSet<>(); // while(Option.class.isAssignableFrom(clazz)) { // if (knownOptions.containsKey(clazz)) { // opts.addAll(knownOptions.get(clazz)); // } // clazz = clazz.getSuperclass(); // } // // return opts; // } // // private static void rememberOption(Option opt) { // Set<Option> opts = knownOptions.get(opt.getClass()); // if (opts == null) { // opts = new HashSet<>(); // knownOptions.put(opt.getClass(), opts); // } // opts.add(opt); // } // // private static final Map<Class, Set<Option>> knownOptions = new HashMap<>(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codec.java // public interface Codec<E,D> { // // E encode(D data); // // D decode(E encoded); // // Class<E> encodesTo(); // // String name(); // // String contentType(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codecs.java // public class Codecs { // // public Codecs add(Codec codec) { // codecs.put(codec.name(), codec); // codecs.put(codec.contentType(), codec); // // return this; // } // // public Codec forName(String name) { // return codecs.get(name); // } // // public Codec forContentType(String contentType) { // return codecs.get(contentType); // } // // public Set<Codec> codecs() { // return Collections.unmodifiableSet(new HashSet<>(codecs.values())); // } // // private final Map<String, Codec> codecs = new HashMap<>(); // } // Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/Destination.java import org.projectodd.wunderboss.Option; import org.projectodd.wunderboss.codecs.Codec; import org.projectodd.wunderboss.codecs.Codecs; import java.util.Map; /* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging; public interface Destination extends HasCloseables { String name(); class ListenOption extends Option { public static final ListenOption CONTEXT = opt("context", ListenOption.class); public static final ListenOption CONCURRENCY = opt("concurrency", ListenOption.class); public static final ListenOption SELECTOR = opt("selector", ListenOption.class); public static final ListenOption MODE = opt("mode", Context.Mode.TRANSACTED, ListenOption.class); } Listener listen(MessageHandler handler,
Codecs codecs,
projectodd/wunderboss
messaging/src/main/java/org/projectodd/wunderboss/messaging/Destination.java
// Path: core/src/main/java/org/projectodd/wunderboss/Option.java // public class Option { // // public String name; // public Object defaultValue; // // public Option() {} // // public String toString() { // return "[" + this.getClass().getName() + ": " + name + ", default = " + defaultValue + "]"; // } // // public static <T extends Option> T opt(String name, Class T) { // return opt(name, null, T); // } // // public static <T extends Option> T opt(String name, Object defaultValue, Class T) { // T opt = null; // try { // opt = (T)T.newInstance(); // opt.name = name; // opt.defaultValue = defaultValue; // rememberOption(opt); // } catch (InstantiationException | IllegalAccessException e) { // e.printStackTrace(); // } // // return opt; // } // // public static Set<Option> optsFor(Class clazz) { // Set<Option> opts = new HashSet<>(); // while(Option.class.isAssignableFrom(clazz)) { // if (knownOptions.containsKey(clazz)) { // opts.addAll(knownOptions.get(clazz)); // } // clazz = clazz.getSuperclass(); // } // // return opts; // } // // private static void rememberOption(Option opt) { // Set<Option> opts = knownOptions.get(opt.getClass()); // if (opts == null) { // opts = new HashSet<>(); // knownOptions.put(opt.getClass(), opts); // } // opts.add(opt); // } // // private static final Map<Class, Set<Option>> knownOptions = new HashMap<>(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codec.java // public interface Codec<E,D> { // // E encode(D data); // // D decode(E encoded); // // Class<E> encodesTo(); // // String name(); // // String contentType(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codecs.java // public class Codecs { // // public Codecs add(Codec codec) { // codecs.put(codec.name(), codec); // codecs.put(codec.contentType(), codec); // // return this; // } // // public Codec forName(String name) { // return codecs.get(name); // } // // public Codec forContentType(String contentType) { // return codecs.get(contentType); // } // // public Set<Codec> codecs() { // return Collections.unmodifiableSet(new HashSet<>(codecs.values())); // } // // private final Map<String, Codec> codecs = new HashMap<>(); // }
import org.projectodd.wunderboss.Option; import org.projectodd.wunderboss.codecs.Codec; import org.projectodd.wunderboss.codecs.Codecs; import java.util.Map;
/* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging; public interface Destination extends HasCloseables { String name(); class ListenOption extends Option { public static final ListenOption CONTEXT = opt("context", ListenOption.class); public static final ListenOption CONCURRENCY = opt("concurrency", ListenOption.class); public static final ListenOption SELECTOR = opt("selector", ListenOption.class); public static final ListenOption MODE = opt("mode", Context.Mode.TRANSACTED, ListenOption.class); } Listener listen(MessageHandler handler, Codecs codecs, Map<ListenOption, Object> options) throws Exception; class MessageOpOption extends Option { public static final MessageOpOption CONTEXT = opt("context", MessageOpOption.class); } class PublishOption extends MessageOpOption { public static final PublishOption PRIORITY = opt("priority", 4, PublishOption.class); //TODO: 4 is JMS specific? public static final PublishOption TTL = opt("ttl", 0, PublishOption.class); public static final PublishOption PERSISTENT = opt("persistent", true, PublishOption.class); public static final PublishOption PROPERTIES = opt("properties", PublishOption.class); }
// Path: core/src/main/java/org/projectodd/wunderboss/Option.java // public class Option { // // public String name; // public Object defaultValue; // // public Option() {} // // public String toString() { // return "[" + this.getClass().getName() + ": " + name + ", default = " + defaultValue + "]"; // } // // public static <T extends Option> T opt(String name, Class T) { // return opt(name, null, T); // } // // public static <T extends Option> T opt(String name, Object defaultValue, Class T) { // T opt = null; // try { // opt = (T)T.newInstance(); // opt.name = name; // opt.defaultValue = defaultValue; // rememberOption(opt); // } catch (InstantiationException | IllegalAccessException e) { // e.printStackTrace(); // } // // return opt; // } // // public static Set<Option> optsFor(Class clazz) { // Set<Option> opts = new HashSet<>(); // while(Option.class.isAssignableFrom(clazz)) { // if (knownOptions.containsKey(clazz)) { // opts.addAll(knownOptions.get(clazz)); // } // clazz = clazz.getSuperclass(); // } // // return opts; // } // // private static void rememberOption(Option opt) { // Set<Option> opts = knownOptions.get(opt.getClass()); // if (opts == null) { // opts = new HashSet<>(); // knownOptions.put(opt.getClass(), opts); // } // opts.add(opt); // } // // private static final Map<Class, Set<Option>> knownOptions = new HashMap<>(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codec.java // public interface Codec<E,D> { // // E encode(D data); // // D decode(E encoded); // // Class<E> encodesTo(); // // String name(); // // String contentType(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codecs.java // public class Codecs { // // public Codecs add(Codec codec) { // codecs.put(codec.name(), codec); // codecs.put(codec.contentType(), codec); // // return this; // } // // public Codec forName(String name) { // return codecs.get(name); // } // // public Codec forContentType(String contentType) { // return codecs.get(contentType); // } // // public Set<Codec> codecs() { // return Collections.unmodifiableSet(new HashSet<>(codecs.values())); // } // // private final Map<String, Codec> codecs = new HashMap<>(); // } // Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/Destination.java import org.projectodd.wunderboss.Option; import org.projectodd.wunderboss.codecs.Codec; import org.projectodd.wunderboss.codecs.Codecs; import java.util.Map; /* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging; public interface Destination extends HasCloseables { String name(); class ListenOption extends Option { public static final ListenOption CONTEXT = opt("context", ListenOption.class); public static final ListenOption CONCURRENCY = opt("concurrency", ListenOption.class); public static final ListenOption SELECTOR = opt("selector", ListenOption.class); public static final ListenOption MODE = opt("mode", Context.Mode.TRANSACTED, ListenOption.class); } Listener listen(MessageHandler handler, Codecs codecs, Map<ListenOption, Object> options) throws Exception; class MessageOpOption extends Option { public static final MessageOpOption CONTEXT = opt("context", MessageOpOption.class); } class PublishOption extends MessageOpOption { public static final PublishOption PRIORITY = opt("priority", 4, PublishOption.class); //TODO: 4 is JMS specific? public static final PublishOption TTL = opt("ttl", 0, PublishOption.class); public static final PublishOption PERSISTENT = opt("persistent", true, PublishOption.class); public static final PublishOption PROPERTIES = opt("properties", PublishOption.class); }
void publish(Object content, Codec codec, Map<MessageOpOption, Object> options) throws Exception;
projectodd/wunderboss
web-undertow/src/main/java/org/projectodd/wunderboss/web/undertow/async/websocket/UndertowWebsocket.java
// Path: web-undertow/src/main/java/org/projectodd/wunderboss/web/undertow/AttachableHttpHandler.java // public abstract class AttachableHttpHandler extends AbstractAttachable implements HttpHandler { // // }
import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.ResponseCodeHandler; import io.undertow.util.AttachmentKey; import io.undertow.util.HeaderValues; import io.undertow.util.Headers; import io.undertow.websockets.WebSocketConnectionCallback; import io.undertow.websockets.WebSocketProtocolHandshakeHandler; import io.undertow.websockets.core.AbstractReceiveListener; import io.undertow.websockets.core.BufferedBinaryMessage; import io.undertow.websockets.core.BufferedTextMessage; import io.undertow.websockets.core.CloseMessage; import io.undertow.websockets.core.WebSocketChannel; import io.undertow.websockets.spi.WebSocketHttpExchange; import org.projectodd.wunderboss.web.undertow.AttachableHttpHandler; import org.xnio.Buffers; import org.xnio.ChannelListener; import org.xnio.Pooled; import java.io.IOException; import java.nio.ByteBuffer;
protected void onCloseMessage (CloseMessage message, WebSocketChannel channel) { endpoint.onClose(channel, message); } protected void onFullTextMessage (WebSocketChannel channel, BufferedTextMessage message) { endpoint.onMessage(channel, message.getData()); } protected void onFullBinaryMessage (WebSocketChannel channel, BufferedBinaryMessage message) { Pooled<ByteBuffer[]> pooled = message.getData(); try { ByteBuffer[] payload = pooled.getResource(); endpoint.onMessage(channel, toArray(payload)); } finally { pooled.free(); } } }); channel.resumeReceives(); } else { try { channel.close(); } catch (IOException e) { throw new RuntimeException("Error closing websocket", e); } } } }; final HttpHandler downstream = next==null ? ResponseCodeHandler.HANDLE_404 : next; final WebSocketProtocolHandshakeHandler wsHandler = new WebSocketProtocolHandshakeHandler(callback, downstream);
// Path: web-undertow/src/main/java/org/projectodd/wunderboss/web/undertow/AttachableHttpHandler.java // public abstract class AttachableHttpHandler extends AbstractAttachable implements HttpHandler { // // } // Path: web-undertow/src/main/java/org/projectodd/wunderboss/web/undertow/async/websocket/UndertowWebsocket.java import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.ResponseCodeHandler; import io.undertow.util.AttachmentKey; import io.undertow.util.HeaderValues; import io.undertow.util.Headers; import io.undertow.websockets.WebSocketConnectionCallback; import io.undertow.websockets.WebSocketProtocolHandshakeHandler; import io.undertow.websockets.core.AbstractReceiveListener; import io.undertow.websockets.core.BufferedBinaryMessage; import io.undertow.websockets.core.BufferedTextMessage; import io.undertow.websockets.core.CloseMessage; import io.undertow.websockets.core.WebSocketChannel; import io.undertow.websockets.spi.WebSocketHttpExchange; import org.projectodd.wunderboss.web.undertow.AttachableHttpHandler; import org.xnio.Buffers; import org.xnio.ChannelListener; import org.xnio.Pooled; import java.io.IOException; import java.nio.ByteBuffer; protected void onCloseMessage (CloseMessage message, WebSocketChannel channel) { endpoint.onClose(channel, message); } protected void onFullTextMessage (WebSocketChannel channel, BufferedTextMessage message) { endpoint.onMessage(channel, message.getData()); } protected void onFullBinaryMessage (WebSocketChannel channel, BufferedBinaryMessage message) { Pooled<ByteBuffer[]> pooled = message.getData(); try { ByteBuffer[] payload = pooled.getResource(); endpoint.onMessage(channel, toArray(payload)); } finally { pooled.free(); } } }); channel.resumeReceives(); } else { try { channel.close(); } catch (IOException e) { throw new RuntimeException("Error closing websocket", e); } } } }; final HttpHandler downstream = next==null ? ResponseCodeHandler.HANDLE_404 : next; final WebSocketProtocolHandshakeHandler wsHandler = new WebSocketProtocolHandshakeHandler(callback, downstream);
final AttachableHttpHandler handler = new AttachableHttpHandler() {
projectodd/wunderboss
core/src/main/java/org/projectodd/wunderboss/ec/DaemonContextProvider.java
// Path: core/src/main/java/org/projectodd/wunderboss/Options.java // public class Options<T> extends HashMap<T, Object> { // // public Options() { // this(null); // } // // public Options(Map<T, Object> options) { // if (options != null) { // putAll(options); // } // } // // /** // * Looks up key in the options. // * // * If key is an Option, its default value will be returned if the key // * isn't found. // * // * @param key // * @return // */ // public Object get(Object key) { // Object val = super.get(key); // if (val == null && key instanceof Option) { // val = ((Option)key).defaultValue; // } // // return val; // } // // public Object get(T key, Object defaultValue) { // return get(key) != null ? get(key) : defaultValue; // } // // public Boolean getBoolean(T key) { // return getBoolean(key, null); // } // // public Boolean getBoolean(T key, Boolean defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Boolean)) { // value = Boolean.parseBoolean(value.toString()); // } // // return (Boolean)value; // } // // public Integer getInt(T key) { // return getInt(key, null); // } // // public Integer getInt(T key, Integer defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Integer)) { // value = Integer.parseInt(value.toString()); // } // // return (Integer)value; // } // // public Long getLong(T key) { // return getLong(key, null); // } // // public Long getLong(T key, Long defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Long)) { // value = Long.parseLong(value.toString()); // } // // return (Long)value; // } // // public Double getDouble(T key) { // return getDouble(key, null); // } // // public Double getDouble(T key, Double defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Double)) { // value = Double.parseDouble(value.toString()); // } // // return (Double)value; // } // // public String getString(T key) { // return getString(key, null); // } // // public String getString(T key, String defaultValue) { // return get(key) != null ? get(key).toString() : defaultValue; // } // // public Date getDate(T key) { // return getDate(key, null); // } // // public Date getDate(T key, Date defaultValue) { // return get(key) != null ? (Date)get(key) : defaultValue; // } // // public List getList(T key) { // Object v = get(key); // if (v instanceof List || v == null) { // return (List) v; // } // return Arrays.asList(v); // } // // public Options put(T key, Object value) { // super.put(key, value); // // return this; // } // // /** // * Returns true if key resolves to a *non-null value* (considering // * a possible default), false otherwise. // */ // public boolean has(T key) { // return get(key) != null; // } // // public Options<T> merge(Options<T> otherOptions) { // Options mergedOptions = new Options(); // for (T key : this.keySet()) { // mergedOptions.put(key, this.get(key)); // } // for (T key : otherOptions.keySet()) { // mergedOptions.put(key, otherOptions.get(key)); // } // return mergedOptions; // } // }
import org.projectodd.wunderboss.ComponentProvider; import org.projectodd.wunderboss.Options;
/* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.ec; public class DaemonContextProvider extends ExecutionContextProvider implements ComponentProvider<DaemonContext> { @Override
// Path: core/src/main/java/org/projectodd/wunderboss/Options.java // public class Options<T> extends HashMap<T, Object> { // // public Options() { // this(null); // } // // public Options(Map<T, Object> options) { // if (options != null) { // putAll(options); // } // } // // /** // * Looks up key in the options. // * // * If key is an Option, its default value will be returned if the key // * isn't found. // * // * @param key // * @return // */ // public Object get(Object key) { // Object val = super.get(key); // if (val == null && key instanceof Option) { // val = ((Option)key).defaultValue; // } // // return val; // } // // public Object get(T key, Object defaultValue) { // return get(key) != null ? get(key) : defaultValue; // } // // public Boolean getBoolean(T key) { // return getBoolean(key, null); // } // // public Boolean getBoolean(T key, Boolean defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Boolean)) { // value = Boolean.parseBoolean(value.toString()); // } // // return (Boolean)value; // } // // public Integer getInt(T key) { // return getInt(key, null); // } // // public Integer getInt(T key, Integer defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Integer)) { // value = Integer.parseInt(value.toString()); // } // // return (Integer)value; // } // // public Long getLong(T key) { // return getLong(key, null); // } // // public Long getLong(T key, Long defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Long)) { // value = Long.parseLong(value.toString()); // } // // return (Long)value; // } // // public Double getDouble(T key) { // return getDouble(key, null); // } // // public Double getDouble(T key, Double defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Double)) { // value = Double.parseDouble(value.toString()); // } // // return (Double)value; // } // // public String getString(T key) { // return getString(key, null); // } // // public String getString(T key, String defaultValue) { // return get(key) != null ? get(key).toString() : defaultValue; // } // // public Date getDate(T key) { // return getDate(key, null); // } // // public Date getDate(T key, Date defaultValue) { // return get(key) != null ? (Date)get(key) : defaultValue; // } // // public List getList(T key) { // Object v = get(key); // if (v instanceof List || v == null) { // return (List) v; // } // return Arrays.asList(v); // } // // public Options put(T key, Object value) { // super.put(key, value); // // return this; // } // // /** // * Returns true if key resolves to a *non-null value* (considering // * a possible default), false otherwise. // */ // public boolean has(T key) { // return get(key) != null; // } // // public Options<T> merge(Options<T> otherOptions) { // Options mergedOptions = new Options(); // for (T key : this.keySet()) { // mergedOptions.put(key, this.get(key)); // } // for (T key : otherOptions.keySet()) { // mergedOptions.put(key, otherOptions.get(key)); // } // return mergedOptions; // } // } // Path: core/src/main/java/org/projectodd/wunderboss/ec/DaemonContextProvider.java import org.projectodd.wunderboss.ComponentProvider; import org.projectodd.wunderboss.Options; /* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.ec; public class DaemonContextProvider extends ExecutionContextProvider implements ComponentProvider<DaemonContext> { @Override
public DaemonContext create(final String name, final Options options) {
projectodd/wunderboss
messaging/src/main/java/org/projectodd/wunderboss/messaging/Topic.java
// Path: core/src/main/java/org/projectodd/wunderboss/Option.java // public class Option { // // public String name; // public Object defaultValue; // // public Option() {} // // public String toString() { // return "[" + this.getClass().getName() + ": " + name + ", default = " + defaultValue + "]"; // } // // public static <T extends Option> T opt(String name, Class T) { // return opt(name, null, T); // } // // public static <T extends Option> T opt(String name, Object defaultValue, Class T) { // T opt = null; // try { // opt = (T)T.newInstance(); // opt.name = name; // opt.defaultValue = defaultValue; // rememberOption(opt); // } catch (InstantiationException | IllegalAccessException e) { // e.printStackTrace(); // } // // return opt; // } // // public static Set<Option> optsFor(Class clazz) { // Set<Option> opts = new HashSet<>(); // while(Option.class.isAssignableFrom(clazz)) { // if (knownOptions.containsKey(clazz)) { // opts.addAll(knownOptions.get(clazz)); // } // clazz = clazz.getSuperclass(); // } // // return opts; // } // // private static void rememberOption(Option opt) { // Set<Option> opts = knownOptions.get(opt.getClass()); // if (opts == null) { // opts = new HashSet<>(); // knownOptions.put(opt.getClass(), opts); // } // opts.add(opt); // } // // private static final Map<Class, Set<Option>> knownOptions = new HashMap<>(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codecs.java // public class Codecs { // // public Codecs add(Codec codec) { // codecs.put(codec.name(), codec); // codecs.put(codec.contentType(), codec); // // return this; // } // // public Codec forName(String name) { // return codecs.get(name); // } // // public Codec forContentType(String contentType) { // return codecs.get(contentType); // } // // public Set<Codec> codecs() { // return Collections.unmodifiableSet(new HashSet<>(codecs.values())); // } // // private final Map<String, Codec> codecs = new HashMap<>(); // }
import org.projectodd.wunderboss.Option; import org.projectodd.wunderboss.codecs.Codecs; import java.util.Map;
/* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging; public interface Topic extends Destination { class SubscribeOption extends Option { public static final SubscribeOption CONTEXT = opt("context", SubscribeOption.class); public static final SubscribeOption SELECTOR = opt("selector", SubscribeOption.class); public static final SubscribeOption TRANSACTED = opt("transacted", true, SubscribeOption.class); } Listener subscribe(String id, MessageHandler handler,
// Path: core/src/main/java/org/projectodd/wunderboss/Option.java // public class Option { // // public String name; // public Object defaultValue; // // public Option() {} // // public String toString() { // return "[" + this.getClass().getName() + ": " + name + ", default = " + defaultValue + "]"; // } // // public static <T extends Option> T opt(String name, Class T) { // return opt(name, null, T); // } // // public static <T extends Option> T opt(String name, Object defaultValue, Class T) { // T opt = null; // try { // opt = (T)T.newInstance(); // opt.name = name; // opt.defaultValue = defaultValue; // rememberOption(opt); // } catch (InstantiationException | IllegalAccessException e) { // e.printStackTrace(); // } // // return opt; // } // // public static Set<Option> optsFor(Class clazz) { // Set<Option> opts = new HashSet<>(); // while(Option.class.isAssignableFrom(clazz)) { // if (knownOptions.containsKey(clazz)) { // opts.addAll(knownOptions.get(clazz)); // } // clazz = clazz.getSuperclass(); // } // // return opts; // } // // private static void rememberOption(Option opt) { // Set<Option> opts = knownOptions.get(opt.getClass()); // if (opts == null) { // opts = new HashSet<>(); // knownOptions.put(opt.getClass(), opts); // } // opts.add(opt); // } // // private static final Map<Class, Set<Option>> knownOptions = new HashMap<>(); // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codecs.java // public class Codecs { // // public Codecs add(Codec codec) { // codecs.put(codec.name(), codec); // codecs.put(codec.contentType(), codec); // // return this; // } // // public Codec forName(String name) { // return codecs.get(name); // } // // public Codec forContentType(String contentType) { // return codecs.get(contentType); // } // // public Set<Codec> codecs() { // return Collections.unmodifiableSet(new HashSet<>(codecs.values())); // } // // private final Map<String, Codec> codecs = new HashMap<>(); // } // Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/Topic.java import org.projectodd.wunderboss.Option; import org.projectodd.wunderboss.codecs.Codecs; import java.util.Map; /* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging; public interface Topic extends Destination { class SubscribeOption extends Option { public static final SubscribeOption CONTEXT = opt("context", SubscribeOption.class); public static final SubscribeOption SELECTOR = opt("selector", SubscribeOption.class); public static final SubscribeOption TRANSACTED = opt("transacted", true, SubscribeOption.class); } Listener subscribe(String id, MessageHandler handler,
Codecs codecs,
projectodd/wunderboss
messaging/src/main/java/org/projectodd/wunderboss/messaging/ResponseRouter.java
// Path: core/src/main/java/org/projectodd/wunderboss/Options.java // public class Options<T> extends HashMap<T, Object> { // // public Options() { // this(null); // } // // public Options(Map<T, Object> options) { // if (options != null) { // putAll(options); // } // } // // /** // * Looks up key in the options. // * // * If key is an Option, its default value will be returned if the key // * isn't found. // * // * @param key // * @return // */ // public Object get(Object key) { // Object val = super.get(key); // if (val == null && key instanceof Option) { // val = ((Option)key).defaultValue; // } // // return val; // } // // public Object get(T key, Object defaultValue) { // return get(key) != null ? get(key) : defaultValue; // } // // public Boolean getBoolean(T key) { // return getBoolean(key, null); // } // // public Boolean getBoolean(T key, Boolean defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Boolean)) { // value = Boolean.parseBoolean(value.toString()); // } // // return (Boolean)value; // } // // public Integer getInt(T key) { // return getInt(key, null); // } // // public Integer getInt(T key, Integer defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Integer)) { // value = Integer.parseInt(value.toString()); // } // // return (Integer)value; // } // // public Long getLong(T key) { // return getLong(key, null); // } // // public Long getLong(T key, Long defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Long)) { // value = Long.parseLong(value.toString()); // } // // return (Long)value; // } // // public Double getDouble(T key) { // return getDouble(key, null); // } // // public Double getDouble(T key, Double defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Double)) { // value = Double.parseDouble(value.toString()); // } // // return (Double)value; // } // // public String getString(T key) { // return getString(key, null); // } // // public String getString(T key, String defaultValue) { // return get(key) != null ? get(key).toString() : defaultValue; // } // // public Date getDate(T key) { // return getDate(key, null); // } // // public Date getDate(T key, Date defaultValue) { // return get(key) != null ? (Date)get(key) : defaultValue; // } // // public List getList(T key) { // Object v = get(key); // if (v instanceof List || v == null) { // return (List) v; // } // return Arrays.asList(v); // } // // public Options put(T key, Object value) { // super.put(key, value); // // return this; // } // // /** // * Returns true if key resolves to a *non-null value* (considering // * a possible default), false otherwise. // */ // public boolean has(T key) { // return get(key) != null; // } // // public Options<T> merge(Options<T> otherOptions) { // Options mergedOptions = new Options(); // for (T key : this.keySet()) { // mergedOptions.put(key, this.get(key)); // } // for (T key : otherOptions.keySet()) { // mergedOptions.put(key, otherOptions.get(key)); // } // return mergedOptions; // } // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codecs.java // public class Codecs { // // public Codecs add(Codec codec) { // codecs.put(codec.name(), codec); // codecs.put(codec.contentType(), codec); // // return this; // } // // public Codec forName(String name) { // return codecs.get(name); // } // // public Codec forContentType(String contentType) { // return codecs.get(contentType); // } // // public Set<Codec> codecs() { // return Collections.unmodifiableSet(new HashSet<>(codecs.values())); // } // // private final Map<String, Codec> codecs = new HashMap<>(); // }
import org.projectodd.wunderboss.Options; import org.projectodd.wunderboss.codecs.Codecs; import java.util.HashMap; import java.util.Map;
/* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging; public class ResponseRouter implements AutoCloseable, MessageHandler { public ResponseRouter(String id) { this.id = id; } @Override public Reply onMessage(Message msg, Context ignored) throws Exception { String id = msg.requestID(); Response response = this.responses.remove(id); if (response == null) { throw new IllegalStateException("No responder for id " + id); } response.deliver(msg); return null; } public void registerResponse(String id, Response response) { this.responses.put(id, response); }
// Path: core/src/main/java/org/projectodd/wunderboss/Options.java // public class Options<T> extends HashMap<T, Object> { // // public Options() { // this(null); // } // // public Options(Map<T, Object> options) { // if (options != null) { // putAll(options); // } // } // // /** // * Looks up key in the options. // * // * If key is an Option, its default value will be returned if the key // * isn't found. // * // * @param key // * @return // */ // public Object get(Object key) { // Object val = super.get(key); // if (val == null && key instanceof Option) { // val = ((Option)key).defaultValue; // } // // return val; // } // // public Object get(T key, Object defaultValue) { // return get(key) != null ? get(key) : defaultValue; // } // // public Boolean getBoolean(T key) { // return getBoolean(key, null); // } // // public Boolean getBoolean(T key, Boolean defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Boolean)) { // value = Boolean.parseBoolean(value.toString()); // } // // return (Boolean)value; // } // // public Integer getInt(T key) { // return getInt(key, null); // } // // public Integer getInt(T key, Integer defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Integer)) { // value = Integer.parseInt(value.toString()); // } // // return (Integer)value; // } // // public Long getLong(T key) { // return getLong(key, null); // } // // public Long getLong(T key, Long defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Long)) { // value = Long.parseLong(value.toString()); // } // // return (Long)value; // } // // public Double getDouble(T key) { // return getDouble(key, null); // } // // public Double getDouble(T key, Double defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Double)) { // value = Double.parseDouble(value.toString()); // } // // return (Double)value; // } // // public String getString(T key) { // return getString(key, null); // } // // public String getString(T key, String defaultValue) { // return get(key) != null ? get(key).toString() : defaultValue; // } // // public Date getDate(T key) { // return getDate(key, null); // } // // public Date getDate(T key, Date defaultValue) { // return get(key) != null ? (Date)get(key) : defaultValue; // } // // public List getList(T key) { // Object v = get(key); // if (v instanceof List || v == null) { // return (List) v; // } // return Arrays.asList(v); // } // // public Options put(T key, Object value) { // super.put(key, value); // // return this; // } // // /** // * Returns true if key resolves to a *non-null value* (considering // * a possible default), false otherwise. // */ // public boolean has(T key) { // return get(key) != null; // } // // public Options<T> merge(Options<T> otherOptions) { // Options mergedOptions = new Options(); // for (T key : this.keySet()) { // mergedOptions.put(key, this.get(key)); // } // for (T key : otherOptions.keySet()) { // mergedOptions.put(key, otherOptions.get(key)); // } // return mergedOptions; // } // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codecs.java // public class Codecs { // // public Codecs add(Codec codec) { // codecs.put(codec.name(), codec); // codecs.put(codec.contentType(), codec); // // return this; // } // // public Codec forName(String name) { // return codecs.get(name); // } // // public Codec forContentType(String contentType) { // return codecs.get(contentType); // } // // public Set<Codec> codecs() { // return Collections.unmodifiableSet(new HashSet<>(codecs.values())); // } // // private final Map<String, Codec> codecs = new HashMap<>(); // } // Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/ResponseRouter.java import org.projectodd.wunderboss.Options; import org.projectodd.wunderboss.codecs.Codecs; import java.util.HashMap; import java.util.Map; /* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging; public class ResponseRouter implements AutoCloseable, MessageHandler { public ResponseRouter(String id) { this.id = id; } @Override public Reply onMessage(Message msg, Context ignored) throws Exception { String id = msg.requestID(); Response response = this.responses.remove(id); if (response == null) { throw new IllegalStateException("No responder for id " + id); } response.deliver(msg); return null; } public void registerResponse(String id, Response response) { this.responses.put(id, response); }
public synchronized static ResponseRouter routerFor(Queue queue, Codecs codecs,
projectodd/wunderboss
messaging/src/main/java/org/projectodd/wunderboss/messaging/ResponseRouter.java
// Path: core/src/main/java/org/projectodd/wunderboss/Options.java // public class Options<T> extends HashMap<T, Object> { // // public Options() { // this(null); // } // // public Options(Map<T, Object> options) { // if (options != null) { // putAll(options); // } // } // // /** // * Looks up key in the options. // * // * If key is an Option, its default value will be returned if the key // * isn't found. // * // * @param key // * @return // */ // public Object get(Object key) { // Object val = super.get(key); // if (val == null && key instanceof Option) { // val = ((Option)key).defaultValue; // } // // return val; // } // // public Object get(T key, Object defaultValue) { // return get(key) != null ? get(key) : defaultValue; // } // // public Boolean getBoolean(T key) { // return getBoolean(key, null); // } // // public Boolean getBoolean(T key, Boolean defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Boolean)) { // value = Boolean.parseBoolean(value.toString()); // } // // return (Boolean)value; // } // // public Integer getInt(T key) { // return getInt(key, null); // } // // public Integer getInt(T key, Integer defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Integer)) { // value = Integer.parseInt(value.toString()); // } // // return (Integer)value; // } // // public Long getLong(T key) { // return getLong(key, null); // } // // public Long getLong(T key, Long defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Long)) { // value = Long.parseLong(value.toString()); // } // // return (Long)value; // } // // public Double getDouble(T key) { // return getDouble(key, null); // } // // public Double getDouble(T key, Double defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Double)) { // value = Double.parseDouble(value.toString()); // } // // return (Double)value; // } // // public String getString(T key) { // return getString(key, null); // } // // public String getString(T key, String defaultValue) { // return get(key) != null ? get(key).toString() : defaultValue; // } // // public Date getDate(T key) { // return getDate(key, null); // } // // public Date getDate(T key, Date defaultValue) { // return get(key) != null ? (Date)get(key) : defaultValue; // } // // public List getList(T key) { // Object v = get(key); // if (v instanceof List || v == null) { // return (List) v; // } // return Arrays.asList(v); // } // // public Options put(T key, Object value) { // super.put(key, value); // // return this; // } // // /** // * Returns true if key resolves to a *non-null value* (considering // * a possible default), false otherwise. // */ // public boolean has(T key) { // return get(key) != null; // } // // public Options<T> merge(Options<T> otherOptions) { // Options mergedOptions = new Options(); // for (T key : this.keySet()) { // mergedOptions.put(key, this.get(key)); // } // for (T key : otherOptions.keySet()) { // mergedOptions.put(key, otherOptions.get(key)); // } // return mergedOptions; // } // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codecs.java // public class Codecs { // // public Codecs add(Codec codec) { // codecs.put(codec.name(), codec); // codecs.put(codec.contentType(), codec); // // return this; // } // // public Codec forName(String name) { // return codecs.get(name); // } // // public Codec forContentType(String contentType) { // return codecs.get(contentType); // } // // public Set<Codec> codecs() { // return Collections.unmodifiableSet(new HashSet<>(codecs.values())); // } // // private final Map<String, Codec> codecs = new HashMap<>(); // }
import org.projectodd.wunderboss.Options; import org.projectodd.wunderboss.codecs.Codecs; import java.util.HashMap; import java.util.Map;
/* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging; public class ResponseRouter implements AutoCloseable, MessageHandler { public ResponseRouter(String id) { this.id = id; } @Override public Reply onMessage(Message msg, Context ignored) throws Exception { String id = msg.requestID(); Response response = this.responses.remove(id); if (response == null) { throw new IllegalStateException("No responder for id " + id); } response.deliver(msg); return null; } public void registerResponse(String id, Response response) { this.responses.put(id, response); } public synchronized static ResponseRouter routerFor(Queue queue, Codecs codecs,
// Path: core/src/main/java/org/projectodd/wunderboss/Options.java // public class Options<T> extends HashMap<T, Object> { // // public Options() { // this(null); // } // // public Options(Map<T, Object> options) { // if (options != null) { // putAll(options); // } // } // // /** // * Looks up key in the options. // * // * If key is an Option, its default value will be returned if the key // * isn't found. // * // * @param key // * @return // */ // public Object get(Object key) { // Object val = super.get(key); // if (val == null && key instanceof Option) { // val = ((Option)key).defaultValue; // } // // return val; // } // // public Object get(T key, Object defaultValue) { // return get(key) != null ? get(key) : defaultValue; // } // // public Boolean getBoolean(T key) { // return getBoolean(key, null); // } // // public Boolean getBoolean(T key, Boolean defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Boolean)) { // value = Boolean.parseBoolean(value.toString()); // } // // return (Boolean)value; // } // // public Integer getInt(T key) { // return getInt(key, null); // } // // public Integer getInt(T key, Integer defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Integer)) { // value = Integer.parseInt(value.toString()); // } // // return (Integer)value; // } // // public Long getLong(T key) { // return getLong(key, null); // } // // public Long getLong(T key, Long defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Long)) { // value = Long.parseLong(value.toString()); // } // // return (Long)value; // } // // public Double getDouble(T key) { // return getDouble(key, null); // } // // public Double getDouble(T key, Double defaultValue) { // Object value = get(key); // if (value == null) { // value = defaultValue; // } else if (!(value instanceof Double)) { // value = Double.parseDouble(value.toString()); // } // // return (Double)value; // } // // public String getString(T key) { // return getString(key, null); // } // // public String getString(T key, String defaultValue) { // return get(key) != null ? get(key).toString() : defaultValue; // } // // public Date getDate(T key) { // return getDate(key, null); // } // // public Date getDate(T key, Date defaultValue) { // return get(key) != null ? (Date)get(key) : defaultValue; // } // // public List getList(T key) { // Object v = get(key); // if (v instanceof List || v == null) { // return (List) v; // } // return Arrays.asList(v); // } // // public Options put(T key, Object value) { // super.put(key, value); // // return this; // } // // /** // * Returns true if key resolves to a *non-null value* (considering // * a possible default), false otherwise. // */ // public boolean has(T key) { // return get(key) != null; // } // // public Options<T> merge(Options<T> otherOptions) { // Options mergedOptions = new Options(); // for (T key : this.keySet()) { // mergedOptions.put(key, this.get(key)); // } // for (T key : otherOptions.keySet()) { // mergedOptions.put(key, otherOptions.get(key)); // } // return mergedOptions; // } // } // // Path: core/src/main/java/org/projectodd/wunderboss/codecs/Codecs.java // public class Codecs { // // public Codecs add(Codec codec) { // codecs.put(codec.name(), codec); // codecs.put(codec.contentType(), codec); // // return this; // } // // public Codec forName(String name) { // return codecs.get(name); // } // // public Codec forContentType(String contentType) { // return codecs.get(contentType); // } // // public Set<Codec> codecs() { // return Collections.unmodifiableSet(new HashSet<>(codecs.values())); // } // // private final Map<String, Codec> codecs = new HashMap<>(); // } // Path: messaging/src/main/java/org/projectodd/wunderboss/messaging/ResponseRouter.java import org.projectodd.wunderboss.Options; import org.projectodd.wunderboss.codecs.Codecs; import java.util.HashMap; import java.util.Map; /* * Copyright 2014-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.projectodd.wunderboss.messaging; public class ResponseRouter implements AutoCloseable, MessageHandler { public ResponseRouter(String id) { this.id = id; } @Override public Reply onMessage(Message msg, Context ignored) throws Exception { String id = msg.requestID(); Response response = this.responses.remove(id); if (response == null) { throw new IllegalStateException("No responder for id " + id); } response.deliver(msg); return null; } public void registerResponse(String id, Response response) { this.responses.put(id, response); } public synchronized static ResponseRouter routerFor(Queue queue, Codecs codecs,
Options<Destination.ListenOption> options) {
bramp/unsafe
unsafe-benchmark/src/test/java/net/bramp/unsafe/collection/BenchmarkTest.java
// Path: unsafe-benchmark/src/test/java/net/bramp/unsafe/JMHHelper.java // @SuppressWarnings({"abbreviationaswordinname"}) // public class JMHHelper { // // @SuppressWarnings({"typename", "methodname"}) // private static class Blackhole_generated { // static Blackhole _jmh_tryInit_NewBlackhole() { // return new Blackhole(); // } // } // // /** // * Creates a new JMH Blackhole object. // * // * @return a JMH Blackhole object // */ // public static Blackhole newBlackhole() { // return Blackhole_generated._jmh_tryInit_NewBlackhole(); // } // // } // // Path: unsafe-benchmark/src/main/java/net/bramp/unsafe/collection/tests/ArrayListLongPoint.java // public class ArrayListLongPoint extends AbstractArrayListTest<LongPoint> { // // @Override public LongPoint newInstance() { // return new LongPoint(rand.nextLong(), rand.nextLong()); // } // // @Override public void iterate(final Blackhole bh) { // for (int i = 0; i < size; i++) { // bh.consume(list.get(i).x); // } // } // } // // Path: unsafe-benchmark/src/main/java/net/bramp/unsafe/collection/tests/UnsafeListLongPoint.java // public class UnsafeListLongPoint extends AbstractUnsafeListTest<LongPoint> { // // public Class<LongPoint> testClass() { // return LongPoint.class; // } // // @Override public LongPoint newInstance(LongPoint obj) { // obj.x = rand.nextLong(); // obj.y = rand.nextLong(); // return obj; // } // // @Override public void iterate(final Blackhole bh) { // for (int i = 0; i < size; i++) { // bh.consume(list.get(i).x); // } // } // // @Override public void iterateInPlace(final Blackhole bh) { // final LongPoint p = new LongPoint(0, 0); // for (int i = 0; i < size; i++) { // bh.consume(list.get(p, i).x); // } // } // }
import net.bramp.unsafe.JMHHelper; import net.bramp.unsafe.collection.tests.ArrayListLongPoint; import net.bramp.unsafe.collection.tests.UnsafeListLongPoint; import com.google.common.collect.Ordering; import org.junit.Test; import org.openjdk.jmh.infra.Blackhole; import static org.junit.Assert.assertTrue;
package net.bramp.unsafe.collection; public class BenchmarkTest { public static final Blackhole bh = JMHHelper.newBlackhole(); @Test public void testArrayListBenchmarks() throws InstantiationException, IllegalAccessException {
// Path: unsafe-benchmark/src/test/java/net/bramp/unsafe/JMHHelper.java // @SuppressWarnings({"abbreviationaswordinname"}) // public class JMHHelper { // // @SuppressWarnings({"typename", "methodname"}) // private static class Blackhole_generated { // static Blackhole _jmh_tryInit_NewBlackhole() { // return new Blackhole(); // } // } // // /** // * Creates a new JMH Blackhole object. // * // * @return a JMH Blackhole object // */ // public static Blackhole newBlackhole() { // return Blackhole_generated._jmh_tryInit_NewBlackhole(); // } // // } // // Path: unsafe-benchmark/src/main/java/net/bramp/unsafe/collection/tests/ArrayListLongPoint.java // public class ArrayListLongPoint extends AbstractArrayListTest<LongPoint> { // // @Override public LongPoint newInstance() { // return new LongPoint(rand.nextLong(), rand.nextLong()); // } // // @Override public void iterate(final Blackhole bh) { // for (int i = 0; i < size; i++) { // bh.consume(list.get(i).x); // } // } // } // // Path: unsafe-benchmark/src/main/java/net/bramp/unsafe/collection/tests/UnsafeListLongPoint.java // public class UnsafeListLongPoint extends AbstractUnsafeListTest<LongPoint> { // // public Class<LongPoint> testClass() { // return LongPoint.class; // } // // @Override public LongPoint newInstance(LongPoint obj) { // obj.x = rand.nextLong(); // obj.y = rand.nextLong(); // return obj; // } // // @Override public void iterate(final Blackhole bh) { // for (int i = 0; i < size; i++) { // bh.consume(list.get(i).x); // } // } // // @Override public void iterateInPlace(final Blackhole bh) { // final LongPoint p = new LongPoint(0, 0); // for (int i = 0; i < size; i++) { // bh.consume(list.get(p, i).x); // } // } // } // Path: unsafe-benchmark/src/test/java/net/bramp/unsafe/collection/BenchmarkTest.java import net.bramp.unsafe.JMHHelper; import net.bramp.unsafe.collection.tests.ArrayListLongPoint; import net.bramp.unsafe.collection.tests.UnsafeListLongPoint; import com.google.common.collect.Ordering; import org.junit.Test; import org.openjdk.jmh.infra.Blackhole; import static org.junit.Assert.assertTrue; package net.bramp.unsafe.collection; public class BenchmarkTest { public static final Blackhole bh = JMHHelper.newBlackhole(); @Test public void testArrayListBenchmarks() throws InstantiationException, IllegalAccessException {
ArrayListLongPoint state = new ArrayListLongPoint();
bramp/unsafe
unsafe-benchmark/src/test/java/net/bramp/unsafe/collection/BenchmarkTest.java
// Path: unsafe-benchmark/src/test/java/net/bramp/unsafe/JMHHelper.java // @SuppressWarnings({"abbreviationaswordinname"}) // public class JMHHelper { // // @SuppressWarnings({"typename", "methodname"}) // private static class Blackhole_generated { // static Blackhole _jmh_tryInit_NewBlackhole() { // return new Blackhole(); // } // } // // /** // * Creates a new JMH Blackhole object. // * // * @return a JMH Blackhole object // */ // public static Blackhole newBlackhole() { // return Blackhole_generated._jmh_tryInit_NewBlackhole(); // } // // } // // Path: unsafe-benchmark/src/main/java/net/bramp/unsafe/collection/tests/ArrayListLongPoint.java // public class ArrayListLongPoint extends AbstractArrayListTest<LongPoint> { // // @Override public LongPoint newInstance() { // return new LongPoint(rand.nextLong(), rand.nextLong()); // } // // @Override public void iterate(final Blackhole bh) { // for (int i = 0; i < size; i++) { // bh.consume(list.get(i).x); // } // } // } // // Path: unsafe-benchmark/src/main/java/net/bramp/unsafe/collection/tests/UnsafeListLongPoint.java // public class UnsafeListLongPoint extends AbstractUnsafeListTest<LongPoint> { // // public Class<LongPoint> testClass() { // return LongPoint.class; // } // // @Override public LongPoint newInstance(LongPoint obj) { // obj.x = rand.nextLong(); // obj.y = rand.nextLong(); // return obj; // } // // @Override public void iterate(final Blackhole bh) { // for (int i = 0; i < size; i++) { // bh.consume(list.get(i).x); // } // } // // @Override public void iterateInPlace(final Blackhole bh) { // final LongPoint p = new LongPoint(0, 0); // for (int i = 0; i < size; i++) { // bh.consume(list.get(p, i).x); // } // } // }
import net.bramp.unsafe.JMHHelper; import net.bramp.unsafe.collection.tests.ArrayListLongPoint; import net.bramp.unsafe.collection.tests.UnsafeListLongPoint; import com.google.common.collect.Ordering; import org.junit.Test; import org.openjdk.jmh.infra.Blackhole; import static org.junit.Assert.assertTrue;
package net.bramp.unsafe.collection; public class BenchmarkTest { public static final Blackhole bh = JMHHelper.newBlackhole(); @Test public void testArrayListBenchmarks() throws InstantiationException, IllegalAccessException { ArrayListLongPoint state = new ArrayListLongPoint(); state.size = 1000; state.setup(); state.iterate(bh); state.sort(); state.shuffle(); state.sort(); assertTrue(Ordering.natural().isOrdered(state.list)); } @Test public void testUnsafeListBenchmarks() throws InstantiationException, IllegalAccessException {
// Path: unsafe-benchmark/src/test/java/net/bramp/unsafe/JMHHelper.java // @SuppressWarnings({"abbreviationaswordinname"}) // public class JMHHelper { // // @SuppressWarnings({"typename", "methodname"}) // private static class Blackhole_generated { // static Blackhole _jmh_tryInit_NewBlackhole() { // return new Blackhole(); // } // } // // /** // * Creates a new JMH Blackhole object. // * // * @return a JMH Blackhole object // */ // public static Blackhole newBlackhole() { // return Blackhole_generated._jmh_tryInit_NewBlackhole(); // } // // } // // Path: unsafe-benchmark/src/main/java/net/bramp/unsafe/collection/tests/ArrayListLongPoint.java // public class ArrayListLongPoint extends AbstractArrayListTest<LongPoint> { // // @Override public LongPoint newInstance() { // return new LongPoint(rand.nextLong(), rand.nextLong()); // } // // @Override public void iterate(final Blackhole bh) { // for (int i = 0; i < size; i++) { // bh.consume(list.get(i).x); // } // } // } // // Path: unsafe-benchmark/src/main/java/net/bramp/unsafe/collection/tests/UnsafeListLongPoint.java // public class UnsafeListLongPoint extends AbstractUnsafeListTest<LongPoint> { // // public Class<LongPoint> testClass() { // return LongPoint.class; // } // // @Override public LongPoint newInstance(LongPoint obj) { // obj.x = rand.nextLong(); // obj.y = rand.nextLong(); // return obj; // } // // @Override public void iterate(final Blackhole bh) { // for (int i = 0; i < size; i++) { // bh.consume(list.get(i).x); // } // } // // @Override public void iterateInPlace(final Blackhole bh) { // final LongPoint p = new LongPoint(0, 0); // for (int i = 0; i < size; i++) { // bh.consume(list.get(p, i).x); // } // } // } // Path: unsafe-benchmark/src/test/java/net/bramp/unsafe/collection/BenchmarkTest.java import net.bramp.unsafe.JMHHelper; import net.bramp.unsafe.collection.tests.ArrayListLongPoint; import net.bramp.unsafe.collection.tests.UnsafeListLongPoint; import com.google.common.collect.Ordering; import org.junit.Test; import org.openjdk.jmh.infra.Blackhole; import static org.junit.Assert.assertTrue; package net.bramp.unsafe.collection; public class BenchmarkTest { public static final Blackhole bh = JMHHelper.newBlackhole(); @Test public void testArrayListBenchmarks() throws InstantiationException, IllegalAccessException { ArrayListLongPoint state = new ArrayListLongPoint(); state.size = 1000; state.setup(); state.iterate(bh); state.sort(); state.shuffle(); state.sort(); assertTrue(Ordering.natural().isOrdered(state.list)); } @Test public void testUnsafeListBenchmarks() throws InstantiationException, IllegalAccessException {
UnsafeListLongPoint state = new UnsafeListLongPoint();
bramp/unsafe
unsafe-collection/src/main/java/net/bramp/unsafe/UnsafeArrayList.java
// Path: unsafe-helper/src/main/java/net/bramp/unsafe/Preconditions.java // public static void checkArgument(boolean expression, // @Nullable String errorMessageTemplate, // @Nullable Object... errorMessageArgs) { // if (!expression) { // throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs)); // } // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/Preconditions.java // public static <T> T checkNotNull(T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import com.google.common.base.Throwables; import sun.misc.Unsafe; import java.util.AbstractList; import java.util.Collection; import java.util.RandomAccess; import static net.bramp.unsafe.Preconditions.checkArgument; import static net.bramp.unsafe.Preconditions.checkNotNull;
addAll(c); } public UnsafeArrayList(Class<T> type, int initialCapacity) { this.type = type; this.unsafe = UnsafeHelper.getUnsafe(); this.firstFieldOffset = UnsafeHelper.firstFieldOffset(type); this.elementSize = UnsafeHelper.sizeOf(type) - firstFieldOffset; this.elementSpacing = Math.max(8, this.elementSize); // TODO(bramp) Do we need to pad to 8 bytes. try { copier = new UnrolledUnsafeCopierBuilder().of(type).build(this.unsafe); // Temp working space tmp = newInstance(); } catch (Exception e) { throw Throwables.propagate(e); } setCapacity(initialCapacity); } @SuppressWarnings("unchecked") private T newInstance() throws InstantiationException { return (T) unsafe.allocateInstance(type); } private void setCapacity(int capacity) {
// Path: unsafe-helper/src/main/java/net/bramp/unsafe/Preconditions.java // public static void checkArgument(boolean expression, // @Nullable String errorMessageTemplate, // @Nullable Object... errorMessageArgs) { // if (!expression) { // throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs)); // } // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/Preconditions.java // public static <T> T checkNotNull(T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: unsafe-collection/src/main/java/net/bramp/unsafe/UnsafeArrayList.java import com.google.common.base.Throwables; import sun.misc.Unsafe; import java.util.AbstractList; import java.util.Collection; import java.util.RandomAccess; import static net.bramp.unsafe.Preconditions.checkArgument; import static net.bramp.unsafe.Preconditions.checkNotNull; addAll(c); } public UnsafeArrayList(Class<T> type, int initialCapacity) { this.type = type; this.unsafe = UnsafeHelper.getUnsafe(); this.firstFieldOffset = UnsafeHelper.firstFieldOffset(type); this.elementSize = UnsafeHelper.sizeOf(type) - firstFieldOffset; this.elementSpacing = Math.max(8, this.elementSize); // TODO(bramp) Do we need to pad to 8 bytes. try { copier = new UnrolledUnsafeCopierBuilder().of(type).build(this.unsafe); // Temp working space tmp = newInstance(); } catch (Exception e) { throw Throwables.propagate(e); } setCapacity(initialCapacity); } @SuppressWarnings("unchecked") private T newInstance() throws InstantiationException { return (T) unsafe.allocateInstance(type); } private void setCapacity(int capacity) {
checkArgument(capacity >= 0, "Capacity must be greater than or equal to zero");
bramp/unsafe
unsafe-collection/src/main/java/net/bramp/unsafe/UnsafeArrayList.java
// Path: unsafe-helper/src/main/java/net/bramp/unsafe/Preconditions.java // public static void checkArgument(boolean expression, // @Nullable String errorMessageTemplate, // @Nullable Object... errorMessageArgs) { // if (!expression) { // throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs)); // } // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/Preconditions.java // public static <T> T checkNotNull(T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import com.google.common.base.Throwables; import sun.misc.Unsafe; import java.util.AbstractList; import java.util.Collection; import java.util.RandomAccess; import static net.bramp.unsafe.Preconditions.checkArgument; import static net.bramp.unsafe.Preconditions.checkNotNull;
@Override public T get(int index) { try { return get(newInstance(), index); } catch (InstantiationException e) { throw Throwables.propagate(e); } } private long offset(int index) { return base + index * elementSpacing; } /** * Copies the element at index into dest * * @param dest The destination object * @param index The index of the object to get * @return The fetched object */ public T get(T dest, int index) { checkBounds(index); // We would rather do // UnsafeHelper.copyMemory(null, offset(index), dest, firstFieldOffset, elementSize); // but this is unsupported by the Unsafe class copier.copy(dest, offset(index)); return dest; } @Override public T set(int index, T element) { checkBounds(index);
// Path: unsafe-helper/src/main/java/net/bramp/unsafe/Preconditions.java // public static void checkArgument(boolean expression, // @Nullable String errorMessageTemplate, // @Nullable Object... errorMessageArgs) { // if (!expression) { // throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs)); // } // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/Preconditions.java // public static <T> T checkNotNull(T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: unsafe-collection/src/main/java/net/bramp/unsafe/UnsafeArrayList.java import com.google.common.base.Throwables; import sun.misc.Unsafe; import java.util.AbstractList; import java.util.Collection; import java.util.RandomAccess; import static net.bramp.unsafe.Preconditions.checkArgument; import static net.bramp.unsafe.Preconditions.checkNotNull; @Override public T get(int index) { try { return get(newInstance(), index); } catch (InstantiationException e) { throw Throwables.propagate(e); } } private long offset(int index) { return base + index * elementSpacing; } /** * Copies the element at index into dest * * @param dest The destination object * @param index The index of the object to get * @return The fetched object */ public T get(T dest, int index) { checkBounds(index); // We would rather do // UnsafeHelper.copyMemory(null, offset(index), dest, firstFieldOffset, elementSize); // but this is unsupported by the Unsafe class copier.copy(dest, offset(index)); return dest; } @Override public T set(int index, T element) { checkBounds(index);
checkNotNull(element);
bramp/unsafe
unsafe-collection/src/test/java/net/bramp/unsafe/UnsafeArrayListTest.java
// Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/LongPoint.java // public class LongPoint implements Comparable<LongPoint> { // public long x; // public long y; // // public LongPoint(long x, long y) { // this.x = x; // this.y = y; // } // // public String toString() { // return "Point(" + x + "," + y + ")"; // } // // @Override public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // LongPoint longPoint = (LongPoint) obj; // return Objects.equal(x, longPoint.x) && Objects.equal(y, longPoint.y); // } // // @Override public int hashCode() { // return Objects.hashCode(x, y); // } // // public int compareTo(LongPoint obj) { // return ComparisonChain.start().compare(x, obj.x).compare(y, obj.y).result(); // } // }
import com.google.common.collect.testing.*; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.ListFeature; import junit.framework.TestSuite; import net.bramp.unsafe.examples.LongPoint; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Suite; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals;
/** * Tests the UnsafeArrayList using guava-testlib. * Used https://www.klittlepage.com/2014/01/08/testing-collections-with-guava-testlib-and-junit-4/ * as a reference. */ package net.bramp.unsafe; /** * Your test class must be annotated with {@link RunWith} to specify that it's a * test suite and not a single test. */ @RunWith(Suite.class) /** * We need to use static inner classes as JUnit only allows for empty "holder" * suite classes. */ @Suite.SuiteClasses({ UnsafeArrayListTest.GuavaTests.class, UnsafeArrayListTest.AdditionalTests.class, }) public class UnsafeArrayListTest { /** * Add your additional test cases here. */ public static class AdditionalTests { static final int TEST_SIZE = 25; // Recommended larger than UnsafeArrayList.DEFAULT_CAPACITY
// Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/LongPoint.java // public class LongPoint implements Comparable<LongPoint> { // public long x; // public long y; // // public LongPoint(long x, long y) { // this.x = x; // this.y = y; // } // // public String toString() { // return "Point(" + x + "," + y + ")"; // } // // @Override public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // LongPoint longPoint = (LongPoint) obj; // return Objects.equal(x, longPoint.x) && Objects.equal(y, longPoint.y); // } // // @Override public int hashCode() { // return Objects.hashCode(x, y); // } // // public int compareTo(LongPoint obj) { // return ComparisonChain.start().compare(x, obj.x).compare(y, obj.y).result(); // } // } // Path: unsafe-collection/src/test/java/net/bramp/unsafe/UnsafeArrayListTest.java import com.google.common.collect.testing.*; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.ListFeature; import junit.framework.TestSuite; import net.bramp.unsafe.examples.LongPoint; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Suite; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; /** * Tests the UnsafeArrayList using guava-testlib. * Used https://www.klittlepage.com/2014/01/08/testing-collections-with-guava-testlib-and-junit-4/ * as a reference. */ package net.bramp.unsafe; /** * Your test class must be annotated with {@link RunWith} to specify that it's a * test suite and not a single test. */ @RunWith(Suite.class) /** * We need to use static inner classes as JUnit only allows for empty "holder" * suite classes. */ @Suite.SuiteClasses({ UnsafeArrayListTest.GuavaTests.class, UnsafeArrayListTest.AdditionalTests.class, }) public class UnsafeArrayListTest { /** * Add your additional test cases here. */ public static class AdditionalTests { static final int TEST_SIZE = 25; // Recommended larger than UnsafeArrayList.DEFAULT_CAPACITY
UnsafeArrayList<LongPoint> list;
bramp/unsafe
unsafe-unroller/src/test/java/net/bramp/unsafe/AbstractUnsafeCopierTest.java
// Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/FourLongs.java // public class FourLongs implements Comparable<FourLongs> { // public long a, b, c, d; // // public FourLongs() { // this(0, 0, 0, 0); // } // // /** // * Creates a new FourLongs. // * // * @param a 1st field // * @param b 2nd field // * @param c 3rd field // * @param d 4th field // */ // public FourLongs(long a, long b, long c, long d) { // this.a = a; // this.b = b; // this.c = c; // this.d = d; // } // // @Override public String toString() { // return "FourLongs{" + // "a=0x" + Long.toHexString(a) + ", " + // "b=0x" + Long.toHexString(b) + ", " + // "c=0x" + Long.toHexString(c) + ", " + // "d=0x" + Long.toHexString(d) + '}'; // } // // @Override public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // FourLongs fourLongs = (FourLongs) obj; // return Objects.equal(a, fourLongs.a) // && Objects.equal(b, fourLongs.b) // && Objects.equal(c, fourLongs.c) // && Objects.equal(d, fourLongs.d); // } // // @Override public int hashCode() { // return Objects.hashCode(a, b, c, d); // } // // @Override public int compareTo(FourLongs obj) { // return ComparisonChain.start() // .compare(a, obj.a) // .compare(b, obj.b) // .compare(c, obj.c) // .compare(d, obj.d) // .result(); // } // } // // Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/UnalignedClass.java // public class UnalignedClass implements Comparable<UnalignedClass> { // public final char c; // // public UnalignedClass(char c) { // this.c = c; // } // // public UnalignedClass(int i) { // this.c = (char)i; // } // // @Override // public String toString() { // return "UnalignedClass{c=" + (int)c + "}"; // } // // @Override // public int compareTo(UnalignedClass obj) { // return ComparisonChain.start().compare(c, obj.c).result(); // } // // @Override // public boolean equals(Object obj) { // return obj instanceof UnalignedClass && c == ((UnalignedClass)obj).c; // } // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java // public static long firstFieldOffset(Object obj) { // return firstFieldOffset(obj.getClass()); // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java // public static long sizeOfFields(Object obj) { // return sizeOfFields(obj.getClass()); // }
import net.bramp.unsafe.examples.FourLongs; import net.bramp.unsafe.examples.UnalignedClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import sun.misc.Unsafe; import java.lang.reflect.InvocationTargetException; import static net.bramp.unsafe.UnsafeHelper.firstFieldOffset; import static net.bramp.unsafe.UnsafeHelper.sizeOfFields; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package net.bramp.unsafe; /** * TODO Test the write doesn't overrun or underun */ public abstract class AbstractUnsafeCopierTest { final static Unsafe unsafe = UnsafeHelper.getUnsafe();
// Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/FourLongs.java // public class FourLongs implements Comparable<FourLongs> { // public long a, b, c, d; // // public FourLongs() { // this(0, 0, 0, 0); // } // // /** // * Creates a new FourLongs. // * // * @param a 1st field // * @param b 2nd field // * @param c 3rd field // * @param d 4th field // */ // public FourLongs(long a, long b, long c, long d) { // this.a = a; // this.b = b; // this.c = c; // this.d = d; // } // // @Override public String toString() { // return "FourLongs{" + // "a=0x" + Long.toHexString(a) + ", " + // "b=0x" + Long.toHexString(b) + ", " + // "c=0x" + Long.toHexString(c) + ", " + // "d=0x" + Long.toHexString(d) + '}'; // } // // @Override public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // FourLongs fourLongs = (FourLongs) obj; // return Objects.equal(a, fourLongs.a) // && Objects.equal(b, fourLongs.b) // && Objects.equal(c, fourLongs.c) // && Objects.equal(d, fourLongs.d); // } // // @Override public int hashCode() { // return Objects.hashCode(a, b, c, d); // } // // @Override public int compareTo(FourLongs obj) { // return ComparisonChain.start() // .compare(a, obj.a) // .compare(b, obj.b) // .compare(c, obj.c) // .compare(d, obj.d) // .result(); // } // } // // Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/UnalignedClass.java // public class UnalignedClass implements Comparable<UnalignedClass> { // public final char c; // // public UnalignedClass(char c) { // this.c = c; // } // // public UnalignedClass(int i) { // this.c = (char)i; // } // // @Override // public String toString() { // return "UnalignedClass{c=" + (int)c + "}"; // } // // @Override // public int compareTo(UnalignedClass obj) { // return ComparisonChain.start().compare(c, obj.c).result(); // } // // @Override // public boolean equals(Object obj) { // return obj instanceof UnalignedClass && c == ((UnalignedClass)obj).c; // } // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java // public static long firstFieldOffset(Object obj) { // return firstFieldOffset(obj.getClass()); // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java // public static long sizeOfFields(Object obj) { // return sizeOfFields(obj.getClass()); // } // Path: unsafe-unroller/src/test/java/net/bramp/unsafe/AbstractUnsafeCopierTest.java import net.bramp.unsafe.examples.FourLongs; import net.bramp.unsafe.examples.UnalignedClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import sun.misc.Unsafe; import java.lang.reflect.InvocationTargetException; import static net.bramp.unsafe.UnsafeHelper.firstFieldOffset; import static net.bramp.unsafe.UnsafeHelper.sizeOfFields; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package net.bramp.unsafe; /** * TODO Test the write doesn't overrun or underun */ public abstract class AbstractUnsafeCopierTest { final static Unsafe unsafe = UnsafeHelper.getUnsafe();
final static long fourLongOffset = firstFieldOffset(FourLongs.class);
bramp/unsafe
unsafe-unroller/src/test/java/net/bramp/unsafe/AbstractUnsafeCopierTest.java
// Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/FourLongs.java // public class FourLongs implements Comparable<FourLongs> { // public long a, b, c, d; // // public FourLongs() { // this(0, 0, 0, 0); // } // // /** // * Creates a new FourLongs. // * // * @param a 1st field // * @param b 2nd field // * @param c 3rd field // * @param d 4th field // */ // public FourLongs(long a, long b, long c, long d) { // this.a = a; // this.b = b; // this.c = c; // this.d = d; // } // // @Override public String toString() { // return "FourLongs{" + // "a=0x" + Long.toHexString(a) + ", " + // "b=0x" + Long.toHexString(b) + ", " + // "c=0x" + Long.toHexString(c) + ", " + // "d=0x" + Long.toHexString(d) + '}'; // } // // @Override public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // FourLongs fourLongs = (FourLongs) obj; // return Objects.equal(a, fourLongs.a) // && Objects.equal(b, fourLongs.b) // && Objects.equal(c, fourLongs.c) // && Objects.equal(d, fourLongs.d); // } // // @Override public int hashCode() { // return Objects.hashCode(a, b, c, d); // } // // @Override public int compareTo(FourLongs obj) { // return ComparisonChain.start() // .compare(a, obj.a) // .compare(b, obj.b) // .compare(c, obj.c) // .compare(d, obj.d) // .result(); // } // } // // Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/UnalignedClass.java // public class UnalignedClass implements Comparable<UnalignedClass> { // public final char c; // // public UnalignedClass(char c) { // this.c = c; // } // // public UnalignedClass(int i) { // this.c = (char)i; // } // // @Override // public String toString() { // return "UnalignedClass{c=" + (int)c + "}"; // } // // @Override // public int compareTo(UnalignedClass obj) { // return ComparisonChain.start().compare(c, obj.c).result(); // } // // @Override // public boolean equals(Object obj) { // return obj instanceof UnalignedClass && c == ((UnalignedClass)obj).c; // } // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java // public static long firstFieldOffset(Object obj) { // return firstFieldOffset(obj.getClass()); // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java // public static long sizeOfFields(Object obj) { // return sizeOfFields(obj.getClass()); // }
import net.bramp.unsafe.examples.FourLongs; import net.bramp.unsafe.examples.UnalignedClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import sun.misc.Unsafe; import java.lang.reflect.InvocationTargetException; import static net.bramp.unsafe.UnsafeHelper.firstFieldOffset; import static net.bramp.unsafe.UnsafeHelper.sizeOfFields; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package net.bramp.unsafe; /** * TODO Test the write doesn't overrun or underun */ public abstract class AbstractUnsafeCopierTest { final static Unsafe unsafe = UnsafeHelper.getUnsafe();
// Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/FourLongs.java // public class FourLongs implements Comparable<FourLongs> { // public long a, b, c, d; // // public FourLongs() { // this(0, 0, 0, 0); // } // // /** // * Creates a new FourLongs. // * // * @param a 1st field // * @param b 2nd field // * @param c 3rd field // * @param d 4th field // */ // public FourLongs(long a, long b, long c, long d) { // this.a = a; // this.b = b; // this.c = c; // this.d = d; // } // // @Override public String toString() { // return "FourLongs{" + // "a=0x" + Long.toHexString(a) + ", " + // "b=0x" + Long.toHexString(b) + ", " + // "c=0x" + Long.toHexString(c) + ", " + // "d=0x" + Long.toHexString(d) + '}'; // } // // @Override public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // FourLongs fourLongs = (FourLongs) obj; // return Objects.equal(a, fourLongs.a) // && Objects.equal(b, fourLongs.b) // && Objects.equal(c, fourLongs.c) // && Objects.equal(d, fourLongs.d); // } // // @Override public int hashCode() { // return Objects.hashCode(a, b, c, d); // } // // @Override public int compareTo(FourLongs obj) { // return ComparisonChain.start() // .compare(a, obj.a) // .compare(b, obj.b) // .compare(c, obj.c) // .compare(d, obj.d) // .result(); // } // } // // Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/UnalignedClass.java // public class UnalignedClass implements Comparable<UnalignedClass> { // public final char c; // // public UnalignedClass(char c) { // this.c = c; // } // // public UnalignedClass(int i) { // this.c = (char)i; // } // // @Override // public String toString() { // return "UnalignedClass{c=" + (int)c + "}"; // } // // @Override // public int compareTo(UnalignedClass obj) { // return ComparisonChain.start().compare(c, obj.c).result(); // } // // @Override // public boolean equals(Object obj) { // return obj instanceof UnalignedClass && c == ((UnalignedClass)obj).c; // } // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java // public static long firstFieldOffset(Object obj) { // return firstFieldOffset(obj.getClass()); // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java // public static long sizeOfFields(Object obj) { // return sizeOfFields(obj.getClass()); // } // Path: unsafe-unroller/src/test/java/net/bramp/unsafe/AbstractUnsafeCopierTest.java import net.bramp.unsafe.examples.FourLongs; import net.bramp.unsafe.examples.UnalignedClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import sun.misc.Unsafe; import java.lang.reflect.InvocationTargetException; import static net.bramp.unsafe.UnsafeHelper.firstFieldOffset; import static net.bramp.unsafe.UnsafeHelper.sizeOfFields; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package net.bramp.unsafe; /** * TODO Test the write doesn't overrun or underun */ public abstract class AbstractUnsafeCopierTest { final static Unsafe unsafe = UnsafeHelper.getUnsafe();
final static long fourLongOffset = firstFieldOffset(FourLongs.class);
bramp/unsafe
unsafe-unroller/src/test/java/net/bramp/unsafe/AbstractUnsafeCopierTest.java
// Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/FourLongs.java // public class FourLongs implements Comparable<FourLongs> { // public long a, b, c, d; // // public FourLongs() { // this(0, 0, 0, 0); // } // // /** // * Creates a new FourLongs. // * // * @param a 1st field // * @param b 2nd field // * @param c 3rd field // * @param d 4th field // */ // public FourLongs(long a, long b, long c, long d) { // this.a = a; // this.b = b; // this.c = c; // this.d = d; // } // // @Override public String toString() { // return "FourLongs{" + // "a=0x" + Long.toHexString(a) + ", " + // "b=0x" + Long.toHexString(b) + ", " + // "c=0x" + Long.toHexString(c) + ", " + // "d=0x" + Long.toHexString(d) + '}'; // } // // @Override public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // FourLongs fourLongs = (FourLongs) obj; // return Objects.equal(a, fourLongs.a) // && Objects.equal(b, fourLongs.b) // && Objects.equal(c, fourLongs.c) // && Objects.equal(d, fourLongs.d); // } // // @Override public int hashCode() { // return Objects.hashCode(a, b, c, d); // } // // @Override public int compareTo(FourLongs obj) { // return ComparisonChain.start() // .compare(a, obj.a) // .compare(b, obj.b) // .compare(c, obj.c) // .compare(d, obj.d) // .result(); // } // } // // Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/UnalignedClass.java // public class UnalignedClass implements Comparable<UnalignedClass> { // public final char c; // // public UnalignedClass(char c) { // this.c = c; // } // // public UnalignedClass(int i) { // this.c = (char)i; // } // // @Override // public String toString() { // return "UnalignedClass{c=" + (int)c + "}"; // } // // @Override // public int compareTo(UnalignedClass obj) { // return ComparisonChain.start().compare(c, obj.c).result(); // } // // @Override // public boolean equals(Object obj) { // return obj instanceof UnalignedClass && c == ((UnalignedClass)obj).c; // } // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java // public static long firstFieldOffset(Object obj) { // return firstFieldOffset(obj.getClass()); // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java // public static long sizeOfFields(Object obj) { // return sizeOfFields(obj.getClass()); // }
import net.bramp.unsafe.examples.FourLongs; import net.bramp.unsafe.examples.UnalignedClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import sun.misc.Unsafe; import java.lang.reflect.InvocationTargetException; import static net.bramp.unsafe.UnsafeHelper.firstFieldOffset; import static net.bramp.unsafe.UnsafeHelper.sizeOfFields; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package net.bramp.unsafe; /** * TODO Test the write doesn't overrun or underun */ public abstract class AbstractUnsafeCopierTest { final static Unsafe unsafe = UnsafeHelper.getUnsafe(); final static long fourLongOffset = firstFieldOffset(FourLongs.class); /** * Copies the objects fields into a allocated space in memory * * @param src * @return The address of the memory, must be freed with unsafe.freeMemory(..) */ protected static long copyToMemory(Object src, long srcOffset) { final long offset = UnsafeHelper.firstFieldOffset(src) + srcOffset;
// Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/FourLongs.java // public class FourLongs implements Comparable<FourLongs> { // public long a, b, c, d; // // public FourLongs() { // this(0, 0, 0, 0); // } // // /** // * Creates a new FourLongs. // * // * @param a 1st field // * @param b 2nd field // * @param c 3rd field // * @param d 4th field // */ // public FourLongs(long a, long b, long c, long d) { // this.a = a; // this.b = b; // this.c = c; // this.d = d; // } // // @Override public String toString() { // return "FourLongs{" + // "a=0x" + Long.toHexString(a) + ", " + // "b=0x" + Long.toHexString(b) + ", " + // "c=0x" + Long.toHexString(c) + ", " + // "d=0x" + Long.toHexString(d) + '}'; // } // // @Override public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // FourLongs fourLongs = (FourLongs) obj; // return Objects.equal(a, fourLongs.a) // && Objects.equal(b, fourLongs.b) // && Objects.equal(c, fourLongs.c) // && Objects.equal(d, fourLongs.d); // } // // @Override public int hashCode() { // return Objects.hashCode(a, b, c, d); // } // // @Override public int compareTo(FourLongs obj) { // return ComparisonChain.start() // .compare(a, obj.a) // .compare(b, obj.b) // .compare(c, obj.c) // .compare(d, obj.d) // .result(); // } // } // // Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/UnalignedClass.java // public class UnalignedClass implements Comparable<UnalignedClass> { // public final char c; // // public UnalignedClass(char c) { // this.c = c; // } // // public UnalignedClass(int i) { // this.c = (char)i; // } // // @Override // public String toString() { // return "UnalignedClass{c=" + (int)c + "}"; // } // // @Override // public int compareTo(UnalignedClass obj) { // return ComparisonChain.start().compare(c, obj.c).result(); // } // // @Override // public boolean equals(Object obj) { // return obj instanceof UnalignedClass && c == ((UnalignedClass)obj).c; // } // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java // public static long firstFieldOffset(Object obj) { // return firstFieldOffset(obj.getClass()); // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java // public static long sizeOfFields(Object obj) { // return sizeOfFields(obj.getClass()); // } // Path: unsafe-unroller/src/test/java/net/bramp/unsafe/AbstractUnsafeCopierTest.java import net.bramp.unsafe.examples.FourLongs; import net.bramp.unsafe.examples.UnalignedClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import sun.misc.Unsafe; import java.lang.reflect.InvocationTargetException; import static net.bramp.unsafe.UnsafeHelper.firstFieldOffset; import static net.bramp.unsafe.UnsafeHelper.sizeOfFields; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package net.bramp.unsafe; /** * TODO Test the write doesn't overrun or underun */ public abstract class AbstractUnsafeCopierTest { final static Unsafe unsafe = UnsafeHelper.getUnsafe(); final static long fourLongOffset = firstFieldOffset(FourLongs.class); /** * Copies the objects fields into a allocated space in memory * * @param src * @return The address of the memory, must be freed with unsafe.freeMemory(..) */ protected static long copyToMemory(Object src, long srcOffset) { final long offset = UnsafeHelper.firstFieldOffset(src) + srcOffset;
final long size = UnsafeHelper.sizeOfFields(src) - srcOffset;
bramp/unsafe
unsafe-unroller/src/test/java/net/bramp/unsafe/AbstractUnsafeCopierTest.java
// Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/FourLongs.java // public class FourLongs implements Comparable<FourLongs> { // public long a, b, c, d; // // public FourLongs() { // this(0, 0, 0, 0); // } // // /** // * Creates a new FourLongs. // * // * @param a 1st field // * @param b 2nd field // * @param c 3rd field // * @param d 4th field // */ // public FourLongs(long a, long b, long c, long d) { // this.a = a; // this.b = b; // this.c = c; // this.d = d; // } // // @Override public String toString() { // return "FourLongs{" + // "a=0x" + Long.toHexString(a) + ", " + // "b=0x" + Long.toHexString(b) + ", " + // "c=0x" + Long.toHexString(c) + ", " + // "d=0x" + Long.toHexString(d) + '}'; // } // // @Override public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // FourLongs fourLongs = (FourLongs) obj; // return Objects.equal(a, fourLongs.a) // && Objects.equal(b, fourLongs.b) // && Objects.equal(c, fourLongs.c) // && Objects.equal(d, fourLongs.d); // } // // @Override public int hashCode() { // return Objects.hashCode(a, b, c, d); // } // // @Override public int compareTo(FourLongs obj) { // return ComparisonChain.start() // .compare(a, obj.a) // .compare(b, obj.b) // .compare(c, obj.c) // .compare(d, obj.d) // .result(); // } // } // // Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/UnalignedClass.java // public class UnalignedClass implements Comparable<UnalignedClass> { // public final char c; // // public UnalignedClass(char c) { // this.c = c; // } // // public UnalignedClass(int i) { // this.c = (char)i; // } // // @Override // public String toString() { // return "UnalignedClass{c=" + (int)c + "}"; // } // // @Override // public int compareTo(UnalignedClass obj) { // return ComparisonChain.start().compare(c, obj.c).result(); // } // // @Override // public boolean equals(Object obj) { // return obj instanceof UnalignedClass && c == ((UnalignedClass)obj).c; // } // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java // public static long firstFieldOffset(Object obj) { // return firstFieldOffset(obj.getClass()); // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java // public static long sizeOfFields(Object obj) { // return sizeOfFields(obj.getClass()); // }
import net.bramp.unsafe.examples.FourLongs; import net.bramp.unsafe.examples.UnalignedClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import sun.misc.Unsafe; import java.lang.reflect.InvocationTargetException; import static net.bramp.unsafe.UnsafeHelper.firstFieldOffset; import static net.bramp.unsafe.UnsafeHelper.sizeOfFields; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
* @param srcOffset * @param dest * @param <T> * @return */ protected static<T> T test(UnsafeCopier copier, T src, long srcOffset, T dest) { final long srcMemory = copyToMemory(src, srcOffset); try { copier.copy(dest, srcMemory); } finally { unsafe.freeMemory(srcMemory); } return dest; } protected abstract UnsafeCopier createCopier(Class clazz) throws Exception; protected abstract UnsafeCopier createCopier(long offset, long length) throws Exception; protected abstract boolean supportsUnaligned(); protected abstract int stride(); /** * Ensure the test classes looks how we want */ @BeforeClass public static void checkAssumptions() { // FourLongs is aligned and a multiple of 8 bytes assertTrue(firstFieldOffset(FourLongs.class) % 8 == 0); assertEquals(4 * 8, sizeOfFields(FourLongs.class)); // UnalignedClass is not 8 byte aligned, and not a multiple of 8.
// Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/FourLongs.java // public class FourLongs implements Comparable<FourLongs> { // public long a, b, c, d; // // public FourLongs() { // this(0, 0, 0, 0); // } // // /** // * Creates a new FourLongs. // * // * @param a 1st field // * @param b 2nd field // * @param c 3rd field // * @param d 4th field // */ // public FourLongs(long a, long b, long c, long d) { // this.a = a; // this.b = b; // this.c = c; // this.d = d; // } // // @Override public String toString() { // return "FourLongs{" + // "a=0x" + Long.toHexString(a) + ", " + // "b=0x" + Long.toHexString(b) + ", " + // "c=0x" + Long.toHexString(c) + ", " + // "d=0x" + Long.toHexString(d) + '}'; // } // // @Override public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // FourLongs fourLongs = (FourLongs) obj; // return Objects.equal(a, fourLongs.a) // && Objects.equal(b, fourLongs.b) // && Objects.equal(c, fourLongs.c) // && Objects.equal(d, fourLongs.d); // } // // @Override public int hashCode() { // return Objects.hashCode(a, b, c, d); // } // // @Override public int compareTo(FourLongs obj) { // return ComparisonChain.start() // .compare(a, obj.a) // .compare(b, obj.b) // .compare(c, obj.c) // .compare(d, obj.d) // .result(); // } // } // // Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/UnalignedClass.java // public class UnalignedClass implements Comparable<UnalignedClass> { // public final char c; // // public UnalignedClass(char c) { // this.c = c; // } // // public UnalignedClass(int i) { // this.c = (char)i; // } // // @Override // public String toString() { // return "UnalignedClass{c=" + (int)c + "}"; // } // // @Override // public int compareTo(UnalignedClass obj) { // return ComparisonChain.start().compare(c, obj.c).result(); // } // // @Override // public boolean equals(Object obj) { // return obj instanceof UnalignedClass && c == ((UnalignedClass)obj).c; // } // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java // public static long firstFieldOffset(Object obj) { // return firstFieldOffset(obj.getClass()); // } // // Path: unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java // public static long sizeOfFields(Object obj) { // return sizeOfFields(obj.getClass()); // } // Path: unsafe-unroller/src/test/java/net/bramp/unsafe/AbstractUnsafeCopierTest.java import net.bramp.unsafe.examples.FourLongs; import net.bramp.unsafe.examples.UnalignedClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import sun.misc.Unsafe; import java.lang.reflect.InvocationTargetException; import static net.bramp.unsafe.UnsafeHelper.firstFieldOffset; import static net.bramp.unsafe.UnsafeHelper.sizeOfFields; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; * @param srcOffset * @param dest * @param <T> * @return */ protected static<T> T test(UnsafeCopier copier, T src, long srcOffset, T dest) { final long srcMemory = copyToMemory(src, srcOffset); try { copier.copy(dest, srcMemory); } finally { unsafe.freeMemory(srcMemory); } return dest; } protected abstract UnsafeCopier createCopier(Class clazz) throws Exception; protected abstract UnsafeCopier createCopier(long offset, long length) throws Exception; protected abstract boolean supportsUnaligned(); protected abstract int stride(); /** * Ensure the test classes looks how we want */ @BeforeClass public static void checkAssumptions() { // FourLongs is aligned and a multiple of 8 bytes assertTrue(firstFieldOffset(FourLongs.class) % 8 == 0); assertEquals(4 * 8, sizeOfFields(FourLongs.class)); // UnalignedClass is not 8 byte aligned, and not a multiple of 8.
assertTrue(firstFieldOffset(UnalignedClass.class) % 8 != 0);
bramp/unsafe
unsafe-benchmark/src/main/java/net/bramp/unsafe/Main.java
// Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/LongPoint.java // public class LongPoint implements Comparable<LongPoint> { // public long x; // public long y; // // public LongPoint(long x, long y) { // this.x = x; // this.y = y; // } // // public String toString() { // return "Point(" + x + "," + y + ")"; // } // // @Override public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // LongPoint longPoint = (LongPoint) obj; // return Objects.equal(x, longPoint.x) && Objects.equal(y, longPoint.y); // } // // @Override public int hashCode() { // return Objects.hashCode(x, y); // } // // public int compareTo(LongPoint obj) { // return ComparisonChain.start().compare(x, obj.x).compare(y, obj.y).result(); // } // } // // Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/Person.java // public class Person { // // final String name; // final long birthday; // Timestamp (as returned by currentTimeMillis) // final char gender; // // public Person(String name, long birthday, char gender) { // this.name = name; // this.birthday = birthday; // this.gender = gender; // } // // public String getName() { // return name; // } // // public long getBirthday() { // return birthday; // } // // public char getGender() { // return gender; // } // // /** // * Note: Not accurate, but only used as an example. // * // * @return the age of the person in years. // */ // public int getAge() { // return (int) ((System.currentTimeMillis() - birthday) / 1000 / 60 / 60 / 24 / 365); // } // // public String toString() { // return "Person(" + getName() + ", " + new Date(getBirthday()) + ", " + getGender() + ")"; // } // }
import net.bramp.unsafe.examples.LongPoint; import net.bramp.unsafe.examples.Person; import com.google.common.base.Stopwatch; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.TimeUnit;
package net.bramp.unsafe; public class Main { /** * Prints the memory layout of various test classes. */ public static void printMemoryLayout2() { Object o1 = new Object(); Object o2 = new Object(); Byte b1 = new Byte((byte) 0x12); Byte b2 = new Byte((byte) 0x34); Byte b3 = new Byte((byte) 0x56); Long l = new Long(0x0123456789ABCDEFL);
// Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/LongPoint.java // public class LongPoint implements Comparable<LongPoint> { // public long x; // public long y; // // public LongPoint(long x, long y) { // this.x = x; // this.y = y; // } // // public String toString() { // return "Point(" + x + "," + y + ")"; // } // // @Override public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // LongPoint longPoint = (LongPoint) obj; // return Objects.equal(x, longPoint.x) && Objects.equal(y, longPoint.y); // } // // @Override public int hashCode() { // return Objects.hashCode(x, y); // } // // public int compareTo(LongPoint obj) { // return ComparisonChain.start().compare(x, obj.x).compare(y, obj.y).result(); // } // } // // Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/Person.java // public class Person { // // final String name; // final long birthday; // Timestamp (as returned by currentTimeMillis) // final char gender; // // public Person(String name, long birthday, char gender) { // this.name = name; // this.birthday = birthday; // this.gender = gender; // } // // public String getName() { // return name; // } // // public long getBirthday() { // return birthday; // } // // public char getGender() { // return gender; // } // // /** // * Note: Not accurate, but only used as an example. // * // * @return the age of the person in years. // */ // public int getAge() { // return (int) ((System.currentTimeMillis() - birthday) / 1000 / 60 / 60 / 24 / 365); // } // // public String toString() { // return "Person(" + getName() + ", " + new Date(getBirthday()) + ", " + getGender() + ")"; // } // } // Path: unsafe-benchmark/src/main/java/net/bramp/unsafe/Main.java import net.bramp.unsafe.examples.LongPoint; import net.bramp.unsafe.examples.Person; import com.google.common.base.Stopwatch; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.TimeUnit; package net.bramp.unsafe; public class Main { /** * Prints the memory layout of various test classes. */ public static void printMemoryLayout2() { Object o1 = new Object(); Object o2 = new Object(); Byte b1 = new Byte((byte) 0x12); Byte b2 = new Byte((byte) 0x34); Byte b3 = new Byte((byte) 0x56); Long l = new Long(0x0123456789ABCDEFL);
Person p = new Person("Bob", 406425600000L, 'M');
bramp/unsafe
unsafe-benchmark/src/main/java/net/bramp/unsafe/Main.java
// Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/LongPoint.java // public class LongPoint implements Comparable<LongPoint> { // public long x; // public long y; // // public LongPoint(long x, long y) { // this.x = x; // this.y = y; // } // // public String toString() { // return "Point(" + x + "," + y + ")"; // } // // @Override public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // LongPoint longPoint = (LongPoint) obj; // return Objects.equal(x, longPoint.x) && Objects.equal(y, longPoint.y); // } // // @Override public int hashCode() { // return Objects.hashCode(x, y); // } // // public int compareTo(LongPoint obj) { // return ComparisonChain.start().compare(x, obj.x).compare(y, obj.y).result(); // } // } // // Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/Person.java // public class Person { // // final String name; // final long birthday; // Timestamp (as returned by currentTimeMillis) // final char gender; // // public Person(String name, long birthday, char gender) { // this.name = name; // this.birthday = birthday; // this.gender = gender; // } // // public String getName() { // return name; // } // // public long getBirthday() { // return birthday; // } // // public char getGender() { // return gender; // } // // /** // * Note: Not accurate, but only used as an example. // * // * @return the age of the person in years. // */ // public int getAge() { // return (int) ((System.currentTimeMillis() - birthday) / 1000 / 60 / 60 / 24 / 365); // } // // public String toString() { // return "Person(" + getName() + ", " + new Date(getBirthday()) + ", " + getGender() + ")"; // } // }
import net.bramp.unsafe.examples.LongPoint; import net.bramp.unsafe.examples.Person; import com.google.common.base.Stopwatch; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.TimeUnit;
System.out .printf("Person len:%d header:%d\n", UnsafeHelper.sizeOf(p), UnsafeHelper.headerSize(p)); UnsafeHelper.hexDump(System.out, p); } /** * <pre> * _________________________________________________________________ * | Test | Trial| Time (s)| Extra | * |================================================================| * | Create | 0 | 19.281 | | * | Safelist Sum | 0 | 0.208 | -1254641639, 1253696635| * | Unsafelist Sum (copy)| 0 | 0.448 | -1254641639, 1253696635| * | Safelist Sum | 1 | 0.235 | -1254641639, 1253696635| * | Unsafelist Sum (copy)| 1 | 0.282 | -1254641639, 1253696635| * | Safelist Sum | 2 | 0.259 | -1254641639, 1253696635| * | Unsafelist Sum (copy)| 2 | 0.22 | -1254641639, 1253696635| * | Safelist Sum | 3 | 0.23 | -1254641639, 1253696635| * | Unsafelist Sum (copy)| 3 | 0.271 | -1254641639, 1253696635| * | Safelist Sum | 4 | 0.251 | -1254641639, 1253696635| * | Unsafelist Sum (copy)| 4 | 0.263 | -1254641639, 1253696635| * </pre> */ public static class UnsafeTester { static final int SIZE = 40000000; // 40000000 uses ~3.1GiB of RAM. TODO work out what I expect static final Stopwatch stopwatch = Stopwatch.createUnstarted(); public void go() {
// Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/LongPoint.java // public class LongPoint implements Comparable<LongPoint> { // public long x; // public long y; // // public LongPoint(long x, long y) { // this.x = x; // this.y = y; // } // // public String toString() { // return "Point(" + x + "," + y + ")"; // } // // @Override public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // LongPoint longPoint = (LongPoint) obj; // return Objects.equal(x, longPoint.x) && Objects.equal(y, longPoint.y); // } // // @Override public int hashCode() { // return Objects.hashCode(x, y); // } // // public int compareTo(LongPoint obj) { // return ComparisonChain.start().compare(x, obj.x).compare(y, obj.y).result(); // } // } // // Path: unsafe-tests/src/main/java/net/bramp/unsafe/examples/Person.java // public class Person { // // final String name; // final long birthday; // Timestamp (as returned by currentTimeMillis) // final char gender; // // public Person(String name, long birthday, char gender) { // this.name = name; // this.birthday = birthday; // this.gender = gender; // } // // public String getName() { // return name; // } // // public long getBirthday() { // return birthday; // } // // public char getGender() { // return gender; // } // // /** // * Note: Not accurate, but only used as an example. // * // * @return the age of the person in years. // */ // public int getAge() { // return (int) ((System.currentTimeMillis() - birthday) / 1000 / 60 / 60 / 24 / 365); // } // // public String toString() { // return "Person(" + getName() + ", " + new Date(getBirthday()) + ", " + getGender() + ")"; // } // } // Path: unsafe-benchmark/src/main/java/net/bramp/unsafe/Main.java import net.bramp.unsafe.examples.LongPoint; import net.bramp.unsafe.examples.Person; import com.google.common.base.Stopwatch; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.TimeUnit; System.out .printf("Person len:%d header:%d\n", UnsafeHelper.sizeOf(p), UnsafeHelper.headerSize(p)); UnsafeHelper.hexDump(System.out, p); } /** * <pre> * _________________________________________________________________ * | Test | Trial| Time (s)| Extra | * |================================================================| * | Create | 0 | 19.281 | | * | Safelist Sum | 0 | 0.208 | -1254641639, 1253696635| * | Unsafelist Sum (copy)| 0 | 0.448 | -1254641639, 1253696635| * | Safelist Sum | 1 | 0.235 | -1254641639, 1253696635| * | Unsafelist Sum (copy)| 1 | 0.282 | -1254641639, 1253696635| * | Safelist Sum | 2 | 0.259 | -1254641639, 1253696635| * | Unsafelist Sum (copy)| 2 | 0.22 | -1254641639, 1253696635| * | Safelist Sum | 3 | 0.23 | -1254641639, 1253696635| * | Unsafelist Sum (copy)| 3 | 0.271 | -1254641639, 1253696635| * | Safelist Sum | 4 | 0.251 | -1254641639, 1253696635| * | Unsafelist Sum (copy)| 4 | 0.263 | -1254641639, 1253696635| * </pre> */ public static class UnsafeTester { static final int SIZE = 40000000; // 40000000 uses ~3.1GiB of RAM. TODO work out what I expect static final Stopwatch stopwatch = Stopwatch.createUnstarted(); public void go() {
final ArrayList<LongPoint> safeList = new ArrayList<LongPoint>(SIZE);
acromusashi/acromusashi-stream-ml
src/main/java/acromusashi/stream/ml/clustering/kmeans/state/InfinispanKmeansState.java
// Path: src/main/java/acromusashi/stream/ml/clustering/kmeans/entity/KmeansDataSet.java // public class KmeansDataSet implements Serializable // { // /** シリアル */ // private static final long serialVersionUID = 338231277453149972L; // // /** 各クラスタの中心座標の行列を格納した配列 */ // private double[][] centroids; // // /** 各クラスタに分類された要素数 */ // private long[] clusteredNum; // // /** // * パラメータを指定せずにインスタンスを生成する。 // */ // public KmeansDataSet() // {} // // /** // * @return the centroids // */ // public double[][] getCentroids() // { // return this.centroids; // } // // /** // * @param centroids the centroids to set // */ // public void setCentroids(double[][] centroids) // { // this.centroids = centroids; // } // // /** // * @return the clusteredNum // */ // public long[] getClusteredNum() // { // return this.clusteredNum; // } // // /** // * @param clusteredNum the clusteredNum to set // */ // public void setClusteredNum(long[] clusteredNum) // { // this.clusteredNum = clusteredNum; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() // { // String result = ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // return result; // } // }
import java.io.IOException; import java.util.Arrays; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commons.marshall.Marshaller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import acromusashi.stream.ml.clustering.kmeans.entity.KmeansDataSet; import com.google.common.base.Joiner;
/** * Copyright (c) Acroquest Technology Co, Ltd. All Rights Reserved. * Please read the associated COPYRIGHTS file for more details. * * THE SOFTWARE IS PROVIDED BY Acroquest Technolog Co., Ltd., * 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 HOLDER BE LIABLE FOR ANY * CLAIM, DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ package acromusashi.stream.ml.clustering.kmeans.state; /** * KMeans分散用Infinispan向けStateクラス<br> * 設定された「parallelismHint」の数だけ存在する。 * * @author kimura */ public class InfinispanKmeansState extends KmeansState { /** キャッシュ上のデータ生存期間のデフォルト値 */ private static final int DEFAULT_LIFESPAN = 600; /** logger */ private static final Logger logger = LoggerFactory.getLogger(InfinispanKmeansState.class); /** キャッシュ上のデータ生存期間(単位:秒) */ protected int lifespan = DEFAULT_LIFESPAN; /** 投入先のサーバ情報 */ protected String targetServer; /** 投入先キャッシュ名称 */ protected String cacheName; /** 状態を保存するベースキー */ protected String baseKey; /** Remoteキャッシュマネージャ */ protected transient RemoteCacheManager clientManager; /** 状態保存用キャッシュ */
// Path: src/main/java/acromusashi/stream/ml/clustering/kmeans/entity/KmeansDataSet.java // public class KmeansDataSet implements Serializable // { // /** シリアル */ // private static final long serialVersionUID = 338231277453149972L; // // /** 各クラスタの中心座標の行列を格納した配列 */ // private double[][] centroids; // // /** 各クラスタに分類された要素数 */ // private long[] clusteredNum; // // /** // * パラメータを指定せずにインスタンスを生成する。 // */ // public KmeansDataSet() // {} // // /** // * @return the centroids // */ // public double[][] getCentroids() // { // return this.centroids; // } // // /** // * @param centroids the centroids to set // */ // public void setCentroids(double[][] centroids) // { // this.centroids = centroids; // } // // /** // * @return the clusteredNum // */ // public long[] getClusteredNum() // { // return this.clusteredNum; // } // // /** // * @param clusteredNum the clusteredNum to set // */ // public void setClusteredNum(long[] clusteredNum) // { // this.clusteredNum = clusteredNum; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() // { // String result = ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // return result; // } // } // Path: src/main/java/acromusashi/stream/ml/clustering/kmeans/state/InfinispanKmeansState.java import java.io.IOException; import java.util.Arrays; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commons.marshall.Marshaller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import acromusashi.stream.ml.clustering.kmeans.entity.KmeansDataSet; import com.google.common.base.Joiner; /** * Copyright (c) Acroquest Technology Co, Ltd. All Rights Reserved. * Please read the associated COPYRIGHTS file for more details. * * THE SOFTWARE IS PROVIDED BY Acroquest Technolog Co., Ltd., * 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 HOLDER BE LIABLE FOR ANY * CLAIM, DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ package acromusashi.stream.ml.clustering.kmeans.state; /** * KMeans分散用Infinispan向けStateクラス<br> * 設定された「parallelismHint」の数だけ存在する。 * * @author kimura */ public class InfinispanKmeansState extends KmeansState { /** キャッシュ上のデータ生存期間のデフォルト値 */ private static final int DEFAULT_LIFESPAN = 600; /** logger */ private static final Logger logger = LoggerFactory.getLogger(InfinispanKmeansState.class); /** キャッシュ上のデータ生存期間(単位:秒) */ protected int lifespan = DEFAULT_LIFESPAN; /** 投入先のサーバ情報 */ protected String targetServer; /** 投入先キャッシュ名称 */ protected String cacheName; /** 状態を保存するベースキー */ protected String baseKey; /** Remoteキャッシュマネージャ */ protected transient RemoteCacheManager clientManager; /** 状態保存用キャッシュ */
protected transient RemoteCache<String, KmeansDataSet> stateCache;
acromusashi/acromusashi-stream-ml
src/main/java/acromusashi/stream/ml/clustering/kmeans/KmeansCreator.java
// Path: src/main/java/acromusashi/stream/ml/clustering/kmeans/entity/KmeansPoint.java // public class KmeansPoint implements Serializable // { // /** serialVersionUID */ // private static final long serialVersionUID = -5518876772129721631L; // // /** データ座標 */ // private double[] dataPoint; // // /** // * パラメータを指定せずにインスタンスを生成する。 // */ // public KmeansPoint() // {} // // /** // * @return the dataPoint // */ // public double[] getDataPoint() // { // return this.dataPoint; // } // // /** // * @param dataPoint the dataPoint to set // */ // public void setDataPoint(double[] dataPoint) // { // this.dataPoint = dataPoint; // } // // /** // * {@inheritDoc} // */ // @Override // public boolean equals(Object other) // { // if (this == other) // { // return true; // } // // if (!(other instanceof KmeansPoint)) // { // return false; // } // // KmeansPoint otherPoint = (KmeansPoint) other; // // for (int i = 0; i < this.dataPoint.length; ++i) // { // if (this.dataPoint[i] != otherPoint.getDataPoint()[i]) // { // return false; // } // } // // return true; // } // // /** // * {@inheritDoc} // */ // @Override // public int hashCode() // { // return MathUtils.hash(this.dataPoint); // } // // /** // * 文字列表現を返す。<br> // * StormからDRPC応答を生成するコンポーネント<br> // * (ReturnResultsReducer#complete(ReturnResultsState, TridentCollector))<br> // * に問題があり、JSON文字列とならない状態でレスポンスが生成されるため、結果をダブルクォートで囲っている。 // * // * @return 文字列表現 // */ // @Override // public String toString() // { // // TODO Stormの応答生成部の問題が対応された際にダブルクォートを削除 // String result = "\"" // + ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE) + "\""; // return result; // } // }
import java.util.Map; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import storm.trident.operation.BaseFunction; import storm.trident.operation.TridentCollector; import storm.trident.operation.TridentOperationContext; import storm.trident.tuple.TridentTuple; import acromusashi.stream.ml.clustering.kmeans.entity.KmeansPoint; import backtype.storm.tuple.Values;
/** * Copyright (c) Acroquest Technology Co, Ltd. All Rights Reserved. * Please read the associated COPYRIGHTS file for more details. * * THE SOFTWARE IS PROVIDED BY Acroquest Technolog Co., Ltd., * 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 HOLDER BE LIABLE FOR ANY * CLAIM, DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ package acromusashi.stream.ml.clustering.kmeans; /** * KMeansの対象ポイントを生成するFunctionクラス * * @author kimura */ public class KmeansCreator extends BaseFunction { /** serialVersionUID */ private static final long serialVersionUID = 4620883521921594615L; /** logger */ private static final Logger logger = LoggerFactory.getLogger(KmeansCreator.class); /** 読みこんだデータを分割する文字列 */ private String delimeter = ","; /** * パラメータを指定せずにインスタンスを生成する。 */ public KmeansCreator() {} /** * {@inheritDoc} */ @SuppressWarnings("rawtypes") @Override public void prepare(Map conf, TridentOperationContext context) { if (logger.isDebugEnabled() == true) { logger.debug("prepared started. taskIndex=" + context.getPartitionIndex() + ", taxkNum=" + context.numPartitions()); } } /** * {@inheritDoc} */ @Override public void execute(TridentTuple tuple, TridentCollector collector) { String receivedStr = tuple.getString(0); String[] splitedStr = StringUtils.split(receivedStr, this.delimeter); int dataNum = splitedStr.length; double[] points = new double[splitedStr.length]; try { for (int index = 0; index < dataNum; index++) { points[index] = Double.parseDouble(splitedStr[index].trim()); }
// Path: src/main/java/acromusashi/stream/ml/clustering/kmeans/entity/KmeansPoint.java // public class KmeansPoint implements Serializable // { // /** serialVersionUID */ // private static final long serialVersionUID = -5518876772129721631L; // // /** データ座標 */ // private double[] dataPoint; // // /** // * パラメータを指定せずにインスタンスを生成する。 // */ // public KmeansPoint() // {} // // /** // * @return the dataPoint // */ // public double[] getDataPoint() // { // return this.dataPoint; // } // // /** // * @param dataPoint the dataPoint to set // */ // public void setDataPoint(double[] dataPoint) // { // this.dataPoint = dataPoint; // } // // /** // * {@inheritDoc} // */ // @Override // public boolean equals(Object other) // { // if (this == other) // { // return true; // } // // if (!(other instanceof KmeansPoint)) // { // return false; // } // // KmeansPoint otherPoint = (KmeansPoint) other; // // for (int i = 0; i < this.dataPoint.length; ++i) // { // if (this.dataPoint[i] != otherPoint.getDataPoint()[i]) // { // return false; // } // } // // return true; // } // // /** // * {@inheritDoc} // */ // @Override // public int hashCode() // { // return MathUtils.hash(this.dataPoint); // } // // /** // * 文字列表現を返す。<br> // * StormからDRPC応答を生成するコンポーネント<br> // * (ReturnResultsReducer#complete(ReturnResultsState, TridentCollector))<br> // * に問題があり、JSON文字列とならない状態でレスポンスが生成されるため、結果をダブルクォートで囲っている。 // * // * @return 文字列表現 // */ // @Override // public String toString() // { // // TODO Stormの応答生成部の問題が対応された際にダブルクォートを削除 // String result = "\"" // + ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE) + "\""; // return result; // } // } // Path: src/main/java/acromusashi/stream/ml/clustering/kmeans/KmeansCreator.java import java.util.Map; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import storm.trident.operation.BaseFunction; import storm.trident.operation.TridentCollector; import storm.trident.operation.TridentOperationContext; import storm.trident.tuple.TridentTuple; import acromusashi.stream.ml.clustering.kmeans.entity.KmeansPoint; import backtype.storm.tuple.Values; /** * Copyright (c) Acroquest Technology Co, Ltd. All Rights Reserved. * Please read the associated COPYRIGHTS file for more details. * * THE SOFTWARE IS PROVIDED BY Acroquest Technolog Co., Ltd., * 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 HOLDER BE LIABLE FOR ANY * CLAIM, DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ package acromusashi.stream.ml.clustering.kmeans; /** * KMeansの対象ポイントを生成するFunctionクラス * * @author kimura */ public class KmeansCreator extends BaseFunction { /** serialVersionUID */ private static final long serialVersionUID = 4620883521921594615L; /** logger */ private static final Logger logger = LoggerFactory.getLogger(KmeansCreator.class); /** 読みこんだデータを分割する文字列 */ private String delimeter = ","; /** * パラメータを指定せずにインスタンスを生成する。 */ public KmeansCreator() {} /** * {@inheritDoc} */ @SuppressWarnings("rawtypes") @Override public void prepare(Map conf, TridentOperationContext context) { if (logger.isDebugEnabled() == true) { logger.debug("prepared started. taskIndex=" + context.getPartitionIndex() + ", taxkNum=" + context.numPartitions()); } } /** * {@inheritDoc} */ @Override public void execute(TridentTuple tuple, TridentCollector collector) { String receivedStr = tuple.getString(0); String[] splitedStr = StringUtils.split(receivedStr, this.delimeter); int dataNum = splitedStr.length; double[] points = new double[splitedStr.length]; try { for (int index = 0; index < dataNum; index++) { points[index] = Double.parseDouble(splitedStr[index].trim()); }
KmeansPoint result = new KmeansPoint();
acromusashi/acromusashi-stream-ml
src/main/java/acromusashi/stream/ml/anomaly/lof/state/InfinispanLofState.java
// Path: src/main/java/acromusashi/stream/ml/anomaly/lof/entity/LofDataSet.java // public class LofDataSet implements Serializable // { // /** serialVersionUID */ // private static final long serialVersionUID = 7589332742661081169L; // // /** 保持するデータIDのリスト */ // private List<String> dataIdList = new ArrayList<>(); // // /** 保持するデータID>データ値のマッピング */ // private Map<String, LofPoint> dataMap = new HashMap<>(); // // /** // * パラメータを指定せずにインスタンスを生成する。 // */ // public LofDataSet() // {} // // /** // * 保持するデータIDのリスト/データマッピングに値を追加する。 // * // * @param addedPoint 追加対象点 // */ // public void addData(LofPoint addedPoint) // { // this.dataIdList.add(addedPoint.getDataId()); // this.dataMap.put(addedPoint.getDataId(), addedPoint); // } // // /** // * 保持するデータIDのリスト/データマッピングに値を追加する。 // * // * @param deleteDataId 追加対象点 // */ // public void deleteData(String deleteDataId) // { // this.dataIdList.remove(deleteDataId); // this.dataMap.remove(deleteDataId); // } // // /** // * 対象エンティティのDeepCopyを作成する。 // * // * @return 対象エンティティのDeepCopy // */ // public LofDataSet deepCopy() // { // LofDataSet result = new LofDataSet(); // result.getDataIdList().addAll(this.dataIdList); // Collection<LofPoint> pointList = this.dataMap.values(); // for (LofPoint targetPoint : pointList) // { // result.getDataMap().put(targetPoint.getDataId(), targetPoint.deepCopy()); // } // // return result; // } // // /** // * @return the dataIdList // */ // public List<String> getDataIdList() // { // return this.dataIdList; // } // // /** // * @param dataIdList the dataIdList to set // */ // public void setDataIdList(List<String> dataIdList) // { // this.dataIdList = dataIdList; // } // // /** // * @return the dataMap // */ // public Map<String, LofPoint> getDataMap() // { // return this.dataMap; // } // // /** // * @param dataMap the dataMap to set // */ // public void setDataMap(Map<String, LofPoint> dataMap) // { // this.dataMap = dataMap; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() // { // String result = ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // return result; // } // }
import java.io.IOException; import java.util.Arrays; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commons.marshall.Marshaller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import acromusashi.stream.ml.anomaly.lof.entity.LofDataSet; import com.google.common.base.Joiner;
/** * Copyright (c) Acroquest Technology Co, Ltd. All Rights Reserved. * Please read the associated COPYRIGHTS file for more details. * * THE SOFTWARE IS PROVIDED BY Acroquest Technolog Co., Ltd., * 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 HOLDER BE LIABLE FOR ANY * CLAIM, DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ package acromusashi.stream.ml.anomaly.lof.state; /** * LOF分散用MapStateの保存先にInfinispanを用いたクラス<br> * 設定された「parallelismHint」の数だけ存在する。 * * @author kimura */ public class InfinispanLofState extends LofState { /** キャッシュ上のデータ生存期間のデフォルト値 */ private static final int DEFAULT_LIFESPAN = 600; /** logger */ private static final Logger logger = LoggerFactory.getLogger(InfinispanLofState.class); /** キャッシュ上のデータ生存期間(単位:秒) */ protected int lifespan = DEFAULT_LIFESPAN; /** 投入先のサーバ情報 */ protected String targetServer; /** 投入先キャッシュ名称 */ protected String cacheName; /** 状態を保存するベースキー */ protected String baseKey; /** Remoteキャッシュマネージャ */ protected transient RemoteCacheManager clientManager; /** 状態保存用キャッシュ */
// Path: src/main/java/acromusashi/stream/ml/anomaly/lof/entity/LofDataSet.java // public class LofDataSet implements Serializable // { // /** serialVersionUID */ // private static final long serialVersionUID = 7589332742661081169L; // // /** 保持するデータIDのリスト */ // private List<String> dataIdList = new ArrayList<>(); // // /** 保持するデータID>データ値のマッピング */ // private Map<String, LofPoint> dataMap = new HashMap<>(); // // /** // * パラメータを指定せずにインスタンスを生成する。 // */ // public LofDataSet() // {} // // /** // * 保持するデータIDのリスト/データマッピングに値を追加する。 // * // * @param addedPoint 追加対象点 // */ // public void addData(LofPoint addedPoint) // { // this.dataIdList.add(addedPoint.getDataId()); // this.dataMap.put(addedPoint.getDataId(), addedPoint); // } // // /** // * 保持するデータIDのリスト/データマッピングに値を追加する。 // * // * @param deleteDataId 追加対象点 // */ // public void deleteData(String deleteDataId) // { // this.dataIdList.remove(deleteDataId); // this.dataMap.remove(deleteDataId); // } // // /** // * 対象エンティティのDeepCopyを作成する。 // * // * @return 対象エンティティのDeepCopy // */ // public LofDataSet deepCopy() // { // LofDataSet result = new LofDataSet(); // result.getDataIdList().addAll(this.dataIdList); // Collection<LofPoint> pointList = this.dataMap.values(); // for (LofPoint targetPoint : pointList) // { // result.getDataMap().put(targetPoint.getDataId(), targetPoint.deepCopy()); // } // // return result; // } // // /** // * @return the dataIdList // */ // public List<String> getDataIdList() // { // return this.dataIdList; // } // // /** // * @param dataIdList the dataIdList to set // */ // public void setDataIdList(List<String> dataIdList) // { // this.dataIdList = dataIdList; // } // // /** // * @return the dataMap // */ // public Map<String, LofPoint> getDataMap() // { // return this.dataMap; // } // // /** // * @param dataMap the dataMap to set // */ // public void setDataMap(Map<String, LofPoint> dataMap) // { // this.dataMap = dataMap; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() // { // String result = ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); // return result; // } // } // Path: src/main/java/acromusashi/stream/ml/anomaly/lof/state/InfinispanLofState.java import java.io.IOException; import java.util.Arrays; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commons.marshall.Marshaller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import acromusashi.stream.ml.anomaly.lof.entity.LofDataSet; import com.google.common.base.Joiner; /** * Copyright (c) Acroquest Technology Co, Ltd. All Rights Reserved. * Please read the associated COPYRIGHTS file for more details. * * THE SOFTWARE IS PROVIDED BY Acroquest Technolog Co., Ltd., * 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 HOLDER BE LIABLE FOR ANY * CLAIM, DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ package acromusashi.stream.ml.anomaly.lof.state; /** * LOF分散用MapStateの保存先にInfinispanを用いたクラス<br> * 設定された「parallelismHint」の数だけ存在する。 * * @author kimura */ public class InfinispanLofState extends LofState { /** キャッシュ上のデータ生存期間のデフォルト値 */ private static final int DEFAULT_LIFESPAN = 600; /** logger */ private static final Logger logger = LoggerFactory.getLogger(InfinispanLofState.class); /** キャッシュ上のデータ生存期間(単位:秒) */ protected int lifespan = DEFAULT_LIFESPAN; /** 投入先のサーバ情報 */ protected String targetServer; /** 投入先キャッシュ名称 */ protected String cacheName; /** 状態を保存するベースキー */ protected String baseKey; /** Remoteキャッシュマネージャ */ protected transient RemoteCacheManager clientManager; /** 状態保存用キャッシュ */
protected transient RemoteCache<String, LofDataSet> stateCache;
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/company/CompanyDefaultDummyGenerator.java
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // }
import com.liferay.petra.string.StringBundler; import com.liferay.portal.instances.service.PortalInstancesLocalService; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.model.Company; import com.liferay.portal.kernel.service.CompanyLocalService; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.company; /** * Company Generator * * @author Yasuyuki Takeo */ @Component(immediate = true, service = CompanyDefaultDummyGenerator.class) public class CompanyDefaultDummyGenerator extends DummyGenerator<CompanyContext> { private static final Log _log = LogFactoryUtil.getLog(CompanyDefaultDummyGenerator.class); @Reference private CompanyLocalService _companyLocalService; @Reference private PortalInstancesLocalService _portalInstancesLocalService; @Override protected CompanyContext getContext(ActionRequest request) throws Exception { return new CompanyContext(request); } @Override protected void exec(ActionRequest request, CompanyContext paramContext) throws Exception { //Tracking progress start
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // } // Path: src/main/java/com/liferay/support/tools/company/CompanyDefaultDummyGenerator.java import com.liferay.petra.string.StringBundler; import com.liferay.portal.instances.service.PortalInstancesLocalService; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.model.Company; import com.liferay.portal.kernel.service.CompanyLocalService; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.company; /** * Company Generator * * @author Yasuyuki Takeo */ @Component(immediate = true, service = CompanyDefaultDummyGenerator.class) public class CompanyDefaultDummyGenerator extends DummyGenerator<CompanyContext> { private static final Log _log = LogFactoryUtil.getLog(CompanyDefaultDummyGenerator.class); @Reference private CompanyLocalService _companyLocalService; @Reference private PortalInstancesLocalService _portalInstancesLocalService; @Override protected CompanyContext getContext(ActionRequest request) throws Exception { return new CompanyContext(request); } @Override protected void exec(ActionRequest request, CompanyContext paramContext) throws Exception { //Tracking progress start
ProgressManager progressManager = new ProgressManager();
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/organization/OrgDummyFactory.java
// Path: src/main/java/com/liferay/support/tools/common/DummyFactory.java // public abstract class DummyFactory { // abstract public DummyGenerator<?> create(ActionRequest request); // } // // Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // }
import com.liferay.support.tools.common.DummyFactory; import com.liferay.support.tools.common.DummyGenerator; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.organization; /** * Organization Factory * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = OrgDummyFactory.class) public class OrgDummyFactory extends DummyFactory { @Override
// Path: src/main/java/com/liferay/support/tools/common/DummyFactory.java // public abstract class DummyFactory { // abstract public DummyGenerator<?> create(ActionRequest request); // } // // Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // Path: src/main/java/com/liferay/support/tools/organization/OrgDummyFactory.java import com.liferay.support.tools.common.DummyFactory; import com.liferay.support.tools.common.DummyGenerator; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.organization; /** * Organization Factory * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = OrgDummyFactory.class) public class OrgDummyFactory extends DummyFactory { @Override
public DummyGenerator<OrgContext> create(ActionRequest request) {
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/document/library/DLDefaultDummyGenerator.java
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // }
import com.liferay.document.library.kernel.exception.DuplicateFileEntryException; import com.liferay.document.library.kernel.model.DLFileEntry; import com.liferay.document.library.kernel.model.DLFolder; import com.liferay.document.library.kernel.service.DLAppLocalService; import com.liferay.document.library.kernel.service.DLFileEntryLocalService; import com.liferay.document.library.kernel.service.DLFolderLocalService; import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.dao.orm.QueryUtil; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.repository.model.FileEntry; import com.liferay.portal.kernel.theme.ThemeDisplay; import com.liferay.portal.kernel.util.ContentTypes; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.util.TempFileEntryUtil; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import java.util.List; import java.util.stream.Collectors; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.document.library; /** * Document Library Generator * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = DLDefaultDummyGenerator.class) public class DLDefaultDummyGenerator extends DummyGenerator<DLContext> { @Override protected DLContext getContext(ActionRequest request) { return new DLContext(request); } @Override protected void exec(ActionRequest request, DLContext paramContext) throws PortalException { //Tracking progress start
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // } // Path: src/main/java/com/liferay/support/tools/document/library/DLDefaultDummyGenerator.java import com.liferay.document.library.kernel.exception.DuplicateFileEntryException; import com.liferay.document.library.kernel.model.DLFileEntry; import com.liferay.document.library.kernel.model.DLFolder; import com.liferay.document.library.kernel.service.DLAppLocalService; import com.liferay.document.library.kernel.service.DLFileEntryLocalService; import com.liferay.document.library.kernel.service.DLFolderLocalService; import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.dao.orm.QueryUtil; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.repository.model.FileEntry; import com.liferay.portal.kernel.theme.ThemeDisplay; import com.liferay.portal.kernel.util.ContentTypes; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.util.TempFileEntryUtil; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import java.util.List; import java.util.stream.Collectors; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.document.library; /** * Document Library Generator * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = DLDefaultDummyGenerator.class) public class DLDefaultDummyGenerator extends DummyGenerator<DLContext> { @Override protected DLContext getContext(ActionRequest request) { return new DLContext(request); } @Override protected void exec(ActionRequest request, DLContext paramContext) throws PortalException { //Tracking progress start
ProgressManager progressManager = new ProgressManager();
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/organization/OrgDefaultDummyGenerator.java
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // }
import com.liferay.portal.kernel.exception.DuplicateOrganizationException; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.service.OrganizationLocalService; import com.liferay.portal.kernel.util.Portal; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.organization; /** * Organization Generator * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = OrgDefaultDummyGenerator.class) public class OrgDefaultDummyGenerator extends DummyGenerator<OrgContext> { @Override protected OrgContext getContext(ActionRequest request) { return new OrgContext(request); } @Override protected void exec(ActionRequest request, OrgContext paramContext) throws PortalException { //Tracking progress start
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // } // Path: src/main/java/com/liferay/support/tools/organization/OrgDefaultDummyGenerator.java import com.liferay.portal.kernel.exception.DuplicateOrganizationException; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.service.OrganizationLocalService; import com.liferay.portal.kernel.util.Portal; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.organization; /** * Organization Generator * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = OrgDefaultDummyGenerator.class) public class OrgDefaultDummyGenerator extends DummyGenerator<OrgContext> { @Override protected OrgContext getContext(ActionRequest request) { return new OrgContext(request); } @Override protected void exec(ActionRequest request, OrgContext paramContext) throws PortalException { //Tracking progress start
ProgressManager progressManager = new ProgressManager();
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/site/SiteDefaultDummyGenerator.java
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // }
import com.liferay.petra.string.StringBundler; import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.exception.DuplicateGroupException; import com.liferay.portal.kernel.exception.GroupKeyException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.model.Group; import com.liferay.portal.kernel.model.GroupConstants; import com.liferay.portal.kernel.service.GroupLocalService; import com.liferay.portal.kernel.util.LocaleUtil; import com.liferay.sites.kernel.util.SitesUtil; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.site; /** * Sites Generator * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = SiteDefaultDummyGenerator.class) public class SiteDefaultDummyGenerator extends DummyGenerator<SiteContext> { @Override protected SiteContext getContext(ActionRequest request) { return new SiteContext(request); } @Override protected void exec(ActionRequest request, SiteContext paramContext) throws Exception { //Tracking progress start
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // } // Path: src/main/java/com/liferay/support/tools/site/SiteDefaultDummyGenerator.java import com.liferay.petra.string.StringBundler; import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.exception.DuplicateGroupException; import com.liferay.portal.kernel.exception.GroupKeyException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.model.Group; import com.liferay.portal.kernel.model.GroupConstants; import com.liferay.portal.kernel.service.GroupLocalService; import com.liferay.portal.kernel.util.LocaleUtil; import com.liferay.sites.kernel.util.SitesUtil; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.site; /** * Sites Generator * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = SiteDefaultDummyGenerator.class) public class SiteDefaultDummyGenerator extends DummyGenerator<SiteContext> { @Override protected SiteContext getContext(ActionRequest request) { return new SiteContext(request); } @Override protected void exec(ActionRequest request, SiteContext paramContext) throws Exception { //Tracking progress start
ProgressManager progressManager = new ProgressManager();
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/category/VocabularyDefaultDummyGenerator.java
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // }
import com.liferay.asset.kernel.exception.DuplicateVocabularyException; import com.liferay.asset.kernel.service.AssetVocabularyLocalService; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.category; /** * Vocabulary Generator * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = VocabularyDefaultDummyGenerator.class) public class VocabularyDefaultDummyGenerator extends DummyGenerator<CategoryContext> { @Override protected CategoryContext getContext(ActionRequest request) { return new CategoryContext(request); } @Override protected void exec(ActionRequest request, CategoryContext paramContext) throws PortalException { //Tracking progress start
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // } // Path: src/main/java/com/liferay/support/tools/category/VocabularyDefaultDummyGenerator.java import com.liferay.asset.kernel.exception.DuplicateVocabularyException; import com.liferay.asset.kernel.service.AssetVocabularyLocalService; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.category; /** * Vocabulary Generator * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = VocabularyDefaultDummyGenerator.class) public class VocabularyDefaultDummyGenerator extends DummyGenerator<CategoryContext> { @Override protected CategoryContext getContext(ActionRequest request) { return new CategoryContext(request); } @Override protected void exec(ActionRequest request, CategoryContext paramContext) throws PortalException { //Tracking progress start
ProgressManager progressManager = new ProgressManager();
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/user/UserDummyFactory.java
// Path: src/main/java/com/liferay/support/tools/common/DummyFactory.java // public abstract class DummyFactory { // abstract public DummyGenerator<?> create(ActionRequest request); // } // // Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // }
import com.liferay.support.tools.common.DummyFactory; import com.liferay.support.tools.common.DummyGenerator; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.user; /** * User Factory * * @author Yasuyuki Takeo */ @Component(immediate = true, service = UserDummyFactory.class) public class UserDummyFactory extends DummyFactory { @Override
// Path: src/main/java/com/liferay/support/tools/common/DummyFactory.java // public abstract class DummyFactory { // abstract public DummyGenerator<?> create(ActionRequest request); // } // // Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // Path: src/main/java/com/liferay/support/tools/user/UserDummyFactory.java import com.liferay.support.tools.common.DummyFactory; import com.liferay.support.tools.common.DummyGenerator; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.user; /** * User Factory * * @author Yasuyuki Takeo */ @Component(immediate = true, service = UserDummyFactory.class) public class UserDummyFactory extends DummyFactory { @Override
public DummyGenerator<UserContext> create(ActionRequest request) {
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/blogs/BlogsDummyFactory.java
// Path: src/main/java/com/liferay/support/tools/common/DummyFactory.java // public abstract class DummyFactory { // abstract public DummyGenerator<?> create(ActionRequest request); // } // // Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // }
import com.liferay.support.tools.common.DummyFactory; import com.liferay.support.tools.common.DummyGenerator; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.blogs; /** * Blogs post dummy factory * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = BlogsDummyFactory.class) public class BlogsDummyFactory extends DummyFactory { @Override
// Path: src/main/java/com/liferay/support/tools/common/DummyFactory.java // public abstract class DummyFactory { // abstract public DummyGenerator<?> create(ActionRequest request); // } // // Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // Path: src/main/java/com/liferay/support/tools/blogs/BlogsDummyFactory.java import com.liferay.support.tools.common.DummyFactory; import com.liferay.support.tools.common.DummyGenerator; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.blogs; /** * Blogs post dummy factory * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = BlogsDummyFactory.class) public class BlogsDummyFactory extends DummyFactory { @Override
public DummyGenerator<BlogsContext> create(ActionRequest request) {
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/user/UserDefaultDummyGenerator.java
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // }
import com.liferay.portal.kernel.exception.GroupFriendlyURLException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.model.User; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.util.Validator; import com.liferay.sites.kernel.util.SitesUtil; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.user; /** * User Generator * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = UserDefaultDummyGenerator.class) public class UserDefaultDummyGenerator extends DummyGenerator<UserContext> { @Override protected UserContext getContext(ActionRequest request) throws Exception { return new UserContext(request); } @Override protected void exec(ActionRequest request, UserContext paramContext) throws Exception { // Tracking progress start
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // } // Path: src/main/java/com/liferay/support/tools/user/UserDefaultDummyGenerator.java import com.liferay.portal.kernel.exception.GroupFriendlyURLException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.model.User; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.util.Validator; import com.liferay.sites.kernel.util.SitesUtil; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.user; /** * User Generator * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = UserDefaultDummyGenerator.class) public class UserDefaultDummyGenerator extends DummyGenerator<UserContext> { @Override protected UserContext getContext(ActionRequest request) throws Exception { return new UserContext(request); } @Override protected void exec(ActionRequest request, UserContext paramContext) throws Exception { // Tracking progress start
ProgressManager progressManager = new ProgressManager();
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/site/SiteDummyFactory.java
// Path: src/main/java/com/liferay/support/tools/common/DummyFactory.java // public abstract class DummyFactory { // abstract public DummyGenerator<?> create(ActionRequest request); // } // // Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // }
import com.liferay.support.tools.common.DummyFactory; import com.liferay.support.tools.common.DummyGenerator; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.site; /** * Site Factory * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = SiteDummyFactory.class) public class SiteDummyFactory extends DummyFactory { @Override
// Path: src/main/java/com/liferay/support/tools/common/DummyFactory.java // public abstract class DummyFactory { // abstract public DummyGenerator<?> create(ActionRequest request); // } // // Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // Path: src/main/java/com/liferay/support/tools/site/SiteDummyFactory.java import com.liferay.support.tools.common.DummyFactory; import com.liferay.support.tools.common.DummyGenerator; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.site; /** * Site Factory * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = SiteDummyFactory.class) public class SiteDummyFactory extends DummyFactory { @Override
public DummyGenerator<SiteContext> create(ActionRequest request) {
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/wiki/WikiNodeDummyGenerator.java
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // }
import com.liferay.portal.kernel.service.GroupLocalService; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.workflow.WorkflowConstants; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import com.liferay.wiki.service.WikiNodeLocalService; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.wiki; @Component(immediate = true, service = WikiNodeDummyGenerator.class) public class WikiNodeDummyGenerator extends DummyGenerator<WikiContext> { @Override protected WikiContext getContext(ActionRequest request) throws Exception { return new WikiContext(request); } @Override protected void exec(ActionRequest request, WikiContext paramContext) throws Exception { // Tracking progress start
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // } // Path: src/main/java/com/liferay/support/tools/wiki/WikiNodeDummyGenerator.java import com.liferay.portal.kernel.service.GroupLocalService; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.workflow.WorkflowConstants; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import com.liferay.wiki.service.WikiNodeLocalService; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.wiki; @Component(immediate = true, service = WikiNodeDummyGenerator.class) public class WikiNodeDummyGenerator extends DummyGenerator<WikiContext> { @Override protected WikiContext getContext(ActionRequest request) throws Exception { return new WikiContext(request); } @Override protected void exec(ActionRequest request, WikiContext paramContext) throws Exception { // Tracking progress start
ProgressManager progressManager = new ProgressManager();
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/journal/JournalContext.java
// Path: src/main/java/com/liferay/support/tools/common/ParamContext.java // public abstract class ParamContext { // // protected ThemeDisplay themeDisplay; // protected ServiceContext serviceContext; // // public ThemeDisplay getThemeDisplay() { // return themeDisplay; // } // // public void setThemeDisplay(ThemeDisplay themeDisplay) { // this.themeDisplay = themeDisplay; // } // // public ServiceContext getServiceContext() { // return serviceContext; // } // // public void setServiceContext(ServiceContext serviceContext) { // this.serviceContext = serviceContext; // } // // } // // Path: src/main/java/com/liferay/support/tools/utils/CommonUtil.java // @Component(immediate = true, service = CommonUtil.class) // public class CommonUtil { // // /** // * Page Command Pairs // * // * @return jsp file name corresponding to the command. // */ // public Map<String, String> getPageFromMode() { // return LDFPortletKeys.renderJSPs; // } // // /** // * Convert // * @param source // * @return // */ // static public String[] convertToStringArray(String source) { // if(source.length() == 0) { // return new String[0]; // } // // return source.split(",",0); // } // // /** // * Convert string array to long array // * // * @param source String array of ids // * @return long array of ids // */ // static public long[] convertStringToLongArray(String[] source) { // if (Validator.isNull(source) || source.length <= 0) { // return null; // } // // return Arrays.stream(source).distinct().mapToLong(Long::parseLong).toArray(); // } // // /** // * Filter roles // * // * Depending on role types, the processes to apply roles are different. This // * method filter either Organization / Site roles or Regular roles. // * // * @param roleIds role ids. This can be mix of reguler / organization / site roles. // * @return Filtered roleids in each array. // * @throws PortalException // */ // public Map<Integer, List<Role>> filterRoles(long[] roleIds) throws PortalException { // // if (Validator.isNull(roleIds) || roleIds.length == 0) { // return new ConcurrentHashMap<Integer, List<Role>>(); // } // // List<Role> roles = _roleLocalService.getRoles(roleIds); // return roles.stream().collect(Collectors.groupingBy(Role::getType)); // } // // // /** // * Create Faker // * // * @param locale Language to create Faker object based on. // * @return Faker object. // */ // public Faker createFaker(String locale) { // // For generating dummy user name // Faker faker = new Faker(new Locale(Locale.ENGLISH.toLanguageTag())); // // try { // Faker fakerTmp = new Faker(new Locale(locale)); // faker = fakerTmp; // } catch (Exception e) { // e.printStackTrace(); // } // // return faker; // } // // @Reference // private RoleLocalService _roleLocalService; // // private static final Log _log = LogFactoryUtil.getLog(CommonUtil.class); // }
import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.theme.ThemeDisplay; import com.liferay.portal.kernel.util.LocaleUtil; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.support.tools.common.ParamContext; import com.liferay.support.tools.utils.CommonUtil; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.portlet.ActionRequest;
/** * Constructor * * @param actionRequest * @throws PortalException */ public JournalContext(ActionRequest actionRequest) throws PortalException { ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); // Fetch data numberOfArticles = ParamUtil.getLong(actionRequest, "numberOfArticles", 1); baseTitle = ParamUtil.getString(actionRequest, "baseTitle", ""); baseArticle = ParamUtil.getString(actionRequest, "baseArticle", ""); folderId = ParamUtil.getLong(actionRequest, "folderId", 0); totalParagraphs = ParamUtil.getInteger(actionRequest, "totalParagraphs", 0); titleWords = ParamUtil.getInteger(actionRequest, "titleWords", 0); randomAmount = ParamUtil.getInteger(actionRequest, "randomAmount", 0); createContentsType = ParamUtil.getLong(actionRequest, "createContentsType", 0); linkLists = ParamUtil.getString(actionRequest, "linkLists", ""); ddmStructureId = ParamUtil.getLong(actionRequest, "ddmStructureId", 0); ddmTemplateId = ParamUtil.getLong(actionRequest, "ddmTemplateId", 0); // Locales String[] defLang = { LocaleUtil.getDefault().toString() }; locales = ParamUtil.getStringValues(actionRequest, "locales", defLang); // Sites String[] groupsStrIds = ParamUtil.getStringValues(actionRequest, "groupIds", new String[] { String.valueOf(themeDisplay.getScopeGroupId()) });
// Path: src/main/java/com/liferay/support/tools/common/ParamContext.java // public abstract class ParamContext { // // protected ThemeDisplay themeDisplay; // protected ServiceContext serviceContext; // // public ThemeDisplay getThemeDisplay() { // return themeDisplay; // } // // public void setThemeDisplay(ThemeDisplay themeDisplay) { // this.themeDisplay = themeDisplay; // } // // public ServiceContext getServiceContext() { // return serviceContext; // } // // public void setServiceContext(ServiceContext serviceContext) { // this.serviceContext = serviceContext; // } // // } // // Path: src/main/java/com/liferay/support/tools/utils/CommonUtil.java // @Component(immediate = true, service = CommonUtil.class) // public class CommonUtil { // // /** // * Page Command Pairs // * // * @return jsp file name corresponding to the command. // */ // public Map<String, String> getPageFromMode() { // return LDFPortletKeys.renderJSPs; // } // // /** // * Convert // * @param source // * @return // */ // static public String[] convertToStringArray(String source) { // if(source.length() == 0) { // return new String[0]; // } // // return source.split(",",0); // } // // /** // * Convert string array to long array // * // * @param source String array of ids // * @return long array of ids // */ // static public long[] convertStringToLongArray(String[] source) { // if (Validator.isNull(source) || source.length <= 0) { // return null; // } // // return Arrays.stream(source).distinct().mapToLong(Long::parseLong).toArray(); // } // // /** // * Filter roles // * // * Depending on role types, the processes to apply roles are different. This // * method filter either Organization / Site roles or Regular roles. // * // * @param roleIds role ids. This can be mix of reguler / organization / site roles. // * @return Filtered roleids in each array. // * @throws PortalException // */ // public Map<Integer, List<Role>> filterRoles(long[] roleIds) throws PortalException { // // if (Validator.isNull(roleIds) || roleIds.length == 0) { // return new ConcurrentHashMap<Integer, List<Role>>(); // } // // List<Role> roles = _roleLocalService.getRoles(roleIds); // return roles.stream().collect(Collectors.groupingBy(Role::getType)); // } // // // /** // * Create Faker // * // * @param locale Language to create Faker object based on. // * @return Faker object. // */ // public Faker createFaker(String locale) { // // For generating dummy user name // Faker faker = new Faker(new Locale(Locale.ENGLISH.toLanguageTag())); // // try { // Faker fakerTmp = new Faker(new Locale(locale)); // faker = fakerTmp; // } catch (Exception e) { // e.printStackTrace(); // } // // return faker; // } // // @Reference // private RoleLocalService _roleLocalService; // // private static final Log _log = LogFactoryUtil.getLog(CommonUtil.class); // } // Path: src/main/java/com/liferay/support/tools/journal/JournalContext.java import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.theme.ThemeDisplay; import com.liferay.portal.kernel.util.LocaleUtil; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.support.tools.common.ParamContext; import com.liferay.support.tools.utils.CommonUtil; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.portlet.ActionRequest; /** * Constructor * * @param actionRequest * @throws PortalException */ public JournalContext(ActionRequest actionRequest) throws PortalException { ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); // Fetch data numberOfArticles = ParamUtil.getLong(actionRequest, "numberOfArticles", 1); baseTitle = ParamUtil.getString(actionRequest, "baseTitle", ""); baseArticle = ParamUtil.getString(actionRequest, "baseArticle", ""); folderId = ParamUtil.getLong(actionRequest, "folderId", 0); totalParagraphs = ParamUtil.getInteger(actionRequest, "totalParagraphs", 0); titleWords = ParamUtil.getInteger(actionRequest, "titleWords", 0); randomAmount = ParamUtil.getInteger(actionRequest, "randomAmount", 0); createContentsType = ParamUtil.getLong(actionRequest, "createContentsType", 0); linkLists = ParamUtil.getString(actionRequest, "linkLists", ""); ddmStructureId = ParamUtil.getLong(actionRequest, "ddmStructureId", 0); ddmTemplateId = ParamUtil.getLong(actionRequest, "ddmTemplateId", 0); // Locales String[] defLang = { LocaleUtil.getDefault().toString() }; locales = ParamUtil.getStringValues(actionRequest, "locales", defLang); // Sites String[] groupsStrIds = ParamUtil.getStringValues(actionRequest, "groupIds", new String[] { String.valueOf(themeDisplay.getScopeGroupId()) });
groupIds = CommonUtil.convertStringToLongArray(groupsStrIds);
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/user/UserContext.java
// Path: src/main/java/com/liferay/support/tools/common/ParamContext.java // public abstract class ParamContext { // // protected ThemeDisplay themeDisplay; // protected ServiceContext serviceContext; // // public ThemeDisplay getThemeDisplay() { // return themeDisplay; // } // // public void setThemeDisplay(ThemeDisplay themeDisplay) { // this.themeDisplay = themeDisplay; // } // // public ServiceContext getServiceContext() { // return serviceContext; // } // // public void setServiceContext(ServiceContext serviceContext) { // this.serviceContext = serviceContext; // } // // } // // Path: src/main/java/com/liferay/support/tools/utils/CommonUtil.java // @Component(immediate = true, service = CommonUtil.class) // public class CommonUtil { // // /** // * Page Command Pairs // * // * @return jsp file name corresponding to the command. // */ // public Map<String, String> getPageFromMode() { // return LDFPortletKeys.renderJSPs; // } // // /** // * Convert // * @param source // * @return // */ // static public String[] convertToStringArray(String source) { // if(source.length() == 0) { // return new String[0]; // } // // return source.split(",",0); // } // // /** // * Convert string array to long array // * // * @param source String array of ids // * @return long array of ids // */ // static public long[] convertStringToLongArray(String[] source) { // if (Validator.isNull(source) || source.length <= 0) { // return null; // } // // return Arrays.stream(source).distinct().mapToLong(Long::parseLong).toArray(); // } // // /** // * Filter roles // * // * Depending on role types, the processes to apply roles are different. This // * method filter either Organization / Site roles or Regular roles. // * // * @param roleIds role ids. This can be mix of reguler / organization / site roles. // * @return Filtered roleids in each array. // * @throws PortalException // */ // public Map<Integer, List<Role>> filterRoles(long[] roleIds) throws PortalException { // // if (Validator.isNull(roleIds) || roleIds.length == 0) { // return new ConcurrentHashMap<Integer, List<Role>>(); // } // // List<Role> roles = _roleLocalService.getRoles(roleIds); // return roles.stream().collect(Collectors.groupingBy(Role::getType)); // } // // // /** // * Create Faker // * // * @param locale Language to create Faker object based on. // * @return Faker object. // */ // public Faker createFaker(String locale) { // // For generating dummy user name // Faker faker = new Faker(new Locale(Locale.ENGLISH.toLanguageTag())); // // try { // Faker fakerTmp = new Faker(new Locale(locale)); // faker = fakerTmp; // } catch (Exception e) { // e.printStackTrace(); // } // // return faker; // } // // @Reference // private RoleLocalService _roleLocalService; // // private static final Log _log = LogFactoryUtil.getLog(CommonUtil.class); // }
import com.liferay.announcements.kernel.model.AnnouncementsDelivery; import com.liferay.announcements.kernel.model.AnnouncementsEntryConstants; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.model.Group; import com.liferay.portal.kernel.service.ServiceContext; import com.liferay.portal.kernel.service.ServiceContextFactory; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portlet.announcements.model.impl.AnnouncementsDeliveryImpl; import com.liferay.support.tools.common.ParamContext; import com.liferay.support.tools.utils.CommonUtil; import java.util.ArrayList; import java.util.List; import javax.portlet.ActionRequest;
package com.liferay.support.tools.user; public class UserContext extends ParamContext { public UserContext(ActionRequest actionRequest) throws PortalException { // Fetch data numberOfusers = ParamUtil.getLong(actionRequest, "numberOfusers", 0); baseScreenName = ParamUtil.getString(actionRequest, "baseScreenName", ""); baseDomain = ParamUtil.getString(actionRequest, "baseDomain", "liferay.com"); male = ParamUtil.getBoolean(actionRequest, "male", true); fakerEnable = ParamUtil.getBoolean(actionRequest, "fakerEnable", false); password = ParamUtil.getString(actionRequest, "password", "test"); locale = ParamUtil.getString(actionRequest, "locale", "en"); autoUserPreLogin = ParamUtil.getBoolean(actionRequest, "autoUserPreLogin", false); // Organization String[] organizations = ParamUtil.getStringValues(actionRequest, "organizations", null);
// Path: src/main/java/com/liferay/support/tools/common/ParamContext.java // public abstract class ParamContext { // // protected ThemeDisplay themeDisplay; // protected ServiceContext serviceContext; // // public ThemeDisplay getThemeDisplay() { // return themeDisplay; // } // // public void setThemeDisplay(ThemeDisplay themeDisplay) { // this.themeDisplay = themeDisplay; // } // // public ServiceContext getServiceContext() { // return serviceContext; // } // // public void setServiceContext(ServiceContext serviceContext) { // this.serviceContext = serviceContext; // } // // } // // Path: src/main/java/com/liferay/support/tools/utils/CommonUtil.java // @Component(immediate = true, service = CommonUtil.class) // public class CommonUtil { // // /** // * Page Command Pairs // * // * @return jsp file name corresponding to the command. // */ // public Map<String, String> getPageFromMode() { // return LDFPortletKeys.renderJSPs; // } // // /** // * Convert // * @param source // * @return // */ // static public String[] convertToStringArray(String source) { // if(source.length() == 0) { // return new String[0]; // } // // return source.split(",",0); // } // // /** // * Convert string array to long array // * // * @param source String array of ids // * @return long array of ids // */ // static public long[] convertStringToLongArray(String[] source) { // if (Validator.isNull(source) || source.length <= 0) { // return null; // } // // return Arrays.stream(source).distinct().mapToLong(Long::parseLong).toArray(); // } // // /** // * Filter roles // * // * Depending on role types, the processes to apply roles are different. This // * method filter either Organization / Site roles or Regular roles. // * // * @param roleIds role ids. This can be mix of reguler / organization / site roles. // * @return Filtered roleids in each array. // * @throws PortalException // */ // public Map<Integer, List<Role>> filterRoles(long[] roleIds) throws PortalException { // // if (Validator.isNull(roleIds) || roleIds.length == 0) { // return new ConcurrentHashMap<Integer, List<Role>>(); // } // // List<Role> roles = _roleLocalService.getRoles(roleIds); // return roles.stream().collect(Collectors.groupingBy(Role::getType)); // } // // // /** // * Create Faker // * // * @param locale Language to create Faker object based on. // * @return Faker object. // */ // public Faker createFaker(String locale) { // // For generating dummy user name // Faker faker = new Faker(new Locale(Locale.ENGLISH.toLanguageTag())); // // try { // Faker fakerTmp = new Faker(new Locale(locale)); // faker = fakerTmp; // } catch (Exception e) { // e.printStackTrace(); // } // // return faker; // } // // @Reference // private RoleLocalService _roleLocalService; // // private static final Log _log = LogFactoryUtil.getLog(CommonUtil.class); // } // Path: src/main/java/com/liferay/support/tools/user/UserContext.java import com.liferay.announcements.kernel.model.AnnouncementsDelivery; import com.liferay.announcements.kernel.model.AnnouncementsEntryConstants; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.model.Group; import com.liferay.portal.kernel.service.ServiceContext; import com.liferay.portal.kernel.service.ServiceContextFactory; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portlet.announcements.model.impl.AnnouncementsDeliveryImpl; import com.liferay.support.tools.common.ParamContext; import com.liferay.support.tools.utils.CommonUtil; import java.util.ArrayList; import java.util.List; import javax.portlet.ActionRequest; package com.liferay.support.tools.user; public class UserContext extends ParamContext { public UserContext(ActionRequest actionRequest) throws PortalException { // Fetch data numberOfusers = ParamUtil.getLong(actionRequest, "numberOfusers", 0); baseScreenName = ParamUtil.getString(actionRequest, "baseScreenName", ""); baseDomain = ParamUtil.getString(actionRequest, "baseDomain", "liferay.com"); male = ParamUtil.getBoolean(actionRequest, "male", true); fakerEnable = ParamUtil.getBoolean(actionRequest, "fakerEnable", false); password = ParamUtil.getString(actionRequest, "password", "test"); locale = ParamUtil.getString(actionRequest, "locale", "en"); autoUserPreLogin = ParamUtil.getBoolean(actionRequest, "autoUserPreLogin", false); // Organization String[] organizations = ParamUtil.getStringValues(actionRequest, "organizations", null);
organizationIds = CommonUtil.convertStringToLongArray(organizations);
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/blogs/BlogsContext.java
// Path: src/main/java/com/liferay/support/tools/common/ParamContext.java // public abstract class ParamContext { // // protected ThemeDisplay themeDisplay; // protected ServiceContext serviceContext; // // public ThemeDisplay getThemeDisplay() { // return themeDisplay; // } // // public void setThemeDisplay(ThemeDisplay themeDisplay) { // this.themeDisplay = themeDisplay; // } // // public ServiceContext getServiceContext() { // return serviceContext; // } // // public void setServiceContext(ServiceContext serviceContext) { // this.serviceContext = serviceContext; // } // // } // // Path: src/main/java/com/liferay/support/tools/utils/CommonUtil.java // @Component(immediate = true, service = CommonUtil.class) // public class CommonUtil { // // /** // * Page Command Pairs // * // * @return jsp file name corresponding to the command. // */ // public Map<String, String> getPageFromMode() { // return LDFPortletKeys.renderJSPs; // } // // /** // * Convert // * @param source // * @return // */ // static public String[] convertToStringArray(String source) { // if(source.length() == 0) { // return new String[0]; // } // // return source.split(",",0); // } // // /** // * Convert string array to long array // * // * @param source String array of ids // * @return long array of ids // */ // static public long[] convertStringToLongArray(String[] source) { // if (Validator.isNull(source) || source.length <= 0) { // return null; // } // // return Arrays.stream(source).distinct().mapToLong(Long::parseLong).toArray(); // } // // /** // * Filter roles // * // * Depending on role types, the processes to apply roles are different. This // * method filter either Organization / Site roles or Regular roles. // * // * @param roleIds role ids. This can be mix of reguler / organization / site roles. // * @return Filtered roleids in each array. // * @throws PortalException // */ // public Map<Integer, List<Role>> filterRoles(long[] roleIds) throws PortalException { // // if (Validator.isNull(roleIds) || roleIds.length == 0) { // return new ConcurrentHashMap<Integer, List<Role>>(); // } // // List<Role> roles = _roleLocalService.getRoles(roleIds); // return roles.stream().collect(Collectors.groupingBy(Role::getType)); // } // // // /** // * Create Faker // * // * @param locale Language to create Faker object based on. // * @return Faker object. // */ // public Faker createFaker(String locale) { // // For generating dummy user name // Faker faker = new Faker(new Locale(Locale.ENGLISH.toLanguageTag())); // // try { // Faker fakerTmp = new Faker(new Locale(locale)); // faker = fakerTmp; // } catch (Exception e) { // e.printStackTrace(); // } // // return faker; // } // // @Reference // private RoleLocalService _roleLocalService; // // private static final Log _log = LogFactoryUtil.getLog(CommonUtil.class); // }
import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.support.tools.common.ParamContext; import com.liferay.support.tools.utils.CommonUtil; import javax.portlet.ActionRequest;
package com.liferay.support.tools.blogs; public class BlogsContext extends ParamContext { private long numberOfPosts = 0; private String baseTitle = ""; private String contents = ""; private long userId = 0; private long groupId = 0; private String[] allowTrackbacks; private boolean allowPingbacks; public BlogsContext(ActionRequest actionRequest) { //Fetch data numberOfPosts = ParamUtil.getLong(actionRequest, "numberOfPosts",0); baseTitle = ParamUtil.getString(actionRequest, "baseTitle",""); contents = ParamUtil.getString(actionRequest, "contents",""); userId = ParamUtil.getLong(actionRequest, "userId",0); groupId = ParamUtil.getLong(actionRequest, "groupId",0); String tempPings = ParamUtil.getString(actionRequest, "allowTrackbacks","");
// Path: src/main/java/com/liferay/support/tools/common/ParamContext.java // public abstract class ParamContext { // // protected ThemeDisplay themeDisplay; // protected ServiceContext serviceContext; // // public ThemeDisplay getThemeDisplay() { // return themeDisplay; // } // // public void setThemeDisplay(ThemeDisplay themeDisplay) { // this.themeDisplay = themeDisplay; // } // // public ServiceContext getServiceContext() { // return serviceContext; // } // // public void setServiceContext(ServiceContext serviceContext) { // this.serviceContext = serviceContext; // } // // } // // Path: src/main/java/com/liferay/support/tools/utils/CommonUtil.java // @Component(immediate = true, service = CommonUtil.class) // public class CommonUtil { // // /** // * Page Command Pairs // * // * @return jsp file name corresponding to the command. // */ // public Map<String, String> getPageFromMode() { // return LDFPortletKeys.renderJSPs; // } // // /** // * Convert // * @param source // * @return // */ // static public String[] convertToStringArray(String source) { // if(source.length() == 0) { // return new String[0]; // } // // return source.split(",",0); // } // // /** // * Convert string array to long array // * // * @param source String array of ids // * @return long array of ids // */ // static public long[] convertStringToLongArray(String[] source) { // if (Validator.isNull(source) || source.length <= 0) { // return null; // } // // return Arrays.stream(source).distinct().mapToLong(Long::parseLong).toArray(); // } // // /** // * Filter roles // * // * Depending on role types, the processes to apply roles are different. This // * method filter either Organization / Site roles or Regular roles. // * // * @param roleIds role ids. This can be mix of reguler / organization / site roles. // * @return Filtered roleids in each array. // * @throws PortalException // */ // public Map<Integer, List<Role>> filterRoles(long[] roleIds) throws PortalException { // // if (Validator.isNull(roleIds) || roleIds.length == 0) { // return new ConcurrentHashMap<Integer, List<Role>>(); // } // // List<Role> roles = _roleLocalService.getRoles(roleIds); // return roles.stream().collect(Collectors.groupingBy(Role::getType)); // } // // // /** // * Create Faker // * // * @param locale Language to create Faker object based on. // * @return Faker object. // */ // public Faker createFaker(String locale) { // // For generating dummy user name // Faker faker = new Faker(new Locale(Locale.ENGLISH.toLanguageTag())); // // try { // Faker fakerTmp = new Faker(new Locale(locale)); // faker = fakerTmp; // } catch (Exception e) { // e.printStackTrace(); // } // // return faker; // } // // @Reference // private RoleLocalService _roleLocalService; // // private static final Log _log = LogFactoryUtil.getLog(CommonUtil.class); // } // Path: src/main/java/com/liferay/support/tools/blogs/BlogsContext.java import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.support.tools.common.ParamContext; import com.liferay.support.tools.utils.CommonUtil; import javax.portlet.ActionRequest; package com.liferay.support.tools.blogs; public class BlogsContext extends ParamContext { private long numberOfPosts = 0; private String baseTitle = ""; private String contents = ""; private long userId = 0; private long groupId = 0; private String[] allowTrackbacks; private boolean allowPingbacks; public BlogsContext(ActionRequest actionRequest) { //Fetch data numberOfPosts = ParamUtil.getLong(actionRequest, "numberOfPosts",0); baseTitle = ParamUtil.getString(actionRequest, "baseTitle",""); contents = ParamUtil.getString(actionRequest, "contents",""); userId = ParamUtil.getLong(actionRequest, "userId",0); groupId = ParamUtil.getLong(actionRequest, "groupId",0); String tempPings = ParamUtil.getString(actionRequest, "allowTrackbacks","");
allowTrackbacks = CommonUtil.convertToStringArray(tempPings);
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/journal/JournalStructureTemplateDummyGenerator.java
// Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // }
import com.liferay.dynamic.data.mapping.model.DDMStructure; import com.liferay.dynamic.data.mapping.service.DDMStructureLocalService; import com.liferay.dynamic.data.mapping.service.DDMTemplateLocalService; import com.liferay.journal.model.JournalArticle; import com.liferay.journal.service.JournalArticleLocalService; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.service.GroupLocalService; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.support.tools.utils.ProgressManager; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.journal; /** * Structure / Template selected Journal Articles Generator * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = JournalStructureTemplateDummyGenerator.class) public class JournalStructureTemplateDummyGenerator extends JournalStructureBaseDummyGenerator { @Override protected JournalContext getContext(ActionRequest request) throws PortalException { return new JournalContext(request); } @Override protected void exec(ActionRequest request, JournalContext paramContext) throws Exception { // Structure Key DDMStructure ddmStructure = _DDMStructureLocalService.getStructure( paramContext.getDdmStructureId() ); String structureKey = ddmStructure.getStructureKey(); // Template key String templateKey = _DDMTemplateLocalService.getTemplate( paramContext.getDdmTemplateId() ).getTemplateKey(); // Tracking progress start
// Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // } // Path: src/main/java/com/liferay/support/tools/journal/JournalStructureTemplateDummyGenerator.java import com.liferay.dynamic.data.mapping.model.DDMStructure; import com.liferay.dynamic.data.mapping.service.DDMStructureLocalService; import com.liferay.dynamic.data.mapping.service.DDMTemplateLocalService; import com.liferay.journal.model.JournalArticle; import com.liferay.journal.service.JournalArticleLocalService; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.service.GroupLocalService; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.support.tools.utils.ProgressManager; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.journal; /** * Structure / Template selected Journal Articles Generator * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = JournalStructureTemplateDummyGenerator.class) public class JournalStructureTemplateDummyGenerator extends JournalStructureBaseDummyGenerator { @Override protected JournalContext getContext(ActionRequest request) throws PortalException { return new JournalContext(request); } @Override protected void exec(ActionRequest request, JournalContext paramContext) throws Exception { // Structure Key DDMStructure ddmStructure = _DDMStructureLocalService.getStructure( paramContext.getDdmStructureId() ); String structureKey = ddmStructure.getStructureKey(); // Template key String templateKey = _DDMTemplateLocalService.getTemplate( paramContext.getDdmTemplateId() ).getTemplateKey(); // Tracking progress start
ProgressManager progressManager = new ProgressManager();
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/blogs/BlogsDefaultDummyGenerator.java
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // }
import com.liferay.blogs.model.BlogsEntry; import com.liferay.blogs.service.BlogsEntryLocalService; import com.liferay.petra.string.StringBundler; import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.service.ServiceContext; import com.liferay.portal.kernel.service.ServiceContextFactory; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import java.util.Date; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.blogs; @Component(immediate = true, service = BlogsDefaultDummyGenerator.class) public class BlogsDefaultDummyGenerator extends DummyGenerator<BlogsContext> { @Override protected BlogsContext getContext(ActionRequest request) throws Exception { return new BlogsContext(request); } @Override protected void exec(ActionRequest request, BlogsContext paramContext) throws Exception { //Tracking progress start
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // } // Path: src/main/java/com/liferay/support/tools/blogs/BlogsDefaultDummyGenerator.java import com.liferay.blogs.model.BlogsEntry; import com.liferay.blogs.service.BlogsEntryLocalService; import com.liferay.petra.string.StringBundler; import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.service.ServiceContext; import com.liferay.portal.kernel.service.ServiceContextFactory; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import java.util.Date; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.blogs; @Component(immediate = true, service = BlogsDefaultDummyGenerator.class) public class BlogsDefaultDummyGenerator extends DummyGenerator<BlogsContext> { @Override protected BlogsContext getContext(ActionRequest request) throws Exception { return new BlogsContext(request); } @Override protected void exec(ActionRequest request, BlogsContext paramContext) throws Exception { //Tracking progress start
ProgressManager progressManager = new ProgressManager();
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/page/PageDummyFactory.java
// Path: src/main/java/com/liferay/support/tools/common/DummyFactory.java // public abstract class DummyFactory { // abstract public DummyGenerator<?> create(ActionRequest request); // } // // Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // }
import com.liferay.support.tools.common.DummyFactory; import com.liferay.support.tools.common.DummyGenerator; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.page; /** * Pages Factory * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = PageDummyFactory.class) public class PageDummyFactory extends DummyFactory { @Override
// Path: src/main/java/com/liferay/support/tools/common/DummyFactory.java // public abstract class DummyFactory { // abstract public DummyGenerator<?> create(ActionRequest request); // } // // Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // Path: src/main/java/com/liferay/support/tools/page/PageDummyFactory.java import com.liferay.support.tools.common.DummyFactory; import com.liferay.support.tools.common.DummyGenerator; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.page; /** * Pages Factory * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = PageDummyFactory.class) public class PageDummyFactory extends DummyFactory { @Override
public DummyGenerator<PageContext> create(ActionRequest request) {
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/page/PageDefaultDummyGenerator.java
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // }
import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.service.LayoutLocalService; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.page; /** * Pages Generator * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = PageDefaultDummyGenerator.class) public class PageDefaultDummyGenerator extends DummyGenerator<PageContext> { @Override protected PageContext getContext(ActionRequest request) { return new PageContext(request); } @Override protected void exec(ActionRequest request, PageContext paramContext) throws PortalException { //Tracking progress start
// Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // // Path: src/main/java/com/liferay/support/tools/utils/ProgressManager.java // public class ProgressManager { // // private double _loader = 1; // private ProgressTracker _progressTracker; // private int _threshold = 100; // private ActionRequest _request; // private long _sleep = 1500; // // /** // * Start Progress // * // * @param request ActionRequest // * @param loaderInit // */ // public void start(ActionRequest request) { // _request = request; // // String commonProgressId = ParamUtil.getString(request, LDFPortletKeys.COMMON_PROGRESS_ID, // LDFPortletKeys.COMMON_PROGRESS_ID); // // // Tracking progress start // _progressTracker = new ProgressTracker(commonProgressId); // ProgressTrackerThreadLocal.setProgressTracker(_progressTracker); // _progressTracker.start(request); // // } // // public int getThreshold() { // return _threshold; // } // // public void setThreshold(int threshold) { // _threshold = threshold; // } // // /** // * Calcluate the percentage of prgress // * // * @param index // * @param numberOfTotal // * @return percentage of progress by int // */ // public int percentageCalcluation(long index, long numberOfTotal) { // // if(numberOfTotal <= 0) { // return 0; // } // // double dIndex = (double)index; // double dNumberOfTotal = (double)numberOfTotal; // // int result = (int)(dIndex / dNumberOfTotal * 100.00); // // return (_threshold <= result) ? _threshold : result; // } // // /** // * Tracking progress // * // * @param index Index of loop // * @param numberOfTotal Total number // */ // public void trackProgress(long index, long numberOfTotal) { // if(null != _progressTracker ) { // _loader = percentageCalcluation(index, numberOfTotal); // System.out.println("Creating..." + (int) _loader + "% done"); // _progressTracker.setPercent((int)_loader); // } // } // // /** // * Finish progress bar // */ // public void finish() { // try { // // Progress bar doesn't hit if finish right away. // Thread.sleep(_sleep); // } catch (InterruptedException e) { // e.printStackTrace(); // } // _progressTracker.finish(_request); // } // // } // Path: src/main/java/com/liferay/support/tools/page/PageDefaultDummyGenerator.java import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.service.LayoutLocalService; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.support.tools.common.DummyGenerator; import com.liferay.support.tools.utils.ProgressManager; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.page; /** * Pages Generator * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = PageDefaultDummyGenerator.class) public class PageDefaultDummyGenerator extends DummyGenerator<PageContext> { @Override protected PageContext getContext(ActionRequest request) { return new PageContext(request); } @Override protected void exec(ActionRequest request, PageContext paramContext) throws PortalException { //Tracking progress start
ProgressManager progressManager = new ProgressManager();
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/company/CompanyDummyFactory.java
// Path: src/main/java/com/liferay/support/tools/common/DummyFactory.java // public abstract class DummyFactory { // abstract public DummyGenerator<?> create(ActionRequest request); // } // // Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // }
import com.liferay.support.tools.common.DummyFactory; import com.liferay.support.tools.common.DummyGenerator; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.company; /** * Blogs post dummy factory * * @author Yasuyuki Takeo * */ @Component( immediate = true, service = CompanyDummyFactory.class ) public class CompanyDummyFactory extends DummyFactory { @Override
// Path: src/main/java/com/liferay/support/tools/common/DummyFactory.java // public abstract class DummyFactory { // abstract public DummyGenerator<?> create(ActionRequest request); // } // // Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // Path: src/main/java/com/liferay/support/tools/company/CompanyDummyFactory.java import com.liferay.support.tools.common.DummyFactory; import com.liferay.support.tools.common.DummyGenerator; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.company; /** * Blogs post dummy factory * * @author Yasuyuki Takeo * */ @Component( immediate = true, service = CompanyDummyFactory.class ) public class CompanyDummyFactory extends DummyFactory { @Override
public DummyGenerator<CompanyContext> create( ActionRequest request ) {
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/user/UserDataService.java
// Path: src/main/java/com/liferay/support/tools/utils/CommonUtil.java // @Component(immediate = true, service = CommonUtil.class) // public class CommonUtil { // // /** // * Page Command Pairs // * // * @return jsp file name corresponding to the command. // */ // public Map<String, String> getPageFromMode() { // return LDFPortletKeys.renderJSPs; // } // // /** // * Convert // * @param source // * @return // */ // static public String[] convertToStringArray(String source) { // if(source.length() == 0) { // return new String[0]; // } // // return source.split(",",0); // } // // /** // * Convert string array to long array // * // * @param source String array of ids // * @return long array of ids // */ // static public long[] convertStringToLongArray(String[] source) { // if (Validator.isNull(source) || source.length <= 0) { // return null; // } // // return Arrays.stream(source).distinct().mapToLong(Long::parseLong).toArray(); // } // // /** // * Filter roles // * // * Depending on role types, the processes to apply roles are different. This // * method filter either Organization / Site roles or Regular roles. // * // * @param roleIds role ids. This can be mix of reguler / organization / site roles. // * @return Filtered roleids in each array. // * @throws PortalException // */ // public Map<Integer, List<Role>> filterRoles(long[] roleIds) throws PortalException { // // if (Validator.isNull(roleIds) || roleIds.length == 0) { // return new ConcurrentHashMap<Integer, List<Role>>(); // } // // List<Role> roles = _roleLocalService.getRoles(roleIds); // return roles.stream().collect(Collectors.groupingBy(Role::getType)); // } // // // /** // * Create Faker // * // * @param locale Language to create Faker object based on. // * @return Faker object. // */ // public Faker createFaker(String locale) { // // For generating dummy user name // Faker faker = new Faker(new Locale(Locale.ENGLISH.toLanguageTag())); // // try { // Faker fakerTmp = new Faker(new Locale(locale)); // faker = fakerTmp; // } catch (Exception e) { // e.printStackTrace(); // } // // return faker; // } // // @Reference // private RoleLocalService _roleLocalService; // // private static final Log _log = LogFactoryUtil.getLog(CommonUtil.class); // }
import com.github.javafaker.Faker; import com.liferay.announcements.kernel.model.AnnouncementsDelivery; import com.liferay.announcements.kernel.service.AnnouncementsDeliveryLocalService; import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.exception.UserScreenNameException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.model.Organization; import com.liferay.portal.kernel.model.Role; import com.liferay.portal.kernel.model.RoleConstants; import com.liferay.portal.kernel.model.User; import com.liferay.portal.kernel.security.access.control.AccessControlled; import com.liferay.portal.kernel.service.OrganizationLocalService; import com.liferay.portal.kernel.service.RoleLocalService; import com.liferay.portal.kernel.service.ServiceContext; import com.liferay.portal.kernel.service.UserGroupRoleLocalService; import com.liferay.portal.kernel.service.UserLocalService; import com.liferay.portal.kernel.transaction.Isolation; import com.liferay.portal.kernel.transaction.Transactional; import com.liferay.portal.kernel.util.LocaleUtil; import com.liferay.portal.kernel.util.Validator; import com.liferay.support.tools.utils.CommonUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import aQute.bnd.annotation.ProviderType;
/** * Update Announcements Deliveries * * @param userId * @param announcementsDeliveries * @throws PortalException */ public void updateAnnouncementsDeliveries( long userId, List<AnnouncementsDelivery> announcementsDeliveries) throws PortalException { for (AnnouncementsDelivery announcementsDelivery : announcementsDeliveries) { _announcementsDeliveryLocalService.updateDelivery( userId, announcementsDelivery.getType(), announcementsDelivery.isEmail(), announcementsDelivery.isSms()); } } @Reference private AnnouncementsDeliveryLocalService _announcementsDeliveryLocalService; @Reference private UserLocalService _userLocalService; @Reference private UserGroupRoleLocalService _userGroupRoleLocalService; @Reference
// Path: src/main/java/com/liferay/support/tools/utils/CommonUtil.java // @Component(immediate = true, service = CommonUtil.class) // public class CommonUtil { // // /** // * Page Command Pairs // * // * @return jsp file name corresponding to the command. // */ // public Map<String, String> getPageFromMode() { // return LDFPortletKeys.renderJSPs; // } // // /** // * Convert // * @param source // * @return // */ // static public String[] convertToStringArray(String source) { // if(source.length() == 0) { // return new String[0]; // } // // return source.split(",",0); // } // // /** // * Convert string array to long array // * // * @param source String array of ids // * @return long array of ids // */ // static public long[] convertStringToLongArray(String[] source) { // if (Validator.isNull(source) || source.length <= 0) { // return null; // } // // return Arrays.stream(source).distinct().mapToLong(Long::parseLong).toArray(); // } // // /** // * Filter roles // * // * Depending on role types, the processes to apply roles are different. This // * method filter either Organization / Site roles or Regular roles. // * // * @param roleIds role ids. This can be mix of reguler / organization / site roles. // * @return Filtered roleids in each array. // * @throws PortalException // */ // public Map<Integer, List<Role>> filterRoles(long[] roleIds) throws PortalException { // // if (Validator.isNull(roleIds) || roleIds.length == 0) { // return new ConcurrentHashMap<Integer, List<Role>>(); // } // // List<Role> roles = _roleLocalService.getRoles(roleIds); // return roles.stream().collect(Collectors.groupingBy(Role::getType)); // } // // // /** // * Create Faker // * // * @param locale Language to create Faker object based on. // * @return Faker object. // */ // public Faker createFaker(String locale) { // // For generating dummy user name // Faker faker = new Faker(new Locale(Locale.ENGLISH.toLanguageTag())); // // try { // Faker fakerTmp = new Faker(new Locale(locale)); // faker = fakerTmp; // } catch (Exception e) { // e.printStackTrace(); // } // // return faker; // } // // @Reference // private RoleLocalService _roleLocalService; // // private static final Log _log = LogFactoryUtil.getLog(CommonUtil.class); // } // Path: src/main/java/com/liferay/support/tools/user/UserDataService.java import com.github.javafaker.Faker; import com.liferay.announcements.kernel.model.AnnouncementsDelivery; import com.liferay.announcements.kernel.service.AnnouncementsDeliveryLocalService; import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.exception.UserScreenNameException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.model.Organization; import com.liferay.portal.kernel.model.Role; import com.liferay.portal.kernel.model.RoleConstants; import com.liferay.portal.kernel.model.User; import com.liferay.portal.kernel.security.access.control.AccessControlled; import com.liferay.portal.kernel.service.OrganizationLocalService; import com.liferay.portal.kernel.service.RoleLocalService; import com.liferay.portal.kernel.service.ServiceContext; import com.liferay.portal.kernel.service.UserGroupRoleLocalService; import com.liferay.portal.kernel.service.UserLocalService; import com.liferay.portal.kernel.transaction.Isolation; import com.liferay.portal.kernel.transaction.Transactional; import com.liferay.portal.kernel.util.LocaleUtil; import com.liferay.portal.kernel.util.Validator; import com.liferay.support.tools.utils.CommonUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import aQute.bnd.annotation.ProviderType; /** * Update Announcements Deliveries * * @param userId * @param announcementsDeliveries * @throws PortalException */ public void updateAnnouncementsDeliveries( long userId, List<AnnouncementsDelivery> announcementsDeliveries) throws PortalException { for (AnnouncementsDelivery announcementsDelivery : announcementsDeliveries) { _announcementsDeliveryLocalService.updateDelivery( userId, announcementsDelivery.getType(), announcementsDelivery.isEmail(), announcementsDelivery.isSms()); } } @Reference private AnnouncementsDeliveryLocalService _announcementsDeliveryLocalService; @Reference private UserLocalService _userLocalService; @Reference private UserGroupRoleLocalService _userGroupRoleLocalService; @Reference
private CommonUtil _commonUtil;
yasuflatland-lf/liferay-dummy-factory
src/main/java/com/liferay/support/tools/document/library/DLDummyFactory.java
// Path: src/main/java/com/liferay/support/tools/common/DummyFactory.java // public abstract class DummyFactory { // abstract public DummyGenerator<?> create(ActionRequest request); // } // // Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // }
import com.liferay.support.tools.common.DummyFactory; import com.liferay.support.tools.common.DummyGenerator; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference;
package com.liferay.support.tools.document.library; /** * Document Library Factory * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = DLDummyFactory.class) public class DLDummyFactory extends DummyFactory { @Override
// Path: src/main/java/com/liferay/support/tools/common/DummyFactory.java // public abstract class DummyFactory { // abstract public DummyGenerator<?> create(ActionRequest request); // } // // Path: src/main/java/com/liferay/support/tools/common/DummyGenerator.java // public abstract class DummyGenerator<T extends ParamContext> { // // /** // * Get Context // * // * @param request // * @return // */ // protected abstract T getContext(ActionRequest request) throws Exception; // // /** // * Create Dummy data // * // * @param request // * @throws Exception // */ // public void create(ActionRequest request) throws Exception { // // T paramContext = getContext(request); // // if(!validate(paramContext)) { // throw new Exception("Validation Error"); // } // // ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); // ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), request); // // paramContext.setThemeDisplay(themeDisplay); // paramContext.setServiceContext(serviceContext); // // TimeKeeper timeKeeper = new TimeKeeper(); // timeKeeper.start(); // // // Execute creation process // exec(request, paramContext); // // timeKeeper.stop(); // timeKeeper.outputTime(); // } // // /** // * Validation // * // * @param paramContext // * @return boolean // */ // protected boolean validate(T paramContext) { // return true; // } // // /** // * Exec data // * // * @param paramContext // */ // protected abstract void exec(ActionRequest request, T paramContext) throws Exception; // } // Path: src/main/java/com/liferay/support/tools/document/library/DLDummyFactory.java import com.liferay.support.tools.common.DummyFactory; import com.liferay.support.tools.common.DummyGenerator; import javax.portlet.ActionRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; package com.liferay.support.tools.document.library; /** * Document Library Factory * * @author Yasuyuki Takeo * */ @Component(immediate = true, service = DLDummyFactory.class) public class DLDummyFactory extends DummyFactory { @Override
public DummyGenerator<DLContext> create(ActionRequest request) {
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/metrics/report/MetricReport.java
// Path: stylechecker/src/main/java/com/sqatntu/metrics/Benchmark.java // public class Benchmark { // public static final int LINE_OF_CODE = 200; // public static final int DEPTH_OF_CONDITION_NESTING = 3; // public static final int AVERAGE_LENGTH_OF_IDENTIFIER = 17; // public static final int NUMBER_OF_ATTRIBUTES = 6; // public static final int NUMBER_OF_METHODS = 10; // } // // Path: stylechecker/src/main/java/com/sqatntu/metrics/ScoreCalculator.java // public class ScoreCalculator { // public static float calculateScore(int value, int benchmark) { // if (value <= benchmark) { // return 100f; // } else if (value <= 4f * benchmark) { // return (((-1f / (3f * benchmark)) * value) + (4f / 3f)) * 100f; // } else { // return 0; // } // } // }
import java.util.List; import com.sqatntu.metrics.Benchmark; import com.sqatntu.metrics.ScoreCalculator; import java.util.ArrayList;
return depthOfConditionNesting; } public void setDepthOfConditionNesting(int depthOfConditionNesting) { this.depthOfConditionNesting = depthOfConditionNesting; } public int getLengthOfIdentifier() { return lengthOfIdentifier; } public void addLengthOfIdentifier(int lengthOfIdentifier) { this.lengthOfIdentifier += lengthOfIdentifier; this.numberOfIdentifier++; } public int getAverageLengthOfIdentifier() { return numberOfIdentifier != 0 ? lengthOfIdentifier / numberOfIdentifier : 0; } public int getNumberOfAttributes() { return numberOfAttributes; } public void addNumberOfAttributes(int numberOfAttributes) { this.numberOfAttributes += numberOfAttributes; } public float getAnalysabilityPercentage() { return getAverage(
// Path: stylechecker/src/main/java/com/sqatntu/metrics/Benchmark.java // public class Benchmark { // public static final int LINE_OF_CODE = 200; // public static final int DEPTH_OF_CONDITION_NESTING = 3; // public static final int AVERAGE_LENGTH_OF_IDENTIFIER = 17; // public static final int NUMBER_OF_ATTRIBUTES = 6; // public static final int NUMBER_OF_METHODS = 10; // } // // Path: stylechecker/src/main/java/com/sqatntu/metrics/ScoreCalculator.java // public class ScoreCalculator { // public static float calculateScore(int value, int benchmark) { // if (value <= benchmark) { // return 100f; // } else if (value <= 4f * benchmark) { // return (((-1f / (3f * benchmark)) * value) + (4f / 3f)) * 100f; // } else { // return 0; // } // } // } // Path: stylechecker/src/main/java/com/sqatntu/metrics/report/MetricReport.java import java.util.List; import com.sqatntu.metrics.Benchmark; import com.sqatntu.metrics.ScoreCalculator; import java.util.ArrayList; return depthOfConditionNesting; } public void setDepthOfConditionNesting(int depthOfConditionNesting) { this.depthOfConditionNesting = depthOfConditionNesting; } public int getLengthOfIdentifier() { return lengthOfIdentifier; } public void addLengthOfIdentifier(int lengthOfIdentifier) { this.lengthOfIdentifier += lengthOfIdentifier; this.numberOfIdentifier++; } public int getAverageLengthOfIdentifier() { return numberOfIdentifier != 0 ? lengthOfIdentifier / numberOfIdentifier : 0; } public int getNumberOfAttributes() { return numberOfAttributes; } public void addNumberOfAttributes(int numberOfAttributes) { this.numberOfAttributes += numberOfAttributes; } public float getAnalysabilityPercentage() { return getAverage(
getScore(getNumberOfLines(), Benchmark.LINE_OF_CODE),
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/metrics/report/MetricReport.java
// Path: stylechecker/src/main/java/com/sqatntu/metrics/Benchmark.java // public class Benchmark { // public static final int LINE_OF_CODE = 200; // public static final int DEPTH_OF_CONDITION_NESTING = 3; // public static final int AVERAGE_LENGTH_OF_IDENTIFIER = 17; // public static final int NUMBER_OF_ATTRIBUTES = 6; // public static final int NUMBER_OF_METHODS = 10; // } // // Path: stylechecker/src/main/java/com/sqatntu/metrics/ScoreCalculator.java // public class ScoreCalculator { // public static float calculateScore(int value, int benchmark) { // if (value <= benchmark) { // return 100f; // } else if (value <= 4f * benchmark) { // return (((-1f / (3f * benchmark)) * value) + (4f / 3f)) * 100f; // } else { // return 0; // } // } // }
import java.util.List; import com.sqatntu.metrics.Benchmark; import com.sqatntu.metrics.ScoreCalculator; import java.util.ArrayList;
public void addNumberOfAttributes(int numberOfAttributes) { this.numberOfAttributes += numberOfAttributes; } public float getAnalysabilityPercentage() { return getAverage( getScore(getNumberOfLines(), Benchmark.LINE_OF_CODE), getScore(getDepthOfConditionNesting(), Benchmark.DEPTH_OF_CONDITION_NESTING), getScore(getAverageLengthOfIdentifier(), Benchmark.AVERAGE_LENGTH_OF_IDENTIFIER), getScore(getNumberOfAttributes(), Benchmark.NUMBER_OF_ATTRIBUTES), getScore(getNumberOfMethods(), Benchmark.NUMBER_OF_METHODS) ); } public float getTestabilityPercentage() { return getAverage( getScore(getNumberOfLines(), Benchmark.LINE_OF_CODE), getScore(getDepthOfConditionNesting(), Benchmark.DEPTH_OF_CONDITION_NESTING) ); } public float getOverallPercentage() { return getAverage( getAnalysabilityPercentage(), getTestabilityPercentage() ); } private float getScore(int value, int benchmark) {
// Path: stylechecker/src/main/java/com/sqatntu/metrics/Benchmark.java // public class Benchmark { // public static final int LINE_OF_CODE = 200; // public static final int DEPTH_OF_CONDITION_NESTING = 3; // public static final int AVERAGE_LENGTH_OF_IDENTIFIER = 17; // public static final int NUMBER_OF_ATTRIBUTES = 6; // public static final int NUMBER_OF_METHODS = 10; // } // // Path: stylechecker/src/main/java/com/sqatntu/metrics/ScoreCalculator.java // public class ScoreCalculator { // public static float calculateScore(int value, int benchmark) { // if (value <= benchmark) { // return 100f; // } else if (value <= 4f * benchmark) { // return (((-1f / (3f * benchmark)) * value) + (4f / 3f)) * 100f; // } else { // return 0; // } // } // } // Path: stylechecker/src/main/java/com/sqatntu/metrics/report/MetricReport.java import java.util.List; import com.sqatntu.metrics.Benchmark; import com.sqatntu.metrics.ScoreCalculator; import java.util.ArrayList; public void addNumberOfAttributes(int numberOfAttributes) { this.numberOfAttributes += numberOfAttributes; } public float getAnalysabilityPercentage() { return getAverage( getScore(getNumberOfLines(), Benchmark.LINE_OF_CODE), getScore(getDepthOfConditionNesting(), Benchmark.DEPTH_OF_CONDITION_NESTING), getScore(getAverageLengthOfIdentifier(), Benchmark.AVERAGE_LENGTH_OF_IDENTIFIER), getScore(getNumberOfAttributes(), Benchmark.NUMBER_OF_ATTRIBUTES), getScore(getNumberOfMethods(), Benchmark.NUMBER_OF_METHODS) ); } public float getTestabilityPercentage() { return getAverage( getScore(getNumberOfLines(), Benchmark.LINE_OF_CODE), getScore(getDepthOfConditionNesting(), Benchmark.DEPTH_OF_CONDITION_NESTING) ); } public float getOverallPercentage() { return getAverage( getAnalysabilityPercentage(), getTestabilityPercentage() ); } private float getScore(int value, int benchmark) {
return ScoreCalculator.calculateScore(value, benchmark);
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/JsonConfigurationLoader.java // public class JsonConfigurationLoader implements ConfigurationLoader { // // @Override // public Configuration loadFileConfiguration(String filePath) throws IOException { // File configurationFile = new File(filePath); // String configurationJson = FileUtils.readFileToString(configurationFile); // // return loadJsonConfiguration(configurationJson); // } // // @Override // public Configuration loadJsonConfiguration(String json) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(DefaultConfiguration.class, new ConfigurationDeserializer()); // // Gson gson = gsonBuilder.create(); // DefaultConfiguration configuration = // gson.fromJson(json, DefaultConfiguration.class); // // return configuration; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // }
import javax.inject.Singleton; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.configuration.JsonConfigurationLoader; import com.sqatntu.stylechecker.report.StyleReport; import dagger.Module; import dagger.Provides;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.injection; /** * A module that provides all required dependencies for {@link StyleChecker} */ @Module(injects = {StyleChecker.class}) public class StyleCheckerModule { @Provides @Singleton
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/JsonConfigurationLoader.java // public class JsonConfigurationLoader implements ConfigurationLoader { // // @Override // public Configuration loadFileConfiguration(String filePath) throws IOException { // File configurationFile = new File(filePath); // String configurationJson = FileUtils.readFileToString(configurationFile); // // return loadJsonConfiguration(configurationJson); // } // // @Override // public Configuration loadJsonConfiguration(String json) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(DefaultConfiguration.class, new ConfigurationDeserializer()); // // Gson gson = gsonBuilder.create(); // DefaultConfiguration configuration = // gson.fromJson(json, DefaultConfiguration.class); // // return configuration; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java import javax.inject.Singleton; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.configuration.JsonConfigurationLoader; import com.sqatntu.stylechecker.report.StyleReport; import dagger.Module; import dagger.Provides; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.injection; /** * A module that provides all required dependencies for {@link StyleChecker} */ @Module(injects = {StyleChecker.class}) public class StyleCheckerModule { @Provides @Singleton
ConfigurationLoader provideConfigurationLoader() {
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/JsonConfigurationLoader.java // public class JsonConfigurationLoader implements ConfigurationLoader { // // @Override // public Configuration loadFileConfiguration(String filePath) throws IOException { // File configurationFile = new File(filePath); // String configurationJson = FileUtils.readFileToString(configurationFile); // // return loadJsonConfiguration(configurationJson); // } // // @Override // public Configuration loadJsonConfiguration(String json) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(DefaultConfiguration.class, new ConfigurationDeserializer()); // // Gson gson = gsonBuilder.create(); // DefaultConfiguration configuration = // gson.fromJson(json, DefaultConfiguration.class); // // return configuration; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // }
import javax.inject.Singleton; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.configuration.JsonConfigurationLoader; import com.sqatntu.stylechecker.report.StyleReport; import dagger.Module; import dagger.Provides;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.injection; /** * A module that provides all required dependencies for {@link StyleChecker} */ @Module(injects = {StyleChecker.class}) public class StyleCheckerModule { @Provides @Singleton ConfigurationLoader provideConfigurationLoader() {
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/JsonConfigurationLoader.java // public class JsonConfigurationLoader implements ConfigurationLoader { // // @Override // public Configuration loadFileConfiguration(String filePath) throws IOException { // File configurationFile = new File(filePath); // String configurationJson = FileUtils.readFileToString(configurationFile); // // return loadJsonConfiguration(configurationJson); // } // // @Override // public Configuration loadJsonConfiguration(String json) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(DefaultConfiguration.class, new ConfigurationDeserializer()); // // Gson gson = gsonBuilder.create(); // DefaultConfiguration configuration = // gson.fromJson(json, DefaultConfiguration.class); // // return configuration; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java import javax.inject.Singleton; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.configuration.JsonConfigurationLoader; import com.sqatntu.stylechecker.report.StyleReport; import dagger.Module; import dagger.Provides; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.injection; /** * A module that provides all required dependencies for {@link StyleChecker} */ @Module(injects = {StyleChecker.class}) public class StyleCheckerModule { @Provides @Singleton ConfigurationLoader provideConfigurationLoader() {
return new JsonConfigurationLoader();
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/JsonConfigurationLoader.java // public class JsonConfigurationLoader implements ConfigurationLoader { // // @Override // public Configuration loadFileConfiguration(String filePath) throws IOException { // File configurationFile = new File(filePath); // String configurationJson = FileUtils.readFileToString(configurationFile); // // return loadJsonConfiguration(configurationJson); // } // // @Override // public Configuration loadJsonConfiguration(String json) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(DefaultConfiguration.class, new ConfigurationDeserializer()); // // Gson gson = gsonBuilder.create(); // DefaultConfiguration configuration = // gson.fromJson(json, DefaultConfiguration.class); // // return configuration; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // }
import javax.inject.Singleton; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.configuration.JsonConfigurationLoader; import com.sqatntu.stylechecker.report.StyleReport; import dagger.Module; import dagger.Provides;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.injection; /** * A module that provides all required dependencies for {@link StyleChecker} */ @Module(injects = {StyleChecker.class}) public class StyleCheckerModule { @Provides @Singleton ConfigurationLoader provideConfigurationLoader() { return new JsonConfigurationLoader(); } @Provides
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/JsonConfigurationLoader.java // public class JsonConfigurationLoader implements ConfigurationLoader { // // @Override // public Configuration loadFileConfiguration(String filePath) throws IOException { // File configurationFile = new File(filePath); // String configurationJson = FileUtils.readFileToString(configurationFile); // // return loadJsonConfiguration(configurationJson); // } // // @Override // public Configuration loadJsonConfiguration(String json) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(DefaultConfiguration.class, new ConfigurationDeserializer()); // // Gson gson = gsonBuilder.create(); // DefaultConfiguration configuration = // gson.fromJson(json, DefaultConfiguration.class); // // return configuration; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java import javax.inject.Singleton; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.configuration.JsonConfigurationLoader; import com.sqatntu.stylechecker.report.StyleReport; import dagger.Module; import dagger.Provides; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.injection; /** * A module that provides all required dependencies for {@link StyleChecker} */ @Module(injects = {StyleChecker.class}) public class StyleCheckerModule { @Provides @Singleton ConfigurationLoader provideConfigurationLoader() { return new JsonConfigurationLoader(); } @Provides
StyleReport provideStyleReport() {
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/JsonConfigurationLoader.java // public class JsonConfigurationLoader implements ConfigurationLoader { // // @Override // public Configuration loadFileConfiguration(String filePath) throws IOException { // File configurationFile = new File(filePath); // String configurationJson = FileUtils.readFileToString(configurationFile); // // return loadJsonConfiguration(configurationJson); // } // // @Override // public Configuration loadJsonConfiguration(String json) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(DefaultConfiguration.class, new ConfigurationDeserializer()); // // Gson gson = gsonBuilder.create(); // DefaultConfiguration configuration = // gson.fromJson(json, DefaultConfiguration.class); // // return configuration; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // }
import javax.inject.Singleton; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.configuration.JsonConfigurationLoader; import com.sqatntu.stylechecker.report.StyleReport; import dagger.Module; import dagger.Provides;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.injection; /** * A module that provides all required dependencies for {@link StyleChecker} */ @Module(injects = {StyleChecker.class}) public class StyleCheckerModule { @Provides @Singleton ConfigurationLoader provideConfigurationLoader() { return new JsonConfigurationLoader(); } @Provides StyleReport provideStyleReport() { return new StyleReport(); } @Provides @Singleton
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/JsonConfigurationLoader.java // public class JsonConfigurationLoader implements ConfigurationLoader { // // @Override // public Configuration loadFileConfiguration(String filePath) throws IOException { // File configurationFile = new File(filePath); // String configurationJson = FileUtils.readFileToString(configurationFile); // // return loadJsonConfiguration(configurationJson); // } // // @Override // public Configuration loadJsonConfiguration(String json) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(DefaultConfiguration.class, new ConfigurationDeserializer()); // // Gson gson = gsonBuilder.create(); // DefaultConfiguration configuration = // gson.fromJson(json, DefaultConfiguration.class); // // return configuration; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java import javax.inject.Singleton; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.configuration.JsonConfigurationLoader; import com.sqatntu.stylechecker.report.StyleReport; import dagger.Module; import dagger.Provides; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.injection; /** * A module that provides all required dependencies for {@link StyleChecker} */ @Module(injects = {StyleChecker.class}) public class StyleCheckerModule { @Provides @Singleton ConfigurationLoader provideConfigurationLoader() { return new JsonConfigurationLoader(); } @Provides StyleReport provideStyleReport() { return new StyleReport(); } @Provides @Singleton
ThrowingErrorListener provideThrowingErrorListener() {
Andyccs/sqat
stylechecker/src/test/java/com/sqatntu/stylechecker/listener/BraceStyleListenerTest.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/ListenerTest.java // public class ListenerTest { // // @Rule // public TestName name = new TestName(); // // protected String testCode; // protected String testConfig; // // @Before // public void before() throws NoSuchMethodException, IOException { // Method method = this.getClass().getMethod(name.getMethodName()); // Annotation[] annotations = method.getDeclaredAnnotations(); // // for (Annotation annotation : annotations) { // if (annotation instanceof TestCode) { // TestCode testCodeAnnotation = (TestCode) annotation; // testCode = TestUtil.loadFile(testCodeAnnotation.fileName()); // } else if (annotation instanceof TestConfig) { // TestConfig testConfigAnnotation = (TestConfig) annotation; // testConfig = TestUtil.loadFile(testConfigAnnotation.fileName()); // } // } // } // // @After // public void after() { // testCode = null; // testConfig = null; // } // }
import com.sqatntu.testutil.ListenerTest; import com.sqatntu.testutil.TestCode; import com.sqatntu.testutil.TestConfig; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 11/10/15. */ public class BraceStyleListenerTest extends ListenerTest { @Test @TestCode( detail = "krStyleCode", fileName = "src/test/resources/stylechecker/BraceKRStyle.java") @TestConfig( detail = "krStyleConfig", fileName = "src/test/resources/stylechecker/BraceKRStyle.json")
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/ListenerTest.java // public class ListenerTest { // // @Rule // public TestName name = new TestName(); // // protected String testCode; // protected String testConfig; // // @Before // public void before() throws NoSuchMethodException, IOException { // Method method = this.getClass().getMethod(name.getMethodName()); // Annotation[] annotations = method.getDeclaredAnnotations(); // // for (Annotation annotation : annotations) { // if (annotation instanceof TestCode) { // TestCode testCodeAnnotation = (TestCode) annotation; // testCode = TestUtil.loadFile(testCodeAnnotation.fileName()); // } else if (annotation instanceof TestConfig) { // TestConfig testConfigAnnotation = (TestConfig) annotation; // testConfig = TestUtil.loadFile(testConfigAnnotation.fileName()); // } // } // } // // @After // public void after() { // testCode = null; // testConfig = null; // } // } // Path: stylechecker/src/test/java/com/sqatntu/stylechecker/listener/BraceStyleListenerTest.java import com.sqatntu.testutil.ListenerTest; import com.sqatntu.testutil.TestCode; import com.sqatntu.testutil.TestConfig; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 11/10/15. */ public class BraceStyleListenerTest extends ListenerTest { @Test @TestCode( detail = "krStyleCode", fileName = "src/test/resources/stylechecker/BraceKRStyle.java") @TestConfig( detail = "krStyleConfig", fileName = "src/test/resources/stylechecker/BraceKRStyle.json")
public void braceStyle1() throws IOException, StyleCheckerException {
Andyccs/sqat
stylechecker/src/test/java/com/sqatntu/stylechecker/listener/BraceStyleListenerTest.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/ListenerTest.java // public class ListenerTest { // // @Rule // public TestName name = new TestName(); // // protected String testCode; // protected String testConfig; // // @Before // public void before() throws NoSuchMethodException, IOException { // Method method = this.getClass().getMethod(name.getMethodName()); // Annotation[] annotations = method.getDeclaredAnnotations(); // // for (Annotation annotation : annotations) { // if (annotation instanceof TestCode) { // TestCode testCodeAnnotation = (TestCode) annotation; // testCode = TestUtil.loadFile(testCodeAnnotation.fileName()); // } else if (annotation instanceof TestConfig) { // TestConfig testConfigAnnotation = (TestConfig) annotation; // testConfig = TestUtil.loadFile(testConfigAnnotation.fileName()); // } // } // } // // @After // public void after() { // testCode = null; // testConfig = null; // } // }
import com.sqatntu.testutil.ListenerTest; import com.sqatntu.testutil.TestCode; import com.sqatntu.testutil.TestConfig; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 11/10/15. */ public class BraceStyleListenerTest extends ListenerTest { @Test @TestCode( detail = "krStyleCode", fileName = "src/test/resources/stylechecker/BraceKRStyle.java") @TestConfig( detail = "krStyleConfig", fileName = "src/test/resources/stylechecker/BraceKRStyle.json") public void braceStyle1() throws IOException, StyleCheckerException {
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/ListenerTest.java // public class ListenerTest { // // @Rule // public TestName name = new TestName(); // // protected String testCode; // protected String testConfig; // // @Before // public void before() throws NoSuchMethodException, IOException { // Method method = this.getClass().getMethod(name.getMethodName()); // Annotation[] annotations = method.getDeclaredAnnotations(); // // for (Annotation annotation : annotations) { // if (annotation instanceof TestCode) { // TestCode testCodeAnnotation = (TestCode) annotation; // testCode = TestUtil.loadFile(testCodeAnnotation.fileName()); // } else if (annotation instanceof TestConfig) { // TestConfig testConfigAnnotation = (TestConfig) annotation; // testConfig = TestUtil.loadFile(testConfigAnnotation.fileName()); // } // } // } // // @After // public void after() { // testCode = null; // testConfig = null; // } // } // Path: stylechecker/src/test/java/com/sqatntu/stylechecker/listener/BraceStyleListenerTest.java import com.sqatntu.testutil.ListenerTest; import com.sqatntu.testutil.TestCode; import com.sqatntu.testutil.TestConfig; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 11/10/15. */ public class BraceStyleListenerTest extends ListenerTest { @Test @TestCode( detail = "krStyleCode", fileName = "src/test/resources/stylechecker/BraceKRStyle.java") @TestConfig( detail = "krStyleConfig", fileName = "src/test/resources/stylechecker/BraceKRStyle.json") public void braceStyle1() throws IOException, StyleCheckerException {
StyleChecker checker = new StyleChecker();
Andyccs/sqat
stylechecker/src/test/java/com/sqatntu/stylechecker/listener/BraceStyleListenerTest.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/ListenerTest.java // public class ListenerTest { // // @Rule // public TestName name = new TestName(); // // protected String testCode; // protected String testConfig; // // @Before // public void before() throws NoSuchMethodException, IOException { // Method method = this.getClass().getMethod(name.getMethodName()); // Annotation[] annotations = method.getDeclaredAnnotations(); // // for (Annotation annotation : annotations) { // if (annotation instanceof TestCode) { // TestCode testCodeAnnotation = (TestCode) annotation; // testCode = TestUtil.loadFile(testCodeAnnotation.fileName()); // } else if (annotation instanceof TestConfig) { // TestConfig testConfigAnnotation = (TestConfig) annotation; // testConfig = TestUtil.loadFile(testConfigAnnotation.fileName()); // } // } // } // // @After // public void after() { // testCode = null; // testConfig = null; // } // }
import com.sqatntu.testutil.ListenerTest; import com.sqatntu.testutil.TestCode; import com.sqatntu.testutil.TestConfig; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 11/10/15. */ public class BraceStyleListenerTest extends ListenerTest { @Test @TestCode( detail = "krStyleCode", fileName = "src/test/resources/stylechecker/BraceKRStyle.java") @TestConfig( detail = "krStyleConfig", fileName = "src/test/resources/stylechecker/BraceKRStyle.json") public void braceStyle1() throws IOException, StyleCheckerException { StyleChecker checker = new StyleChecker();
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/ListenerTest.java // public class ListenerTest { // // @Rule // public TestName name = new TestName(); // // protected String testCode; // protected String testConfig; // // @Before // public void before() throws NoSuchMethodException, IOException { // Method method = this.getClass().getMethod(name.getMethodName()); // Annotation[] annotations = method.getDeclaredAnnotations(); // // for (Annotation annotation : annotations) { // if (annotation instanceof TestCode) { // TestCode testCodeAnnotation = (TestCode) annotation; // testCode = TestUtil.loadFile(testCodeAnnotation.fileName()); // } else if (annotation instanceof TestConfig) { // TestConfig testConfigAnnotation = (TestConfig) annotation; // testConfig = TestUtil.loadFile(testConfigAnnotation.fileName()); // } // } // } // // @After // public void after() { // testCode = null; // testConfig = null; // } // } // Path: stylechecker/src/test/java/com/sqatntu/stylechecker/listener/BraceStyleListenerTest.java import com.sqatntu.testutil.ListenerTest; import com.sqatntu.testutil.TestCode; import com.sqatntu.testutil.TestConfig; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 11/10/15. */ public class BraceStyleListenerTest extends ListenerTest { @Test @TestCode( detail = "krStyleCode", fileName = "src/test/resources/stylechecker/BraceKRStyle.java") @TestConfig( detail = "krStyleConfig", fileName = "src/test/resources/stylechecker/BraceKRStyle.json") public void braceStyle1() throws IOException, StyleCheckerException { StyleChecker checker = new StyleChecker();
StyleReport report = checker.checkSourceCode(testCode, testConfig);
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/DefaultConfiguration.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // }
import com.google.common.collect.Maps; import com.sqatntu.stylechecker.StyleCheckerException; import java.util.Map; import java.util.Set;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.configuration; /** * DefaultConfiguration store all configurations in a HashMap. */ public final class DefaultConfiguration implements Configuration { private final Map<String, String> attributeMap = Maps.newHashMap(); @Override public String[] getAttributeNames() { final Set<String> keySet = attributeMap.keySet(); return keySet.toArray(new String[keySet.size()]); } @Override
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/DefaultConfiguration.java import com.google.common.collect.Maps; import com.sqatntu.stylechecker.StyleCheckerException; import java.util.Map; import java.util.Set; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.configuration; /** * DefaultConfiguration store all configurations in a HashMap. */ public final class DefaultConfiguration implements Configuration { private final Map<String, String> attributeMap = Maps.newHashMap(); @Override public String[] getAttributeNames() { final Set<String> keySet = attributeMap.keySet(); return keySet.toArray(new String[keySet.size()]); } @Override
public String getAttribute(String attributeName) throws StyleCheckerException {
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/listener/MethodNameFormatListener.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/StyleName.java // public class StyleName { // // public static final String IGNORE_STYLE = "ignore"; // // public static final String METHOD_NAME_FORMAT = "methodNameFormat"; // public static final String METHOD_NAME_FORMAT_CAMEL_CASE = "camelCase"; // // public static final String WILD_CARD_IMPORT = "wildCardImport"; // public static final String WILD_CARD_IMPORT_OK = "wildCard"; // public static final String WILD_CARD_IMPORT_NO = "noWildCard"; // // public static final String BRACE_STYLE = "braceStyle"; // public static final String BRACE_STYLE_KR = "kr"; // public static final String BRACE_STYLE_NON_KR = "nonKr"; // // public static final String[] ALL_STYLE_NAMES = { // METHOD_NAME_FORMAT, // WILD_CARD_IMPORT, // BRACE_STYLE, // }; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReportContent.java // public class StyleReportContent { // // private int lineNumber; // // private int columnNumber; // // private String message; // // private String suggestion; // // public StyleReportContent(int lineNumber, int columnNumber, String message) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // } // // public StyleReportContent(int lineNumber, int columnNumber, String message, String suggestion) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // this.suggestion = suggestion; // } // // public int getLineNumber() { // return lineNumber; // } // // public int getColumnNumber() { // return columnNumber; // } // // public String getMessage() { // return message; // } // // public String getSuggestion() { // return suggestion; // } // }
import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.StyleName; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.stylechecker.report.StyleReportContent;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Check method name format of source codes * Two method name format is define in {@link StyleName}: * 1. {@link StyleName#METHOD_NAME_FORMAT_CAMEL_CASE} * 2. {@link StyleName#IGNORE_STYLE} * * @see StyleName#METHOD_NAME_FORMAT */ class MethodNameFormatListener extends JavaBaseListener { private Configuration configuration;
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/StyleName.java // public class StyleName { // // public static final String IGNORE_STYLE = "ignore"; // // public static final String METHOD_NAME_FORMAT = "methodNameFormat"; // public static final String METHOD_NAME_FORMAT_CAMEL_CASE = "camelCase"; // // public static final String WILD_CARD_IMPORT = "wildCardImport"; // public static final String WILD_CARD_IMPORT_OK = "wildCard"; // public static final String WILD_CARD_IMPORT_NO = "noWildCard"; // // public static final String BRACE_STYLE = "braceStyle"; // public static final String BRACE_STYLE_KR = "kr"; // public static final String BRACE_STYLE_NON_KR = "nonKr"; // // public static final String[] ALL_STYLE_NAMES = { // METHOD_NAME_FORMAT, // WILD_CARD_IMPORT, // BRACE_STYLE, // }; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReportContent.java // public class StyleReportContent { // // private int lineNumber; // // private int columnNumber; // // private String message; // // private String suggestion; // // public StyleReportContent(int lineNumber, int columnNumber, String message) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // } // // public StyleReportContent(int lineNumber, int columnNumber, String message, String suggestion) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // this.suggestion = suggestion; // } // // public int getLineNumber() { // return lineNumber; // } // // public int getColumnNumber() { // return columnNumber; // } // // public String getMessage() { // return message; // } // // public String getSuggestion() { // return suggestion; // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/MethodNameFormatListener.java import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.StyleName; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.stylechecker.report.StyleReportContent; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Check method name format of source codes * Two method name format is define in {@link StyleName}: * 1. {@link StyleName#METHOD_NAME_FORMAT_CAMEL_CASE} * 2. {@link StyleName#IGNORE_STYLE} * * @see StyleName#METHOD_NAME_FORMAT */ class MethodNameFormatListener extends JavaBaseListener { private Configuration configuration;
private StyleReport report;
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/listener/MethodNameFormatListener.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/StyleName.java // public class StyleName { // // public static final String IGNORE_STYLE = "ignore"; // // public static final String METHOD_NAME_FORMAT = "methodNameFormat"; // public static final String METHOD_NAME_FORMAT_CAMEL_CASE = "camelCase"; // // public static final String WILD_CARD_IMPORT = "wildCardImport"; // public static final String WILD_CARD_IMPORT_OK = "wildCard"; // public static final String WILD_CARD_IMPORT_NO = "noWildCard"; // // public static final String BRACE_STYLE = "braceStyle"; // public static final String BRACE_STYLE_KR = "kr"; // public static final String BRACE_STYLE_NON_KR = "nonKr"; // // public static final String[] ALL_STYLE_NAMES = { // METHOD_NAME_FORMAT, // WILD_CARD_IMPORT, // BRACE_STYLE, // }; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReportContent.java // public class StyleReportContent { // // private int lineNumber; // // private int columnNumber; // // private String message; // // private String suggestion; // // public StyleReportContent(int lineNumber, int columnNumber, String message) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // } // // public StyleReportContent(int lineNumber, int columnNumber, String message, String suggestion) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // this.suggestion = suggestion; // } // // public int getLineNumber() { // return lineNumber; // } // // public int getColumnNumber() { // return columnNumber; // } // // public String getMessage() { // return message; // } // // public String getSuggestion() { // return suggestion; // } // }
import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.StyleName; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.stylechecker.report.StyleReportContent;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Check method name format of source codes * Two method name format is define in {@link StyleName}: * 1. {@link StyleName#METHOD_NAME_FORMAT_CAMEL_CASE} * 2. {@link StyleName#IGNORE_STYLE} * * @see StyleName#METHOD_NAME_FORMAT */ class MethodNameFormatListener extends JavaBaseListener { private Configuration configuration; private StyleReport report; public MethodNameFormatListener(Configuration configuration, StyleReport report) { this.configuration = configuration; this.report = report; } @Override public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { // Determine regular expression by using configuration try { if (configuration
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/StyleName.java // public class StyleName { // // public static final String IGNORE_STYLE = "ignore"; // // public static final String METHOD_NAME_FORMAT = "methodNameFormat"; // public static final String METHOD_NAME_FORMAT_CAMEL_CASE = "camelCase"; // // public static final String WILD_CARD_IMPORT = "wildCardImport"; // public static final String WILD_CARD_IMPORT_OK = "wildCard"; // public static final String WILD_CARD_IMPORT_NO = "noWildCard"; // // public static final String BRACE_STYLE = "braceStyle"; // public static final String BRACE_STYLE_KR = "kr"; // public static final String BRACE_STYLE_NON_KR = "nonKr"; // // public static final String[] ALL_STYLE_NAMES = { // METHOD_NAME_FORMAT, // WILD_CARD_IMPORT, // BRACE_STYLE, // }; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReportContent.java // public class StyleReportContent { // // private int lineNumber; // // private int columnNumber; // // private String message; // // private String suggestion; // // public StyleReportContent(int lineNumber, int columnNumber, String message) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // } // // public StyleReportContent(int lineNumber, int columnNumber, String message, String suggestion) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // this.suggestion = suggestion; // } // // public int getLineNumber() { // return lineNumber; // } // // public int getColumnNumber() { // return columnNumber; // } // // public String getMessage() { // return message; // } // // public String getSuggestion() { // return suggestion; // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/MethodNameFormatListener.java import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.StyleName; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.stylechecker.report.StyleReportContent; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Check method name format of source codes * Two method name format is define in {@link StyleName}: * 1. {@link StyleName#METHOD_NAME_FORMAT_CAMEL_CASE} * 2. {@link StyleName#IGNORE_STYLE} * * @see StyleName#METHOD_NAME_FORMAT */ class MethodNameFormatListener extends JavaBaseListener { private Configuration configuration; private StyleReport report; public MethodNameFormatListener(Configuration configuration, StyleReport report) { this.configuration = configuration; this.report = report; } @Override public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { // Determine regular expression by using configuration try { if (configuration
.getAttribute(StyleName.METHOD_NAME_FORMAT)
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/listener/MethodNameFormatListener.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/StyleName.java // public class StyleName { // // public static final String IGNORE_STYLE = "ignore"; // // public static final String METHOD_NAME_FORMAT = "methodNameFormat"; // public static final String METHOD_NAME_FORMAT_CAMEL_CASE = "camelCase"; // // public static final String WILD_CARD_IMPORT = "wildCardImport"; // public static final String WILD_CARD_IMPORT_OK = "wildCard"; // public static final String WILD_CARD_IMPORT_NO = "noWildCard"; // // public static final String BRACE_STYLE = "braceStyle"; // public static final String BRACE_STYLE_KR = "kr"; // public static final String BRACE_STYLE_NON_KR = "nonKr"; // // public static final String[] ALL_STYLE_NAMES = { // METHOD_NAME_FORMAT, // WILD_CARD_IMPORT, // BRACE_STYLE, // }; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReportContent.java // public class StyleReportContent { // // private int lineNumber; // // private int columnNumber; // // private String message; // // private String suggestion; // // public StyleReportContent(int lineNumber, int columnNumber, String message) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // } // // public StyleReportContent(int lineNumber, int columnNumber, String message, String suggestion) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // this.suggestion = suggestion; // } // // public int getLineNumber() { // return lineNumber; // } // // public int getColumnNumber() { // return columnNumber; // } // // public String getMessage() { // return message; // } // // public String getSuggestion() { // return suggestion; // } // }
import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.StyleName; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.stylechecker.report.StyleReportContent;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Check method name format of source codes * Two method name format is define in {@link StyleName}: * 1. {@link StyleName#METHOD_NAME_FORMAT_CAMEL_CASE} * 2. {@link StyleName#IGNORE_STYLE} * * @see StyleName#METHOD_NAME_FORMAT */ class MethodNameFormatListener extends JavaBaseListener { private Configuration configuration; private StyleReport report; public MethodNameFormatListener(Configuration configuration, StyleReport report) { this.configuration = configuration; this.report = report; } @Override public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { // Determine regular expression by using configuration try { if (configuration .getAttribute(StyleName.METHOD_NAME_FORMAT) .equals(StyleName.IGNORE_STYLE)) { return; }
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/StyleName.java // public class StyleName { // // public static final String IGNORE_STYLE = "ignore"; // // public static final String METHOD_NAME_FORMAT = "methodNameFormat"; // public static final String METHOD_NAME_FORMAT_CAMEL_CASE = "camelCase"; // // public static final String WILD_CARD_IMPORT = "wildCardImport"; // public static final String WILD_CARD_IMPORT_OK = "wildCard"; // public static final String WILD_CARD_IMPORT_NO = "noWildCard"; // // public static final String BRACE_STYLE = "braceStyle"; // public static final String BRACE_STYLE_KR = "kr"; // public static final String BRACE_STYLE_NON_KR = "nonKr"; // // public static final String[] ALL_STYLE_NAMES = { // METHOD_NAME_FORMAT, // WILD_CARD_IMPORT, // BRACE_STYLE, // }; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReportContent.java // public class StyleReportContent { // // private int lineNumber; // // private int columnNumber; // // private String message; // // private String suggestion; // // public StyleReportContent(int lineNumber, int columnNumber, String message) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // } // // public StyleReportContent(int lineNumber, int columnNumber, String message, String suggestion) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // this.suggestion = suggestion; // } // // public int getLineNumber() { // return lineNumber; // } // // public int getColumnNumber() { // return columnNumber; // } // // public String getMessage() { // return message; // } // // public String getSuggestion() { // return suggestion; // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/MethodNameFormatListener.java import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.StyleName; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.stylechecker.report.StyleReportContent; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Check method name format of source codes * Two method name format is define in {@link StyleName}: * 1. {@link StyleName#METHOD_NAME_FORMAT_CAMEL_CASE} * 2. {@link StyleName#IGNORE_STYLE} * * @see StyleName#METHOD_NAME_FORMAT */ class MethodNameFormatListener extends JavaBaseListener { private Configuration configuration; private StyleReport report; public MethodNameFormatListener(Configuration configuration, StyleReport report) { this.configuration = configuration; this.report = report; } @Override public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { // Determine regular expression by using configuration try { if (configuration .getAttribute(StyleName.METHOD_NAME_FORMAT) .equals(StyleName.IGNORE_STYLE)) { return; }
} catch (StyleCheckerException e) {
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/listener/MethodNameFormatListener.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/StyleName.java // public class StyleName { // // public static final String IGNORE_STYLE = "ignore"; // // public static final String METHOD_NAME_FORMAT = "methodNameFormat"; // public static final String METHOD_NAME_FORMAT_CAMEL_CASE = "camelCase"; // // public static final String WILD_CARD_IMPORT = "wildCardImport"; // public static final String WILD_CARD_IMPORT_OK = "wildCard"; // public static final String WILD_CARD_IMPORT_NO = "noWildCard"; // // public static final String BRACE_STYLE = "braceStyle"; // public static final String BRACE_STYLE_KR = "kr"; // public static final String BRACE_STYLE_NON_KR = "nonKr"; // // public static final String[] ALL_STYLE_NAMES = { // METHOD_NAME_FORMAT, // WILD_CARD_IMPORT, // BRACE_STYLE, // }; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReportContent.java // public class StyleReportContent { // // private int lineNumber; // // private int columnNumber; // // private String message; // // private String suggestion; // // public StyleReportContent(int lineNumber, int columnNumber, String message) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // } // // public StyleReportContent(int lineNumber, int columnNumber, String message, String suggestion) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // this.suggestion = suggestion; // } // // public int getLineNumber() { // return lineNumber; // } // // public int getColumnNumber() { // return columnNumber; // } // // public String getMessage() { // return message; // } // // public String getSuggestion() { // return suggestion; // } // }
import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.StyleName; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.stylechecker.report.StyleReportContent;
String methodNameFormatValue = StyleName.METHOD_NAME_FORMAT_CAMEL_CASE; String regex = "^([a-z])([a-zA-Z0-9])*"; // Do matching and add new report String methodName = ctx.getChild(1).getText(); // If there is no problem with the method name if (methodName.matches(regex)) { return; } String message; String suggestion; switch (methodNameFormatValue) { case StyleName.METHOD_NAME_FORMAT_CAMEL_CASE: message = "You should use camel case for method name"; suggestion = "Change method name to " + toCamelCase(methodName); break; default: // This should never happens message = ""; suggestion = ""; break; } int line = ctx.getStart().getLine(); int column = ctx.getStart().getCharPositionInLine() + ctx.getChild(0).getText().length() + 2;
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/StyleName.java // public class StyleName { // // public static final String IGNORE_STYLE = "ignore"; // // public static final String METHOD_NAME_FORMAT = "methodNameFormat"; // public static final String METHOD_NAME_FORMAT_CAMEL_CASE = "camelCase"; // // public static final String WILD_CARD_IMPORT = "wildCardImport"; // public static final String WILD_CARD_IMPORT_OK = "wildCard"; // public static final String WILD_CARD_IMPORT_NO = "noWildCard"; // // public static final String BRACE_STYLE = "braceStyle"; // public static final String BRACE_STYLE_KR = "kr"; // public static final String BRACE_STYLE_NON_KR = "nonKr"; // // public static final String[] ALL_STYLE_NAMES = { // METHOD_NAME_FORMAT, // WILD_CARD_IMPORT, // BRACE_STYLE, // }; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReportContent.java // public class StyleReportContent { // // private int lineNumber; // // private int columnNumber; // // private String message; // // private String suggestion; // // public StyleReportContent(int lineNumber, int columnNumber, String message) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // } // // public StyleReportContent(int lineNumber, int columnNumber, String message, String suggestion) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // this.suggestion = suggestion; // } // // public int getLineNumber() { // return lineNumber; // } // // public int getColumnNumber() { // return columnNumber; // } // // public String getMessage() { // return message; // } // // public String getSuggestion() { // return suggestion; // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/MethodNameFormatListener.java import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.StyleName; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.stylechecker.report.StyleReportContent; String methodNameFormatValue = StyleName.METHOD_NAME_FORMAT_CAMEL_CASE; String regex = "^([a-z])([a-zA-Z0-9])*"; // Do matching and add new report String methodName = ctx.getChild(1).getText(); // If there is no problem with the method name if (methodName.matches(regex)) { return; } String message; String suggestion; switch (methodNameFormatValue) { case StyleName.METHOD_NAME_FORMAT_CAMEL_CASE: message = "You should use camel case for method name"; suggestion = "Change method name to " + toCamelCase(methodName); break; default: // This should never happens message = ""; suggestion = ""; break; } int line = ctx.getStart().getLine(); int column = ctx.getStart().getCharPositionInLine() + ctx.getChild(0).getText().length() + 2;
StyleReportContent reportContent = new StyleReportContent(line, column, message, suggestion);
Andyccs/sqat
stylechecker/src/test/java/com/sqatntu/stylechecker/listener/MethodNameFormatListenerTest.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/TestUtil.java // public class TestUtil { // // public static String loadFile(String filePath) throws IOException { // File file = new File(filePath); // return FileUtils.readFileToString(file); // } // }
import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.testutil.TestUtil; import org.junit.Test;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 6/9/15. */ public class MethodNameFormatListenerTest { @Test
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/TestUtil.java // public class TestUtil { // // public static String loadFile(String filePath) throws IOException { // File file = new File(filePath); // return FileUtils.readFileToString(file); // } // } // Path: stylechecker/src/test/java/com/sqatntu/stylechecker/listener/MethodNameFormatListenerTest.java import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.testutil.TestUtil; import org.junit.Test; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 6/9/15. */ public class MethodNameFormatListenerTest { @Test
public void methodNameFormatWithCamelCase() throws IOException, StyleCheckerException {
Andyccs/sqat
stylechecker/src/test/java/com/sqatntu/stylechecker/listener/MethodNameFormatListenerTest.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/TestUtil.java // public class TestUtil { // // public static String loadFile(String filePath) throws IOException { // File file = new File(filePath); // return FileUtils.readFileToString(file); // } // }
import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.testutil.TestUtil; import org.junit.Test;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 6/9/15. */ public class MethodNameFormatListenerTest { @Test public void methodNameFormatWithCamelCase() throws IOException, StyleCheckerException {
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/TestUtil.java // public class TestUtil { // // public static String loadFile(String filePath) throws IOException { // File file = new File(filePath); // return FileUtils.readFileToString(file); // } // } // Path: stylechecker/src/test/java/com/sqatntu/stylechecker/listener/MethodNameFormatListenerTest.java import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.testutil.TestUtil; import org.junit.Test; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 6/9/15. */ public class MethodNameFormatListenerTest { @Test public void methodNameFormatWithCamelCase() throws IOException, StyleCheckerException {
StyleChecker checker = new StyleChecker();
Andyccs/sqat
stylechecker/src/test/java/com/sqatntu/stylechecker/listener/MethodNameFormatListenerTest.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/TestUtil.java // public class TestUtil { // // public static String loadFile(String filePath) throws IOException { // File file = new File(filePath); // return FileUtils.readFileToString(file); // } // }
import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.testutil.TestUtil; import org.junit.Test;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 6/9/15. */ public class MethodNameFormatListenerTest { @Test public void methodNameFormatWithCamelCase() throws IOException, StyleCheckerException { StyleChecker checker = new StyleChecker();
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/TestUtil.java // public class TestUtil { // // public static String loadFile(String filePath) throws IOException { // File file = new File(filePath); // return FileUtils.readFileToString(file); // } // } // Path: stylechecker/src/test/java/com/sqatntu/stylechecker/listener/MethodNameFormatListenerTest.java import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.testutil.TestUtil; import org.junit.Test; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 6/9/15. */ public class MethodNameFormatListenerTest { @Test public void methodNameFormatWithCamelCase() throws IOException, StyleCheckerException { StyleChecker checker = new StyleChecker();
StyleReport report = checker.checkSourceCode(
Andyccs/sqat
stylechecker/src/test/java/com/sqatntu/stylechecker/listener/MethodNameFormatListenerTest.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/TestUtil.java // public class TestUtil { // // public static String loadFile(String filePath) throws IOException { // File file = new File(filePath); // return FileUtils.readFileToString(file); // } // }
import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.testutil.TestUtil; import org.junit.Test;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 6/9/15. */ public class MethodNameFormatListenerTest { @Test public void methodNameFormatWithCamelCase() throws IOException, StyleCheckerException { StyleChecker checker = new StyleChecker(); StyleReport report = checker.checkSourceCode(
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/TestUtil.java // public class TestUtil { // // public static String loadFile(String filePath) throws IOException { // File file = new File(filePath); // return FileUtils.readFileToString(file); // } // } // Path: stylechecker/src/test/java/com/sqatntu/stylechecker/listener/MethodNameFormatListenerTest.java import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.testutil.TestUtil; import org.junit.Test; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 6/9/15. */ public class MethodNameFormatListenerTest { @Test public void methodNameFormatWithCamelCase() throws IOException, StyleCheckerException { StyleChecker checker = new StyleChecker(); StyleReport report = checker.checkSourceCode(
TestUtil.loadFile("src/test/resources/stylechecker/MethodNameFormatCamelCase.java"),
Andyccs/sqat
stylechecker/src/test/java/com/sqatntu/stylechecker/configuration/JsonConfigurationLoaderTest.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // }
import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleCheckerException; import org.junit.Test; import java.io.IOException;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.configuration; /** * Created by andyccs on 11/9/15. */ public class JsonConfigurationLoaderTest { @Test(expected = IOException.class) public void loadConfigurationFromInvalidPath() throws IOException { String configFilePath = "invalid_path/invalid.json"; JsonConfigurationLoader loader = new JsonConfigurationLoader(); loader.loadFileConfiguration(configFilePath); } @Test
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // Path: stylechecker/src/test/java/com/sqatntu/stylechecker/configuration/JsonConfigurationLoaderTest.java import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleCheckerException; import org.junit.Test; import java.io.IOException; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.configuration; /** * Created by andyccs on 11/9/15. */ public class JsonConfigurationLoaderTest { @Test(expected = IOException.class) public void loadConfigurationFromInvalidPath() throws IOException { String configFilePath = "invalid_path/invalid.json"; JsonConfigurationLoader loader = new JsonConfigurationLoader(); loader.loadFileConfiguration(configFilePath); } @Test
public void loadOneConfiguration() throws StyleCheckerException, IOException {
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // }
import com.sqatntu.stylechecker.StyleCheckerException;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.configuration; /** * Style Checker will check the source codes according to configuration. */ public interface Configuration { String[] getAttributeNames();
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java import com.sqatntu.stylechecker.StyleCheckerException; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.configuration; /** * Style Checker will check the source codes according to configuration. */ public interface Configuration { String[] getAttributeNames();
String getAttribute(String name) throws StyleCheckerException;
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/listener/AllListeners.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // }
import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.report.StyleReport;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Aggregate all {@link JavaBaseListener} so that we only need * {@link org.antlr.v4.runtime.tree.ParseTreeWalker} * to walk the Parse Tree once. */ public class AllListeners extends JavaBaseListener { private MethodNameFormatListener methodNameFormatListener; private WildCardImportStatementListener wildCardImportStatementListener; private BraceStyleListener braceStyleListener;
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/AllListeners.java import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.report.StyleReport; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Aggregate all {@link JavaBaseListener} so that we only need * {@link org.antlr.v4.runtime.tree.ParseTreeWalker} * to walk the Parse Tree once. */ public class AllListeners extends JavaBaseListener { private MethodNameFormatListener methodNameFormatListener; private WildCardImportStatementListener wildCardImportStatementListener; private BraceStyleListener braceStyleListener;
public AllListeners(Configuration configuration, StyleReport report) {
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/listener/AllListeners.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // }
import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.report.StyleReport;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Aggregate all {@link JavaBaseListener} so that we only need * {@link org.antlr.v4.runtime.tree.ParseTreeWalker} * to walk the Parse Tree once. */ public class AllListeners extends JavaBaseListener { private MethodNameFormatListener methodNameFormatListener; private WildCardImportStatementListener wildCardImportStatementListener; private BraceStyleListener braceStyleListener;
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/AllListeners.java import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.report.StyleReport; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Aggregate all {@link JavaBaseListener} so that we only need * {@link org.antlr.v4.runtime.tree.ParseTreeWalker} * to walk the Parse Tree once. */ public class AllListeners extends JavaBaseListener { private MethodNameFormatListener methodNameFormatListener; private WildCardImportStatementListener wildCardImportStatementListener; private BraceStyleListener braceStyleListener;
public AllListeners(Configuration configuration, StyleReport report) {
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java // @Module(injects = {StyleChecker.class}) // public class StyleCheckerModule { // // @Provides // @Singleton // ConfigurationLoader provideConfigurationLoader() { // return new JsonConfigurationLoader(); // } // // @Provides // StyleReport provideStyleReport() { // return new StyleReport(); // } // // @Provides // @Singleton // ThrowingErrorListener provideThrowingErrorListener() { // return new ThrowingErrorListener(); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/AllListeners.java // public class AllListeners extends JavaBaseListener { // // private MethodNameFormatListener methodNameFormatListener; // private WildCardImportStatementListener wildCardImportStatementListener; // private BraceStyleListener braceStyleListener; // // public AllListeners(Configuration configuration, StyleReport report) { // methodNameFormatListener = new MethodNameFormatListener(configuration, report); // wildCardImportStatementListener = new WildCardImportStatementListener(configuration, report); // braceStyleListener = new BraceStyleListener(configuration, report); // } // // @Override // public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { // methodNameFormatListener.enterMethodDeclaration(ctx); // } // // @Override // public void enterImportDeclaration(JavaParser.ImportDeclarationContext ctx) { // wildCardImportStatementListener.enterImportDeclaration(ctx); // } // // @Override // public void enterBlock(com.sqatntu.api.JavaParser.BlockContext ctx) { // braceStyleListener.enterBlock(ctx); // } // // @Override // public void enterClassBody(JavaParser.ClassBodyContext ctx) { // braceStyleListener.enterClassBody(ctx); // } // // @Override // public void enterInterfaceBody(JavaParser.InterfaceBodyContext ctx) { // braceStyleListener.enterInterfaceBody(ctx); // } // // @Override // public void enterStatement(JavaParser.StatementContext ctx) { // braceStyleListener.enterStatement(ctx); // } // // @Override // public void enterCatchClause(JavaParser.CatchClauseContext ctx) { // braceStyleListener.enterCatchClause(ctx); // } // // @Override // public void enterFinallyBlock(JavaParser.FinallyBlockContext ctx) { // braceStyleListener.enterFinallyBlock(ctx); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // }
import dagger.ObjectGraph; import org.antlr.v4.runtime.ANTLRFileStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ParseTreeWalker; import java.io.IOException; import javax.inject.Inject; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.api.JavaLexer; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.injection.StyleCheckerModule; import com.sqatntu.stylechecker.listener.AllListeners; import com.sqatntu.stylechecker.report.StyleReport;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker; /** * StyleChecker provides only one method, i.e. the {@link #checkSourceCode} method. * The method accepts source code and style check configuration and performs style * checking by using Visitor pattern. */ public class StyleChecker { @Inject
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java // @Module(injects = {StyleChecker.class}) // public class StyleCheckerModule { // // @Provides // @Singleton // ConfigurationLoader provideConfigurationLoader() { // return new JsonConfigurationLoader(); // } // // @Provides // StyleReport provideStyleReport() { // return new StyleReport(); // } // // @Provides // @Singleton // ThrowingErrorListener provideThrowingErrorListener() { // return new ThrowingErrorListener(); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/AllListeners.java // public class AllListeners extends JavaBaseListener { // // private MethodNameFormatListener methodNameFormatListener; // private WildCardImportStatementListener wildCardImportStatementListener; // private BraceStyleListener braceStyleListener; // // public AllListeners(Configuration configuration, StyleReport report) { // methodNameFormatListener = new MethodNameFormatListener(configuration, report); // wildCardImportStatementListener = new WildCardImportStatementListener(configuration, report); // braceStyleListener = new BraceStyleListener(configuration, report); // } // // @Override // public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { // methodNameFormatListener.enterMethodDeclaration(ctx); // } // // @Override // public void enterImportDeclaration(JavaParser.ImportDeclarationContext ctx) { // wildCardImportStatementListener.enterImportDeclaration(ctx); // } // // @Override // public void enterBlock(com.sqatntu.api.JavaParser.BlockContext ctx) { // braceStyleListener.enterBlock(ctx); // } // // @Override // public void enterClassBody(JavaParser.ClassBodyContext ctx) { // braceStyleListener.enterClassBody(ctx); // } // // @Override // public void enterInterfaceBody(JavaParser.InterfaceBodyContext ctx) { // braceStyleListener.enterInterfaceBody(ctx); // } // // @Override // public void enterStatement(JavaParser.StatementContext ctx) { // braceStyleListener.enterStatement(ctx); // } // // @Override // public void enterCatchClause(JavaParser.CatchClauseContext ctx) { // braceStyleListener.enterCatchClause(ctx); // } // // @Override // public void enterFinallyBlock(JavaParser.FinallyBlockContext ctx) { // braceStyleListener.enterFinallyBlock(ctx); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java import dagger.ObjectGraph; import org.antlr.v4.runtime.ANTLRFileStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ParseTreeWalker; import java.io.IOException; import javax.inject.Inject; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.api.JavaLexer; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.injection.StyleCheckerModule; import com.sqatntu.stylechecker.listener.AllListeners; import com.sqatntu.stylechecker.report.StyleReport; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker; /** * StyleChecker provides only one method, i.e. the {@link #checkSourceCode} method. * The method accepts source code and style check configuration and performs style * checking by using Visitor pattern. */ public class StyleChecker { @Inject
public StyleReport styleReport;
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java // @Module(injects = {StyleChecker.class}) // public class StyleCheckerModule { // // @Provides // @Singleton // ConfigurationLoader provideConfigurationLoader() { // return new JsonConfigurationLoader(); // } // // @Provides // StyleReport provideStyleReport() { // return new StyleReport(); // } // // @Provides // @Singleton // ThrowingErrorListener provideThrowingErrorListener() { // return new ThrowingErrorListener(); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/AllListeners.java // public class AllListeners extends JavaBaseListener { // // private MethodNameFormatListener methodNameFormatListener; // private WildCardImportStatementListener wildCardImportStatementListener; // private BraceStyleListener braceStyleListener; // // public AllListeners(Configuration configuration, StyleReport report) { // methodNameFormatListener = new MethodNameFormatListener(configuration, report); // wildCardImportStatementListener = new WildCardImportStatementListener(configuration, report); // braceStyleListener = new BraceStyleListener(configuration, report); // } // // @Override // public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { // methodNameFormatListener.enterMethodDeclaration(ctx); // } // // @Override // public void enterImportDeclaration(JavaParser.ImportDeclarationContext ctx) { // wildCardImportStatementListener.enterImportDeclaration(ctx); // } // // @Override // public void enterBlock(com.sqatntu.api.JavaParser.BlockContext ctx) { // braceStyleListener.enterBlock(ctx); // } // // @Override // public void enterClassBody(JavaParser.ClassBodyContext ctx) { // braceStyleListener.enterClassBody(ctx); // } // // @Override // public void enterInterfaceBody(JavaParser.InterfaceBodyContext ctx) { // braceStyleListener.enterInterfaceBody(ctx); // } // // @Override // public void enterStatement(JavaParser.StatementContext ctx) { // braceStyleListener.enterStatement(ctx); // } // // @Override // public void enterCatchClause(JavaParser.CatchClauseContext ctx) { // braceStyleListener.enterCatchClause(ctx); // } // // @Override // public void enterFinallyBlock(JavaParser.FinallyBlockContext ctx) { // braceStyleListener.enterFinallyBlock(ctx); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // }
import dagger.ObjectGraph; import org.antlr.v4.runtime.ANTLRFileStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ParseTreeWalker; import java.io.IOException; import javax.inject.Inject; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.api.JavaLexer; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.injection.StyleCheckerModule; import com.sqatntu.stylechecker.listener.AllListeners; import com.sqatntu.stylechecker.report.StyleReport;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker; /** * StyleChecker provides only one method, i.e. the {@link #checkSourceCode} method. * The method accepts source code and style check configuration and performs style * checking by using Visitor pattern. */ public class StyleChecker { @Inject public StyleReport styleReport; @Inject
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java // @Module(injects = {StyleChecker.class}) // public class StyleCheckerModule { // // @Provides // @Singleton // ConfigurationLoader provideConfigurationLoader() { // return new JsonConfigurationLoader(); // } // // @Provides // StyleReport provideStyleReport() { // return new StyleReport(); // } // // @Provides // @Singleton // ThrowingErrorListener provideThrowingErrorListener() { // return new ThrowingErrorListener(); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/AllListeners.java // public class AllListeners extends JavaBaseListener { // // private MethodNameFormatListener methodNameFormatListener; // private WildCardImportStatementListener wildCardImportStatementListener; // private BraceStyleListener braceStyleListener; // // public AllListeners(Configuration configuration, StyleReport report) { // methodNameFormatListener = new MethodNameFormatListener(configuration, report); // wildCardImportStatementListener = new WildCardImportStatementListener(configuration, report); // braceStyleListener = new BraceStyleListener(configuration, report); // } // // @Override // public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { // methodNameFormatListener.enterMethodDeclaration(ctx); // } // // @Override // public void enterImportDeclaration(JavaParser.ImportDeclarationContext ctx) { // wildCardImportStatementListener.enterImportDeclaration(ctx); // } // // @Override // public void enterBlock(com.sqatntu.api.JavaParser.BlockContext ctx) { // braceStyleListener.enterBlock(ctx); // } // // @Override // public void enterClassBody(JavaParser.ClassBodyContext ctx) { // braceStyleListener.enterClassBody(ctx); // } // // @Override // public void enterInterfaceBody(JavaParser.InterfaceBodyContext ctx) { // braceStyleListener.enterInterfaceBody(ctx); // } // // @Override // public void enterStatement(JavaParser.StatementContext ctx) { // braceStyleListener.enterStatement(ctx); // } // // @Override // public void enterCatchClause(JavaParser.CatchClauseContext ctx) { // braceStyleListener.enterCatchClause(ctx); // } // // @Override // public void enterFinallyBlock(JavaParser.FinallyBlockContext ctx) { // braceStyleListener.enterFinallyBlock(ctx); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java import dagger.ObjectGraph; import org.antlr.v4.runtime.ANTLRFileStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ParseTreeWalker; import java.io.IOException; import javax.inject.Inject; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.api.JavaLexer; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.injection.StyleCheckerModule; import com.sqatntu.stylechecker.listener.AllListeners; import com.sqatntu.stylechecker.report.StyleReport; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker; /** * StyleChecker provides only one method, i.e. the {@link #checkSourceCode} method. * The method accepts source code and style check configuration and performs style * checking by using Visitor pattern. */ public class StyleChecker { @Inject public StyleReport styleReport; @Inject
ConfigurationLoader configurationLoader;
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java // @Module(injects = {StyleChecker.class}) // public class StyleCheckerModule { // // @Provides // @Singleton // ConfigurationLoader provideConfigurationLoader() { // return new JsonConfigurationLoader(); // } // // @Provides // StyleReport provideStyleReport() { // return new StyleReport(); // } // // @Provides // @Singleton // ThrowingErrorListener provideThrowingErrorListener() { // return new ThrowingErrorListener(); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/AllListeners.java // public class AllListeners extends JavaBaseListener { // // private MethodNameFormatListener methodNameFormatListener; // private WildCardImportStatementListener wildCardImportStatementListener; // private BraceStyleListener braceStyleListener; // // public AllListeners(Configuration configuration, StyleReport report) { // methodNameFormatListener = new MethodNameFormatListener(configuration, report); // wildCardImportStatementListener = new WildCardImportStatementListener(configuration, report); // braceStyleListener = new BraceStyleListener(configuration, report); // } // // @Override // public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { // methodNameFormatListener.enterMethodDeclaration(ctx); // } // // @Override // public void enterImportDeclaration(JavaParser.ImportDeclarationContext ctx) { // wildCardImportStatementListener.enterImportDeclaration(ctx); // } // // @Override // public void enterBlock(com.sqatntu.api.JavaParser.BlockContext ctx) { // braceStyleListener.enterBlock(ctx); // } // // @Override // public void enterClassBody(JavaParser.ClassBodyContext ctx) { // braceStyleListener.enterClassBody(ctx); // } // // @Override // public void enterInterfaceBody(JavaParser.InterfaceBodyContext ctx) { // braceStyleListener.enterInterfaceBody(ctx); // } // // @Override // public void enterStatement(JavaParser.StatementContext ctx) { // braceStyleListener.enterStatement(ctx); // } // // @Override // public void enterCatchClause(JavaParser.CatchClauseContext ctx) { // braceStyleListener.enterCatchClause(ctx); // } // // @Override // public void enterFinallyBlock(JavaParser.FinallyBlockContext ctx) { // braceStyleListener.enterFinallyBlock(ctx); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // }
import dagger.ObjectGraph; import org.antlr.v4.runtime.ANTLRFileStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ParseTreeWalker; import java.io.IOException; import javax.inject.Inject; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.api.JavaLexer; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.injection.StyleCheckerModule; import com.sqatntu.stylechecker.listener.AllListeners; import com.sqatntu.stylechecker.report.StyleReport;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker; /** * StyleChecker provides only one method, i.e. the {@link #checkSourceCode} method. * The method accepts source code and style check configuration and performs style * checking by using Visitor pattern. */ public class StyleChecker { @Inject public StyleReport styleReport; @Inject ConfigurationLoader configurationLoader; @Inject
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java // @Module(injects = {StyleChecker.class}) // public class StyleCheckerModule { // // @Provides // @Singleton // ConfigurationLoader provideConfigurationLoader() { // return new JsonConfigurationLoader(); // } // // @Provides // StyleReport provideStyleReport() { // return new StyleReport(); // } // // @Provides // @Singleton // ThrowingErrorListener provideThrowingErrorListener() { // return new ThrowingErrorListener(); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/AllListeners.java // public class AllListeners extends JavaBaseListener { // // private MethodNameFormatListener methodNameFormatListener; // private WildCardImportStatementListener wildCardImportStatementListener; // private BraceStyleListener braceStyleListener; // // public AllListeners(Configuration configuration, StyleReport report) { // methodNameFormatListener = new MethodNameFormatListener(configuration, report); // wildCardImportStatementListener = new WildCardImportStatementListener(configuration, report); // braceStyleListener = new BraceStyleListener(configuration, report); // } // // @Override // public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { // methodNameFormatListener.enterMethodDeclaration(ctx); // } // // @Override // public void enterImportDeclaration(JavaParser.ImportDeclarationContext ctx) { // wildCardImportStatementListener.enterImportDeclaration(ctx); // } // // @Override // public void enterBlock(com.sqatntu.api.JavaParser.BlockContext ctx) { // braceStyleListener.enterBlock(ctx); // } // // @Override // public void enterClassBody(JavaParser.ClassBodyContext ctx) { // braceStyleListener.enterClassBody(ctx); // } // // @Override // public void enterInterfaceBody(JavaParser.InterfaceBodyContext ctx) { // braceStyleListener.enterInterfaceBody(ctx); // } // // @Override // public void enterStatement(JavaParser.StatementContext ctx) { // braceStyleListener.enterStatement(ctx); // } // // @Override // public void enterCatchClause(JavaParser.CatchClauseContext ctx) { // braceStyleListener.enterCatchClause(ctx); // } // // @Override // public void enterFinallyBlock(JavaParser.FinallyBlockContext ctx) { // braceStyleListener.enterFinallyBlock(ctx); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java import dagger.ObjectGraph; import org.antlr.v4.runtime.ANTLRFileStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ParseTreeWalker; import java.io.IOException; import javax.inject.Inject; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.api.JavaLexer; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.injection.StyleCheckerModule; import com.sqatntu.stylechecker.listener.AllListeners; import com.sqatntu.stylechecker.report.StyleReport; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker; /** * StyleChecker provides only one method, i.e. the {@link #checkSourceCode} method. * The method accepts source code and style check configuration and performs style * checking by using Visitor pattern. */ public class StyleChecker { @Inject public StyleReport styleReport; @Inject ConfigurationLoader configurationLoader; @Inject
ThrowingErrorListener throwingErrorListener;
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java // @Module(injects = {StyleChecker.class}) // public class StyleCheckerModule { // // @Provides // @Singleton // ConfigurationLoader provideConfigurationLoader() { // return new JsonConfigurationLoader(); // } // // @Provides // StyleReport provideStyleReport() { // return new StyleReport(); // } // // @Provides // @Singleton // ThrowingErrorListener provideThrowingErrorListener() { // return new ThrowingErrorListener(); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/AllListeners.java // public class AllListeners extends JavaBaseListener { // // private MethodNameFormatListener methodNameFormatListener; // private WildCardImportStatementListener wildCardImportStatementListener; // private BraceStyleListener braceStyleListener; // // public AllListeners(Configuration configuration, StyleReport report) { // methodNameFormatListener = new MethodNameFormatListener(configuration, report); // wildCardImportStatementListener = new WildCardImportStatementListener(configuration, report); // braceStyleListener = new BraceStyleListener(configuration, report); // } // // @Override // public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { // methodNameFormatListener.enterMethodDeclaration(ctx); // } // // @Override // public void enterImportDeclaration(JavaParser.ImportDeclarationContext ctx) { // wildCardImportStatementListener.enterImportDeclaration(ctx); // } // // @Override // public void enterBlock(com.sqatntu.api.JavaParser.BlockContext ctx) { // braceStyleListener.enterBlock(ctx); // } // // @Override // public void enterClassBody(JavaParser.ClassBodyContext ctx) { // braceStyleListener.enterClassBody(ctx); // } // // @Override // public void enterInterfaceBody(JavaParser.InterfaceBodyContext ctx) { // braceStyleListener.enterInterfaceBody(ctx); // } // // @Override // public void enterStatement(JavaParser.StatementContext ctx) { // braceStyleListener.enterStatement(ctx); // } // // @Override // public void enterCatchClause(JavaParser.CatchClauseContext ctx) { // braceStyleListener.enterCatchClause(ctx); // } // // @Override // public void enterFinallyBlock(JavaParser.FinallyBlockContext ctx) { // braceStyleListener.enterFinallyBlock(ctx); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // }
import dagger.ObjectGraph; import org.antlr.v4.runtime.ANTLRFileStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ParseTreeWalker; import java.io.IOException; import javax.inject.Inject; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.api.JavaLexer; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.injection.StyleCheckerModule; import com.sqatntu.stylechecker.listener.AllListeners; import com.sqatntu.stylechecker.report.StyleReport;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker; /** * StyleChecker provides only one method, i.e. the {@link #checkSourceCode} method. * The method accepts source code and style check configuration and performs style * checking by using Visitor pattern. */ public class StyleChecker { @Inject public StyleReport styleReport; @Inject ConfigurationLoader configurationLoader; @Inject ThrowingErrorListener throwingErrorListener; public StyleChecker() {
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java // @Module(injects = {StyleChecker.class}) // public class StyleCheckerModule { // // @Provides // @Singleton // ConfigurationLoader provideConfigurationLoader() { // return new JsonConfigurationLoader(); // } // // @Provides // StyleReport provideStyleReport() { // return new StyleReport(); // } // // @Provides // @Singleton // ThrowingErrorListener provideThrowingErrorListener() { // return new ThrowingErrorListener(); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/AllListeners.java // public class AllListeners extends JavaBaseListener { // // private MethodNameFormatListener methodNameFormatListener; // private WildCardImportStatementListener wildCardImportStatementListener; // private BraceStyleListener braceStyleListener; // // public AllListeners(Configuration configuration, StyleReport report) { // methodNameFormatListener = new MethodNameFormatListener(configuration, report); // wildCardImportStatementListener = new WildCardImportStatementListener(configuration, report); // braceStyleListener = new BraceStyleListener(configuration, report); // } // // @Override // public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { // methodNameFormatListener.enterMethodDeclaration(ctx); // } // // @Override // public void enterImportDeclaration(JavaParser.ImportDeclarationContext ctx) { // wildCardImportStatementListener.enterImportDeclaration(ctx); // } // // @Override // public void enterBlock(com.sqatntu.api.JavaParser.BlockContext ctx) { // braceStyleListener.enterBlock(ctx); // } // // @Override // public void enterClassBody(JavaParser.ClassBodyContext ctx) { // braceStyleListener.enterClassBody(ctx); // } // // @Override // public void enterInterfaceBody(JavaParser.InterfaceBodyContext ctx) { // braceStyleListener.enterInterfaceBody(ctx); // } // // @Override // public void enterStatement(JavaParser.StatementContext ctx) { // braceStyleListener.enterStatement(ctx); // } // // @Override // public void enterCatchClause(JavaParser.CatchClauseContext ctx) { // braceStyleListener.enterCatchClause(ctx); // } // // @Override // public void enterFinallyBlock(JavaParser.FinallyBlockContext ctx) { // braceStyleListener.enterFinallyBlock(ctx); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java import dagger.ObjectGraph; import org.antlr.v4.runtime.ANTLRFileStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ParseTreeWalker; import java.io.IOException; import javax.inject.Inject; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.api.JavaLexer; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.injection.StyleCheckerModule; import com.sqatntu.stylechecker.listener.AllListeners; import com.sqatntu.stylechecker.report.StyleReport; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker; /** * StyleChecker provides only one method, i.e. the {@link #checkSourceCode} method. * The method accepts source code and style check configuration and performs style * checking by using Visitor pattern. */ public class StyleChecker { @Inject public StyleReport styleReport; @Inject ConfigurationLoader configurationLoader; @Inject ThrowingErrorListener throwingErrorListener; public StyleChecker() {
ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule());
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java // @Module(injects = {StyleChecker.class}) // public class StyleCheckerModule { // // @Provides // @Singleton // ConfigurationLoader provideConfigurationLoader() { // return new JsonConfigurationLoader(); // } // // @Provides // StyleReport provideStyleReport() { // return new StyleReport(); // } // // @Provides // @Singleton // ThrowingErrorListener provideThrowingErrorListener() { // return new ThrowingErrorListener(); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/AllListeners.java // public class AllListeners extends JavaBaseListener { // // private MethodNameFormatListener methodNameFormatListener; // private WildCardImportStatementListener wildCardImportStatementListener; // private BraceStyleListener braceStyleListener; // // public AllListeners(Configuration configuration, StyleReport report) { // methodNameFormatListener = new MethodNameFormatListener(configuration, report); // wildCardImportStatementListener = new WildCardImportStatementListener(configuration, report); // braceStyleListener = new BraceStyleListener(configuration, report); // } // // @Override // public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { // methodNameFormatListener.enterMethodDeclaration(ctx); // } // // @Override // public void enterImportDeclaration(JavaParser.ImportDeclarationContext ctx) { // wildCardImportStatementListener.enterImportDeclaration(ctx); // } // // @Override // public void enterBlock(com.sqatntu.api.JavaParser.BlockContext ctx) { // braceStyleListener.enterBlock(ctx); // } // // @Override // public void enterClassBody(JavaParser.ClassBodyContext ctx) { // braceStyleListener.enterClassBody(ctx); // } // // @Override // public void enterInterfaceBody(JavaParser.InterfaceBodyContext ctx) { // braceStyleListener.enterInterfaceBody(ctx); // } // // @Override // public void enterStatement(JavaParser.StatementContext ctx) { // braceStyleListener.enterStatement(ctx); // } // // @Override // public void enterCatchClause(JavaParser.CatchClauseContext ctx) { // braceStyleListener.enterCatchClause(ctx); // } // // @Override // public void enterFinallyBlock(JavaParser.FinallyBlockContext ctx) { // braceStyleListener.enterFinallyBlock(ctx); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // }
import dagger.ObjectGraph; import org.antlr.v4.runtime.ANTLRFileStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ParseTreeWalker; import java.io.IOException; import javax.inject.Inject; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.api.JavaLexer; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.injection.StyleCheckerModule; import com.sqatntu.stylechecker.listener.AllListeners; import com.sqatntu.stylechecker.report.StyleReport;
return check(stream, configuration); } public StyleReport checkSourceCode(String sourceCode, String jsonConfig) throws StyleCheckerException { // Set up configuration loader Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); ANTLRInputStream stream = new ANTLRInputStream(sourceCode); try { return check(stream, configuration); } catch (ParseCancellationException e) { throw new StyleCheckerException(e.getMessage()); } } private StyleReport check(CharStream stream, Configuration config) { JavaLexer lexer = new JavaLexer(stream); lexer.removeErrorListeners(); lexer.addErrorListener(throwingErrorListener); CommonTokenStream tokens = new CommonTokenStream(lexer); JavaParser parser = new JavaParser(tokens); parser.removeErrorListeners(); parser.addErrorListener(throwingErrorListener); JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse
// Path: stylechecker/src/main/java/com/sqatntu/ThrowingErrorListener.java // public class ThrowingErrorListener extends BaseErrorListener { // // @Override // public void syntaxError( // Recognizer<?, ?> recognizer, // Object offendingSymbol, // int line, // int charPositionInLine, // String message, // RecognitionException error) // throws ParseCancellationException { // throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + message); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/ConfigurationLoader.java // public interface ConfigurationLoader { // Configuration loadFileConfiguration(String filePath) throws IOException; // // Configuration loadJsonConfiguration(String json); // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/injection/StyleCheckerModule.java // @Module(injects = {StyleChecker.class}) // public class StyleCheckerModule { // // @Provides // @Singleton // ConfigurationLoader provideConfigurationLoader() { // return new JsonConfigurationLoader(); // } // // @Provides // StyleReport provideStyleReport() { // return new StyleReport(); // } // // @Provides // @Singleton // ThrowingErrorListener provideThrowingErrorListener() { // return new ThrowingErrorListener(); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/AllListeners.java // public class AllListeners extends JavaBaseListener { // // private MethodNameFormatListener methodNameFormatListener; // private WildCardImportStatementListener wildCardImportStatementListener; // private BraceStyleListener braceStyleListener; // // public AllListeners(Configuration configuration, StyleReport report) { // methodNameFormatListener = new MethodNameFormatListener(configuration, report); // wildCardImportStatementListener = new WildCardImportStatementListener(configuration, report); // braceStyleListener = new BraceStyleListener(configuration, report); // } // // @Override // public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) { // methodNameFormatListener.enterMethodDeclaration(ctx); // } // // @Override // public void enterImportDeclaration(JavaParser.ImportDeclarationContext ctx) { // wildCardImportStatementListener.enterImportDeclaration(ctx); // } // // @Override // public void enterBlock(com.sqatntu.api.JavaParser.BlockContext ctx) { // braceStyleListener.enterBlock(ctx); // } // // @Override // public void enterClassBody(JavaParser.ClassBodyContext ctx) { // braceStyleListener.enterClassBody(ctx); // } // // @Override // public void enterInterfaceBody(JavaParser.InterfaceBodyContext ctx) { // braceStyleListener.enterInterfaceBody(ctx); // } // // @Override // public void enterStatement(JavaParser.StatementContext ctx) { // braceStyleListener.enterStatement(ctx); // } // // @Override // public void enterCatchClause(JavaParser.CatchClauseContext ctx) { // braceStyleListener.enterCatchClause(ctx); // } // // @Override // public void enterFinallyBlock(JavaParser.FinallyBlockContext ctx) { // braceStyleListener.enterFinallyBlock(ctx); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java import dagger.ObjectGraph; import org.antlr.v4.runtime.ANTLRFileStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ParseTreeWalker; import java.io.IOException; import javax.inject.Inject; import com.sqatntu.ThrowingErrorListener; import com.sqatntu.api.JavaLexer; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.ConfigurationLoader; import com.sqatntu.stylechecker.injection.StyleCheckerModule; import com.sqatntu.stylechecker.listener.AllListeners; import com.sqatntu.stylechecker.report.StyleReport; return check(stream, configuration); } public StyleReport checkSourceCode(String sourceCode, String jsonConfig) throws StyleCheckerException { // Set up configuration loader Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); ANTLRInputStream stream = new ANTLRInputStream(sourceCode); try { return check(stream, configuration); } catch (ParseCancellationException e) { throw new StyleCheckerException(e.getMessage()); } } private StyleReport check(CharStream stream, Configuration config) { JavaLexer lexer = new JavaLexer(stream); lexer.removeErrorListeners(); lexer.addErrorListener(throwingErrorListener); CommonTokenStream tokens = new CommonTokenStream(lexer); JavaParser parser = new JavaParser(tokens); parser.removeErrorListeners(); parser.addErrorListener(throwingErrorListener); JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse
AllListeners allListeners = new AllListeners(config, styleReport);
Andyccs/sqat
stylechecker/src/test/java/com/sqatntu/testutil/StyleCheckerTest.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // }
import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import org.junit.Test; import java.io.IOException;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.testutil; /** * Created by andyccs on 9/10/15. */ public class StyleCheckerTest { @Test(expected = StyleCheckerException.class) public void nonJavaCode() throws IOException, StyleCheckerException { String javascriptCode = TestUtil.loadFile("src/test/resources/stylechecker/NotJava.js"); String randomConfig = TestUtil.loadFile("src/test/resources/stylechecker/NotJava.json");
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // Path: stylechecker/src/test/java/com/sqatntu/testutil/StyleCheckerTest.java import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import org.junit.Test; import java.io.IOException; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.testutil; /** * Created by andyccs on 9/10/15. */ public class StyleCheckerTest { @Test(expected = StyleCheckerException.class) public void nonJavaCode() throws IOException, StyleCheckerException { String javascriptCode = TestUtil.loadFile("src/test/resources/stylechecker/NotJava.js"); String randomConfig = TestUtil.loadFile("src/test/resources/stylechecker/NotJava.json");
StyleChecker checker = new StyleChecker();
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/listener/WildCardImportStatementListener.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/StyleName.java // public class StyleName { // // public static final String IGNORE_STYLE = "ignore"; // // public static final String METHOD_NAME_FORMAT = "methodNameFormat"; // public static final String METHOD_NAME_FORMAT_CAMEL_CASE = "camelCase"; // // public static final String WILD_CARD_IMPORT = "wildCardImport"; // public static final String WILD_CARD_IMPORT_OK = "wildCard"; // public static final String WILD_CARD_IMPORT_NO = "noWildCard"; // // public static final String BRACE_STYLE = "braceStyle"; // public static final String BRACE_STYLE_KR = "kr"; // public static final String BRACE_STYLE_NON_KR = "nonKr"; // // public static final String[] ALL_STYLE_NAMES = { // METHOD_NAME_FORMAT, // WILD_CARD_IMPORT, // BRACE_STYLE, // }; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReportContent.java // public class StyleReportContent { // // private int lineNumber; // // private int columnNumber; // // private String message; // // private String suggestion; // // public StyleReportContent(int lineNumber, int columnNumber, String message) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // } // // public StyleReportContent(int lineNumber, int columnNumber, String message, String suggestion) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // this.suggestion = suggestion; // } // // public int getLineNumber() { // return lineNumber; // } // // public int getColumnNumber() { // return columnNumber; // } // // public String getMessage() { // return message; // } // // public String getSuggestion() { // return suggestion; // } // }
import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.StyleName; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.stylechecker.report.StyleReportContent;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Check wild card import statement of source codes. * Two wild card import statement style is define in {@link StyleName}: * 1. {@link StyleName#WILD_CARD_IMPORT_NO} * 2. {@link StyleName#WILD_CARD_IMPORT_OK} * 3. {@link StyleName#IGNORE_STYLE} * * @see StyleName#WILD_CARD_IMPORT */ class WildCardImportStatementListener extends JavaBaseListener { private Configuration configuration;
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/StyleName.java // public class StyleName { // // public static final String IGNORE_STYLE = "ignore"; // // public static final String METHOD_NAME_FORMAT = "methodNameFormat"; // public static final String METHOD_NAME_FORMAT_CAMEL_CASE = "camelCase"; // // public static final String WILD_CARD_IMPORT = "wildCardImport"; // public static final String WILD_CARD_IMPORT_OK = "wildCard"; // public static final String WILD_CARD_IMPORT_NO = "noWildCard"; // // public static final String BRACE_STYLE = "braceStyle"; // public static final String BRACE_STYLE_KR = "kr"; // public static final String BRACE_STYLE_NON_KR = "nonKr"; // // public static final String[] ALL_STYLE_NAMES = { // METHOD_NAME_FORMAT, // WILD_CARD_IMPORT, // BRACE_STYLE, // }; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReportContent.java // public class StyleReportContent { // // private int lineNumber; // // private int columnNumber; // // private String message; // // private String suggestion; // // public StyleReportContent(int lineNumber, int columnNumber, String message) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // } // // public StyleReportContent(int lineNumber, int columnNumber, String message, String suggestion) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // this.suggestion = suggestion; // } // // public int getLineNumber() { // return lineNumber; // } // // public int getColumnNumber() { // return columnNumber; // } // // public String getMessage() { // return message; // } // // public String getSuggestion() { // return suggestion; // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/WildCardImportStatementListener.java import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.StyleName; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.stylechecker.report.StyleReportContent; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Check wild card import statement of source codes. * Two wild card import statement style is define in {@link StyleName}: * 1. {@link StyleName#WILD_CARD_IMPORT_NO} * 2. {@link StyleName#WILD_CARD_IMPORT_OK} * 3. {@link StyleName#IGNORE_STYLE} * * @see StyleName#WILD_CARD_IMPORT */ class WildCardImportStatementListener extends JavaBaseListener { private Configuration configuration;
private StyleReport report;
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/listener/WildCardImportStatementListener.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/StyleName.java // public class StyleName { // // public static final String IGNORE_STYLE = "ignore"; // // public static final String METHOD_NAME_FORMAT = "methodNameFormat"; // public static final String METHOD_NAME_FORMAT_CAMEL_CASE = "camelCase"; // // public static final String WILD_CARD_IMPORT = "wildCardImport"; // public static final String WILD_CARD_IMPORT_OK = "wildCard"; // public static final String WILD_CARD_IMPORT_NO = "noWildCard"; // // public static final String BRACE_STYLE = "braceStyle"; // public static final String BRACE_STYLE_KR = "kr"; // public static final String BRACE_STYLE_NON_KR = "nonKr"; // // public static final String[] ALL_STYLE_NAMES = { // METHOD_NAME_FORMAT, // WILD_CARD_IMPORT, // BRACE_STYLE, // }; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReportContent.java // public class StyleReportContent { // // private int lineNumber; // // private int columnNumber; // // private String message; // // private String suggestion; // // public StyleReportContent(int lineNumber, int columnNumber, String message) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // } // // public StyleReportContent(int lineNumber, int columnNumber, String message, String suggestion) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // this.suggestion = suggestion; // } // // public int getLineNumber() { // return lineNumber; // } // // public int getColumnNumber() { // return columnNumber; // } // // public String getMessage() { // return message; // } // // public String getSuggestion() { // return suggestion; // } // }
import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.StyleName; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.stylechecker.report.StyleReportContent;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Check wild card import statement of source codes. * Two wild card import statement style is define in {@link StyleName}: * 1. {@link StyleName#WILD_CARD_IMPORT_NO} * 2. {@link StyleName#WILD_CARD_IMPORT_OK} * 3. {@link StyleName#IGNORE_STYLE} * * @see StyleName#WILD_CARD_IMPORT */ class WildCardImportStatementListener extends JavaBaseListener { private Configuration configuration; private StyleReport report; public WildCardImportStatementListener(Configuration configuration, StyleReport report) { this.configuration = configuration; this.report = report; } @Override public void enterImportDeclaration(JavaParser.ImportDeclarationContext ctx) { super.enterImportDeclaration(ctx); try {
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/StyleName.java // public class StyleName { // // public static final String IGNORE_STYLE = "ignore"; // // public static final String METHOD_NAME_FORMAT = "methodNameFormat"; // public static final String METHOD_NAME_FORMAT_CAMEL_CASE = "camelCase"; // // public static final String WILD_CARD_IMPORT = "wildCardImport"; // public static final String WILD_CARD_IMPORT_OK = "wildCard"; // public static final String WILD_CARD_IMPORT_NO = "noWildCard"; // // public static final String BRACE_STYLE = "braceStyle"; // public static final String BRACE_STYLE_KR = "kr"; // public static final String BRACE_STYLE_NON_KR = "nonKr"; // // public static final String[] ALL_STYLE_NAMES = { // METHOD_NAME_FORMAT, // WILD_CARD_IMPORT, // BRACE_STYLE, // }; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReportContent.java // public class StyleReportContent { // // private int lineNumber; // // private int columnNumber; // // private String message; // // private String suggestion; // // public StyleReportContent(int lineNumber, int columnNumber, String message) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // } // // public StyleReportContent(int lineNumber, int columnNumber, String message, String suggestion) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // this.suggestion = suggestion; // } // // public int getLineNumber() { // return lineNumber; // } // // public int getColumnNumber() { // return columnNumber; // } // // public String getMessage() { // return message; // } // // public String getSuggestion() { // return suggestion; // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/WildCardImportStatementListener.java import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.StyleName; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.stylechecker.report.StyleReportContent; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Check wild card import statement of source codes. * Two wild card import statement style is define in {@link StyleName}: * 1. {@link StyleName#WILD_CARD_IMPORT_NO} * 2. {@link StyleName#WILD_CARD_IMPORT_OK} * 3. {@link StyleName#IGNORE_STYLE} * * @see StyleName#WILD_CARD_IMPORT */ class WildCardImportStatementListener extends JavaBaseListener { private Configuration configuration; private StyleReport report; public WildCardImportStatementListener(Configuration configuration, StyleReport report) { this.configuration = configuration; this.report = report; } @Override public void enterImportDeclaration(JavaParser.ImportDeclarationContext ctx) { super.enterImportDeclaration(ctx); try {
if (configuration.getAttribute(StyleName.WILD_CARD_IMPORT)
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/listener/WildCardImportStatementListener.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/StyleName.java // public class StyleName { // // public static final String IGNORE_STYLE = "ignore"; // // public static final String METHOD_NAME_FORMAT = "methodNameFormat"; // public static final String METHOD_NAME_FORMAT_CAMEL_CASE = "camelCase"; // // public static final String WILD_CARD_IMPORT = "wildCardImport"; // public static final String WILD_CARD_IMPORT_OK = "wildCard"; // public static final String WILD_CARD_IMPORT_NO = "noWildCard"; // // public static final String BRACE_STYLE = "braceStyle"; // public static final String BRACE_STYLE_KR = "kr"; // public static final String BRACE_STYLE_NON_KR = "nonKr"; // // public static final String[] ALL_STYLE_NAMES = { // METHOD_NAME_FORMAT, // WILD_CARD_IMPORT, // BRACE_STYLE, // }; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReportContent.java // public class StyleReportContent { // // private int lineNumber; // // private int columnNumber; // // private String message; // // private String suggestion; // // public StyleReportContent(int lineNumber, int columnNumber, String message) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // } // // public StyleReportContent(int lineNumber, int columnNumber, String message, String suggestion) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // this.suggestion = suggestion; // } // // public int getLineNumber() { // return lineNumber; // } // // public int getColumnNumber() { // return columnNumber; // } // // public String getMessage() { // return message; // } // // public String getSuggestion() { // return suggestion; // } // }
import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.StyleName; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.stylechecker.report.StyleReportContent;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Check wild card import statement of source codes. * Two wild card import statement style is define in {@link StyleName}: * 1. {@link StyleName#WILD_CARD_IMPORT_NO} * 2. {@link StyleName#WILD_CARD_IMPORT_OK} * 3. {@link StyleName#IGNORE_STYLE} * * @see StyleName#WILD_CARD_IMPORT */ class WildCardImportStatementListener extends JavaBaseListener { private Configuration configuration; private StyleReport report; public WildCardImportStatementListener(Configuration configuration, StyleReport report) { this.configuration = configuration; this.report = report; } @Override public void enterImportDeclaration(JavaParser.ImportDeclarationContext ctx) { super.enterImportDeclaration(ctx); try { if (configuration.getAttribute(StyleName.WILD_CARD_IMPORT) .equals(StyleName.WILD_CARD_IMPORT_OK)) { return; }
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/StyleName.java // public class StyleName { // // public static final String IGNORE_STYLE = "ignore"; // // public static final String METHOD_NAME_FORMAT = "methodNameFormat"; // public static final String METHOD_NAME_FORMAT_CAMEL_CASE = "camelCase"; // // public static final String WILD_CARD_IMPORT = "wildCardImport"; // public static final String WILD_CARD_IMPORT_OK = "wildCard"; // public static final String WILD_CARD_IMPORT_NO = "noWildCard"; // // public static final String BRACE_STYLE = "braceStyle"; // public static final String BRACE_STYLE_KR = "kr"; // public static final String BRACE_STYLE_NON_KR = "nonKr"; // // public static final String[] ALL_STYLE_NAMES = { // METHOD_NAME_FORMAT, // WILD_CARD_IMPORT, // BRACE_STYLE, // }; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReportContent.java // public class StyleReportContent { // // private int lineNumber; // // private int columnNumber; // // private String message; // // private String suggestion; // // public StyleReportContent(int lineNumber, int columnNumber, String message) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // } // // public StyleReportContent(int lineNumber, int columnNumber, String message, String suggestion) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // this.suggestion = suggestion; // } // // public int getLineNumber() { // return lineNumber; // } // // public int getColumnNumber() { // return columnNumber; // } // // public String getMessage() { // return message; // } // // public String getSuggestion() { // return suggestion; // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/WildCardImportStatementListener.java import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.StyleName; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.stylechecker.report.StyleReportContent; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Check wild card import statement of source codes. * Two wild card import statement style is define in {@link StyleName}: * 1. {@link StyleName#WILD_CARD_IMPORT_NO} * 2. {@link StyleName#WILD_CARD_IMPORT_OK} * 3. {@link StyleName#IGNORE_STYLE} * * @see StyleName#WILD_CARD_IMPORT */ class WildCardImportStatementListener extends JavaBaseListener { private Configuration configuration; private StyleReport report; public WildCardImportStatementListener(Configuration configuration, StyleReport report) { this.configuration = configuration; this.report = report; } @Override public void enterImportDeclaration(JavaParser.ImportDeclarationContext ctx) { super.enterImportDeclaration(ctx); try { if (configuration.getAttribute(StyleName.WILD_CARD_IMPORT) .equals(StyleName.WILD_CARD_IMPORT_OK)) { return; }
} catch (StyleCheckerException e) {
Andyccs/sqat
stylechecker/src/main/java/com/sqatntu/stylechecker/listener/WildCardImportStatementListener.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/StyleName.java // public class StyleName { // // public static final String IGNORE_STYLE = "ignore"; // // public static final String METHOD_NAME_FORMAT = "methodNameFormat"; // public static final String METHOD_NAME_FORMAT_CAMEL_CASE = "camelCase"; // // public static final String WILD_CARD_IMPORT = "wildCardImport"; // public static final String WILD_CARD_IMPORT_OK = "wildCard"; // public static final String WILD_CARD_IMPORT_NO = "noWildCard"; // // public static final String BRACE_STYLE = "braceStyle"; // public static final String BRACE_STYLE_KR = "kr"; // public static final String BRACE_STYLE_NON_KR = "nonKr"; // // public static final String[] ALL_STYLE_NAMES = { // METHOD_NAME_FORMAT, // WILD_CARD_IMPORT, // BRACE_STYLE, // }; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReportContent.java // public class StyleReportContent { // // private int lineNumber; // // private int columnNumber; // // private String message; // // private String suggestion; // // public StyleReportContent(int lineNumber, int columnNumber, String message) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // } // // public StyleReportContent(int lineNumber, int columnNumber, String message, String suggestion) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // this.suggestion = suggestion; // } // // public int getLineNumber() { // return lineNumber; // } // // public int getColumnNumber() { // return columnNumber; // } // // public String getMessage() { // return message; // } // // public String getSuggestion() { // return suggestion; // } // }
import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.StyleName; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.stylechecker.report.StyleReportContent;
try { if (configuration.getAttribute(StyleName.WILD_CARD_IMPORT) .equals(StyleName.WILD_CARD_IMPORT_OK)) { return; } } catch (StyleCheckerException e) { System.out.println(e.getMessage()); return; } StringBuilder sb = new StringBuilder(); // index 0 is always "import" for (int i = 1; i < ctx.getChildCount(); i++) { sb.append(ctx.getChild(i).getText()); } String importStatement = sb.toString(); String regex = ".+\\.\\*;$"; if (!importStatement.matches(regex)) { return; } int line = ctx.getStart().getLine(); int column = ctx.getStart().getCharPositionInLine() + ctx.getChild(0).getText().length() + 2; String message = "You should not use wild card import statement"; String suggestion = "Split this statement to multiple import statements";
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/Configuration.java // public interface Configuration { // // String[] getAttributeNames(); // // String getAttribute(String name) throws StyleCheckerException; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/configuration/StyleName.java // public class StyleName { // // public static final String IGNORE_STYLE = "ignore"; // // public static final String METHOD_NAME_FORMAT = "methodNameFormat"; // public static final String METHOD_NAME_FORMAT_CAMEL_CASE = "camelCase"; // // public static final String WILD_CARD_IMPORT = "wildCardImport"; // public static final String WILD_CARD_IMPORT_OK = "wildCard"; // public static final String WILD_CARD_IMPORT_NO = "noWildCard"; // // public static final String BRACE_STYLE = "braceStyle"; // public static final String BRACE_STYLE_KR = "kr"; // public static final String BRACE_STYLE_NON_KR = "nonKr"; // // public static final String[] ALL_STYLE_NAMES = { // METHOD_NAME_FORMAT, // WILD_CARD_IMPORT, // BRACE_STYLE, // }; // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReportContent.java // public class StyleReportContent { // // private int lineNumber; // // private int columnNumber; // // private String message; // // private String suggestion; // // public StyleReportContent(int lineNumber, int columnNumber, String message) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // } // // public StyleReportContent(int lineNumber, int columnNumber, String message, String suggestion) { // this.lineNumber = lineNumber; // this.columnNumber = columnNumber; // this.message = message; // this.suggestion = suggestion; // } // // public int getLineNumber() { // return lineNumber; // } // // public int getColumnNumber() { // return columnNumber; // } // // public String getMessage() { // return message; // } // // public String getSuggestion() { // return suggestion; // } // } // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/listener/WildCardImportStatementListener.java import com.sqatntu.api.JavaBaseListener; import com.sqatntu.api.JavaParser; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.configuration.Configuration; import com.sqatntu.stylechecker.configuration.StyleName; import com.sqatntu.stylechecker.report.StyleReport; import com.sqatntu.stylechecker.report.StyleReportContent; try { if (configuration.getAttribute(StyleName.WILD_CARD_IMPORT) .equals(StyleName.WILD_CARD_IMPORT_OK)) { return; } } catch (StyleCheckerException e) { System.out.println(e.getMessage()); return; } StringBuilder sb = new StringBuilder(); // index 0 is always "import" for (int i = 1; i < ctx.getChildCount(); i++) { sb.append(ctx.getChild(i).getText()); } String importStatement = sb.toString(); String regex = ".+\\.\\*;$"; if (!importStatement.matches(regex)) { return; } int line = ctx.getStart().getLine(); int column = ctx.getStart().getCharPositionInLine() + ctx.getChild(0).getText().length() + 2; String message = "You should not use wild card import statement"; String suggestion = "Split this statement to multiple import statements";
StyleReportContent reportContent = new StyleReportContent(line, column, message, suggestion);
Andyccs/sqat
stylechecker/src/test/java/com/sqatntu/stylechecker/listener/WildCardImportStatementListenerTest.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/TestUtil.java // public class TestUtil { // // public static String loadFile(String filePath) throws IOException { // File file = new File(filePath); // return FileUtils.readFileToString(file); // } // }
import com.sqatntu.testutil.TestUtil; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 22/9/15. */ public class WildCardImportStatementListenerTest { @Test
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/TestUtil.java // public class TestUtil { // // public static String loadFile(String filePath) throws IOException { // File file = new File(filePath); // return FileUtils.readFileToString(file); // } // } // Path: stylechecker/src/test/java/com/sqatntu/stylechecker/listener/WildCardImportStatementListenerTest.java import com.sqatntu.testutil.TestUtil; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 22/9/15. */ public class WildCardImportStatementListenerTest { @Test
public void importStatementsWithoutWildCard() throws IOException, StyleCheckerException {
Andyccs/sqat
stylechecker/src/test/java/com/sqatntu/stylechecker/listener/WildCardImportStatementListenerTest.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/TestUtil.java // public class TestUtil { // // public static String loadFile(String filePath) throws IOException { // File file = new File(filePath); // return FileUtils.readFileToString(file); // } // }
import com.sqatntu.testutil.TestUtil; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 22/9/15. */ public class WildCardImportStatementListenerTest { @Test public void importStatementsWithoutWildCard() throws IOException, StyleCheckerException {
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/TestUtil.java // public class TestUtil { // // public static String loadFile(String filePath) throws IOException { // File file = new File(filePath); // return FileUtils.readFileToString(file); // } // } // Path: stylechecker/src/test/java/com/sqatntu/stylechecker/listener/WildCardImportStatementListenerTest.java import com.sqatntu.testutil.TestUtil; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 22/9/15. */ public class WildCardImportStatementListenerTest { @Test public void importStatementsWithoutWildCard() throws IOException, StyleCheckerException {
StyleChecker checker = new StyleChecker();
Andyccs/sqat
stylechecker/src/test/java/com/sqatntu/stylechecker/listener/WildCardImportStatementListenerTest.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/TestUtil.java // public class TestUtil { // // public static String loadFile(String filePath) throws IOException { // File file = new File(filePath); // return FileUtils.readFileToString(file); // } // }
import com.sqatntu.testutil.TestUtil; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 22/9/15. */ public class WildCardImportStatementListenerTest { @Test public void importStatementsWithoutWildCard() throws IOException, StyleCheckerException { StyleChecker checker = new StyleChecker();
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/TestUtil.java // public class TestUtil { // // public static String loadFile(String filePath) throws IOException { // File file = new File(filePath); // return FileUtils.readFileToString(file); // } // } // Path: stylechecker/src/test/java/com/sqatntu/stylechecker/listener/WildCardImportStatementListenerTest.java import com.sqatntu.testutil.TestUtil; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 22/9/15. */ public class WildCardImportStatementListenerTest { @Test public void importStatementsWithoutWildCard() throws IOException, StyleCheckerException { StyleChecker checker = new StyleChecker();
StyleReport report = checker.checkSourceCode(
Andyccs/sqat
stylechecker/src/test/java/com/sqatntu/stylechecker/listener/WildCardImportStatementListenerTest.java
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/TestUtil.java // public class TestUtil { // // public static String loadFile(String filePath) throws IOException { // File file = new File(filePath); // return FileUtils.readFileToString(file); // } // }
import com.sqatntu.testutil.TestUtil; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport;
/* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 22/9/15. */ public class WildCardImportStatementListenerTest { @Test public void importStatementsWithoutWildCard() throws IOException, StyleCheckerException { StyleChecker checker = new StyleChecker(); StyleReport report = checker.checkSourceCode(
// Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleChecker.java // public class StyleChecker { // // @Inject // public StyleReport styleReport; // // @Inject // ConfigurationLoader configurationLoader; // // @Inject // ThrowingErrorListener throwingErrorListener; // // public StyleChecker() { // ObjectGraph objectGraph = ObjectGraph.create(new StyleCheckerModule()); // objectGraph.inject(this); // } // // @Deprecated // public StyleReport checkFile(String filePath, String configPath) throws IOException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadFileConfiguration(configPath); // ANTLRFileStream stream = new ANTLRFileStream(filePath); // // return check(stream, configuration); // } // // public StyleReport checkSourceCode(String sourceCode, String jsonConfig) // throws StyleCheckerException { // // Set up configuration loader // Configuration configuration = configurationLoader.loadJsonConfiguration(jsonConfig); // // ANTLRInputStream stream = new ANTLRInputStream(sourceCode); // // try { // return check(stream, configuration); // } catch (ParseCancellationException e) { // throw new StyleCheckerException(e.getMessage()); // } // } // // private StyleReport check(CharStream stream, Configuration config) { // JavaLexer lexer = new JavaLexer(stream); // lexer.removeErrorListeners(); // lexer.addErrorListener(throwingErrorListener); // // CommonTokenStream tokens = new CommonTokenStream(lexer); // // JavaParser parser = new JavaParser(tokens); // parser.removeErrorListeners(); // parser.addErrorListener(throwingErrorListener); // // JavaParser.CompilationUnitContext tree = parser.compilationUnit(); // parse // // AllListeners allListeners = new AllListeners(config, styleReport); // ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker // walker.walk(allListeners, tree); // // return styleReport; // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/StyleCheckerException.java // public class StyleCheckerException extends Exception { // // public StyleCheckerException(String message) { // super(message); // } // // public StyleCheckerException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: stylechecker/src/main/java/com/sqatntu/stylechecker/report/StyleReport.java // public class StyleReport { // // List<StyleReportContent> reportContents; // // public StyleReport() { // reportContents = new ArrayList<>(); // } // // public List<StyleReportContent> getReportContents() { // return ImmutableList.<StyleReportContent>builder().addAll(reportContents).build(); // } // // public void addReportContents(StyleReportContent reportContents) { // this.reportContents.add(reportContents); // } // } // // Path: stylechecker/src/test/java/com/sqatntu/testutil/TestUtil.java // public class TestUtil { // // public static String loadFile(String filePath) throws IOException { // File file = new File(filePath); // return FileUtils.readFileToString(file); // } // } // Path: stylechecker/src/test/java/com/sqatntu/stylechecker/listener/WildCardImportStatementListenerTest.java import com.sqatntu.testutil.TestUtil; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; import com.sqatntu.stylechecker.StyleChecker; import com.sqatntu.stylechecker.StyleCheckerException; import com.sqatntu.stylechecker.report.StyleReport; /* * The MIT License (MIT) * * Copyright (c) 2015 Andy Chong Chin Shin * * 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.sqatntu.stylechecker.listener; /** * Created by andyccs on 22/9/15. */ public class WildCardImportStatementListenerTest { @Test public void importStatementsWithoutWildCard() throws IOException, StyleCheckerException { StyleChecker checker = new StyleChecker(); StyleReport report = checker.checkSourceCode(
TestUtil.loadFile("src/test/resources/stylechecker/WildCardImportStatementNoWildCard.java"),
juga999/easy-com-display
src/main/java/org/chorem/ecd/dao/PlaylistDao.java
// Path: src/main/java/org/chorem/ecd/model/Playlist.java // public class Playlist { // // private UUID id; // // private List<SignageStream> streams = Lists.newArrayList(); // // private List<NewsFeed> newsFeeds = Lists.newArrayList(); // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public List<SignageStream> getStreams() { // return streams; // } // // public void setStreams(List<SignageStream> streams) { // this.streams = streams; // } // // public List<NewsFeed> getNewsFeeds() { // return newsFeeds; // } // // public void setNewsFeeds(List<NewsFeed> newsFeeds) { // this.newsFeeds = newsFeeds; // } // // } // // Path: src/main/java/org/chorem/ecd/model/news/NewsFeed.java // public class NewsFeed { // // private UUID id; // // private String name; // // private String url; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getUrl() { // return url; // } // // public URL getParsedUrl() { // URL parsedUrl = null; // try { // parsedUrl = new URL(getUrl()); // } catch (MalformedURLException e) { // } // return parsedUrl; // } // // public void setUrl(String url) { // this.url = url; // } // } // // Path: src/main/java/org/chorem/ecd/model/stream/SignageStream.java // public class SignageStream { // // private UUID id; // // private String name; // // private Integer timing; // // private LocalDateTime creationDateTime; // // private LocalDateTime lastUpdateDateTime; // // private List<SignageStreamFrame> frames; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getTiming() { // return timing; // } // // public void setTiming(Integer timing) { // this.timing = timing; // } // // public LocalDateTime getCreationDateTime() { // return creationDateTime; // } // // public void setCreationDateTime(LocalDateTime creationDateTime) { // this.creationDateTime = creationDateTime; // } // // public LocalDateTime getLastUpdateDateTime() { // return lastUpdateDateTime; // } // // public void setLastUpdateDateTime(LocalDateTime lastUpdateDateTime) { // this.lastUpdateDateTime = lastUpdateDateTime; // } // // public List<SignageStreamFrame> getFrames() { // return frames; // } // // public void setFrames(List<SignageStreamFrame> frames) { // this.frames = frames; // } // }
import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.gson.reflect.TypeToken; import org.chorem.ecd.model.Playlist; import org.chorem.ecd.model.news.NewsFeed; import org.chorem.ecd.model.stream.SignageStream; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.RecordMapper; import org.jooq.Table; import org.jooq.impl.DSL; import org.jooq.util.postgres.PostgresDSL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import java.lang.reflect.Type; import java.util.List; import java.util.UUID; import static org.chorem.ecd.mapping.tables.Playlist.PLAYLIST; import static org.chorem.ecd.mapping.tables.SignageStream.SIGNAGE_STREAM; import static org.chorem.ecd.mapping.tables.NewsFeed.NEWS_FEED;
package org.chorem.ecd.dao; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class PlaylistDao extends AbstractDao<Playlist, UUID> { private static final Logger logger = LoggerFactory.getLogger(PlaylistDao.class);
// Path: src/main/java/org/chorem/ecd/model/Playlist.java // public class Playlist { // // private UUID id; // // private List<SignageStream> streams = Lists.newArrayList(); // // private List<NewsFeed> newsFeeds = Lists.newArrayList(); // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public List<SignageStream> getStreams() { // return streams; // } // // public void setStreams(List<SignageStream> streams) { // this.streams = streams; // } // // public List<NewsFeed> getNewsFeeds() { // return newsFeeds; // } // // public void setNewsFeeds(List<NewsFeed> newsFeeds) { // this.newsFeeds = newsFeeds; // } // // } // // Path: src/main/java/org/chorem/ecd/model/news/NewsFeed.java // public class NewsFeed { // // private UUID id; // // private String name; // // private String url; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getUrl() { // return url; // } // // public URL getParsedUrl() { // URL parsedUrl = null; // try { // parsedUrl = new URL(getUrl()); // } catch (MalformedURLException e) { // } // return parsedUrl; // } // // public void setUrl(String url) { // this.url = url; // } // } // // Path: src/main/java/org/chorem/ecd/model/stream/SignageStream.java // public class SignageStream { // // private UUID id; // // private String name; // // private Integer timing; // // private LocalDateTime creationDateTime; // // private LocalDateTime lastUpdateDateTime; // // private List<SignageStreamFrame> frames; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getTiming() { // return timing; // } // // public void setTiming(Integer timing) { // this.timing = timing; // } // // public LocalDateTime getCreationDateTime() { // return creationDateTime; // } // // public void setCreationDateTime(LocalDateTime creationDateTime) { // this.creationDateTime = creationDateTime; // } // // public LocalDateTime getLastUpdateDateTime() { // return lastUpdateDateTime; // } // // public void setLastUpdateDateTime(LocalDateTime lastUpdateDateTime) { // this.lastUpdateDateTime = lastUpdateDateTime; // } // // public List<SignageStreamFrame> getFrames() { // return frames; // } // // public void setFrames(List<SignageStreamFrame> frames) { // this.frames = frames; // } // } // Path: src/main/java/org/chorem/ecd/dao/PlaylistDao.java import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.gson.reflect.TypeToken; import org.chorem.ecd.model.Playlist; import org.chorem.ecd.model.news.NewsFeed; import org.chorem.ecd.model.stream.SignageStream; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.RecordMapper; import org.jooq.Table; import org.jooq.impl.DSL; import org.jooq.util.postgres.PostgresDSL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import java.lang.reflect.Type; import java.util.List; import java.util.UUID; import static org.chorem.ecd.mapping.tables.Playlist.PLAYLIST; import static org.chorem.ecd.mapping.tables.SignageStream.SIGNAGE_STREAM; import static org.chorem.ecd.mapping.tables.NewsFeed.NEWS_FEED; package org.chorem.ecd.dao; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class PlaylistDao extends AbstractDao<Playlist, UUID> { private static final Logger logger = LoggerFactory.getLogger(PlaylistDao.class);
private final Type streamsListType = new TypeToken<List<SignageStream>>(){}.getType();
juga999/easy-com-display
src/main/java/org/chorem/ecd/dao/PlaylistDao.java
// Path: src/main/java/org/chorem/ecd/model/Playlist.java // public class Playlist { // // private UUID id; // // private List<SignageStream> streams = Lists.newArrayList(); // // private List<NewsFeed> newsFeeds = Lists.newArrayList(); // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public List<SignageStream> getStreams() { // return streams; // } // // public void setStreams(List<SignageStream> streams) { // this.streams = streams; // } // // public List<NewsFeed> getNewsFeeds() { // return newsFeeds; // } // // public void setNewsFeeds(List<NewsFeed> newsFeeds) { // this.newsFeeds = newsFeeds; // } // // } // // Path: src/main/java/org/chorem/ecd/model/news/NewsFeed.java // public class NewsFeed { // // private UUID id; // // private String name; // // private String url; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getUrl() { // return url; // } // // public URL getParsedUrl() { // URL parsedUrl = null; // try { // parsedUrl = new URL(getUrl()); // } catch (MalformedURLException e) { // } // return parsedUrl; // } // // public void setUrl(String url) { // this.url = url; // } // } // // Path: src/main/java/org/chorem/ecd/model/stream/SignageStream.java // public class SignageStream { // // private UUID id; // // private String name; // // private Integer timing; // // private LocalDateTime creationDateTime; // // private LocalDateTime lastUpdateDateTime; // // private List<SignageStreamFrame> frames; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getTiming() { // return timing; // } // // public void setTiming(Integer timing) { // this.timing = timing; // } // // public LocalDateTime getCreationDateTime() { // return creationDateTime; // } // // public void setCreationDateTime(LocalDateTime creationDateTime) { // this.creationDateTime = creationDateTime; // } // // public LocalDateTime getLastUpdateDateTime() { // return lastUpdateDateTime; // } // // public void setLastUpdateDateTime(LocalDateTime lastUpdateDateTime) { // this.lastUpdateDateTime = lastUpdateDateTime; // } // // public List<SignageStreamFrame> getFrames() { // return frames; // } // // public void setFrames(List<SignageStreamFrame> frames) { // this.frames = frames; // } // }
import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.gson.reflect.TypeToken; import org.chorem.ecd.model.Playlist; import org.chorem.ecd.model.news.NewsFeed; import org.chorem.ecd.model.stream.SignageStream; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.RecordMapper; import org.jooq.Table; import org.jooq.impl.DSL; import org.jooq.util.postgres.PostgresDSL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import java.lang.reflect.Type; import java.util.List; import java.util.UUID; import static org.chorem.ecd.mapping.tables.Playlist.PLAYLIST; import static org.chorem.ecd.mapping.tables.SignageStream.SIGNAGE_STREAM; import static org.chorem.ecd.mapping.tables.NewsFeed.NEWS_FEED;
package org.chorem.ecd.dao; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class PlaylistDao extends AbstractDao<Playlist, UUID> { private static final Logger logger = LoggerFactory.getLogger(PlaylistDao.class); private final Type streamsListType = new TypeToken<List<SignageStream>>(){}.getType();
// Path: src/main/java/org/chorem/ecd/model/Playlist.java // public class Playlist { // // private UUID id; // // private List<SignageStream> streams = Lists.newArrayList(); // // private List<NewsFeed> newsFeeds = Lists.newArrayList(); // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public List<SignageStream> getStreams() { // return streams; // } // // public void setStreams(List<SignageStream> streams) { // this.streams = streams; // } // // public List<NewsFeed> getNewsFeeds() { // return newsFeeds; // } // // public void setNewsFeeds(List<NewsFeed> newsFeeds) { // this.newsFeeds = newsFeeds; // } // // } // // Path: src/main/java/org/chorem/ecd/model/news/NewsFeed.java // public class NewsFeed { // // private UUID id; // // private String name; // // private String url; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getUrl() { // return url; // } // // public URL getParsedUrl() { // URL parsedUrl = null; // try { // parsedUrl = new URL(getUrl()); // } catch (MalformedURLException e) { // } // return parsedUrl; // } // // public void setUrl(String url) { // this.url = url; // } // } // // Path: src/main/java/org/chorem/ecd/model/stream/SignageStream.java // public class SignageStream { // // private UUID id; // // private String name; // // private Integer timing; // // private LocalDateTime creationDateTime; // // private LocalDateTime lastUpdateDateTime; // // private List<SignageStreamFrame> frames; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getTiming() { // return timing; // } // // public void setTiming(Integer timing) { // this.timing = timing; // } // // public LocalDateTime getCreationDateTime() { // return creationDateTime; // } // // public void setCreationDateTime(LocalDateTime creationDateTime) { // this.creationDateTime = creationDateTime; // } // // public LocalDateTime getLastUpdateDateTime() { // return lastUpdateDateTime; // } // // public void setLastUpdateDateTime(LocalDateTime lastUpdateDateTime) { // this.lastUpdateDateTime = lastUpdateDateTime; // } // // public List<SignageStreamFrame> getFrames() { // return frames; // } // // public void setFrames(List<SignageStreamFrame> frames) { // this.frames = frames; // } // } // Path: src/main/java/org/chorem/ecd/dao/PlaylistDao.java import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.gson.reflect.TypeToken; import org.chorem.ecd.model.Playlist; import org.chorem.ecd.model.news.NewsFeed; import org.chorem.ecd.model.stream.SignageStream; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.RecordMapper; import org.jooq.Table; import org.jooq.impl.DSL; import org.jooq.util.postgres.PostgresDSL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import java.lang.reflect.Type; import java.util.List; import java.util.UUID; import static org.chorem.ecd.mapping.tables.Playlist.PLAYLIST; import static org.chorem.ecd.mapping.tables.SignageStream.SIGNAGE_STREAM; import static org.chorem.ecd.mapping.tables.NewsFeed.NEWS_FEED; package org.chorem.ecd.dao; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class PlaylistDao extends AbstractDao<Playlist, UUID> { private static final Logger logger = LoggerFactory.getLogger(PlaylistDao.class); private final Type streamsListType = new TypeToken<List<SignageStream>>(){}.getType();
private final Type newsFeedsListType = new TypeToken<List<NewsFeed>>(){}.getType();
juga999/easy-com-display
src/main/java/org/chorem/ecd/dao/SettingsDao.java
// Path: src/main/java/org/chorem/ecd/model/settings/Location.java // public class Location { // private int id; // // private String name; // // private String weatherForecastUrl; // // public Location() { // } // // public Location(String name, String weatherForecastUrl) { // this.name = name; // this.weatherForecastUrl = weatherForecastUrl; // } // // 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; // } // // public String getWeatherForecastUrl() { // return weatherForecastUrl; // } // // public void setWeatherForecastUrl(String weatherForecastUrl) { // this.weatherForecastUrl = weatherForecastUrl; // } // // } // // Path: src/main/java/org/chorem/ecd/model/settings/Settings.java // public class Settings { // private Location location; // // private TvTimes tvTimes; // // public Location getLocation() { // return location; // } // // public void setLocation(Location location) { // this.location = location; // } // // public TvTimes getTvTimes() { // return tvTimes; // } // // public void setTvTimes(TvTimes tvTimes) { // this.tvTimes = tvTimes; // } // } // // Path: src/main/java/org/chorem/ecd/model/settings/TvTimes.java // public class TvTimes { // // private String wakeupTime; // // private String sleepTime; // // public TvTimes() { // // } // // public TvTimes(String wakeupTime, String sleepTime) { // this.wakeupTime = wakeupTime; // this.sleepTime = sleepTime; // } // // public String getWakeupTime() { // return wakeupTime; // } // // public void setWakeupTime(String wakeupTime) { // this.wakeupTime = wakeupTime; // } // // public String getSleepTime() { // return sleepTime; // } // // public void setSleepTime(String sleepTime) { // this.sleepTime = sleepTime; // } // // }
import org.chorem.ecd.model.settings.Location; import org.chorem.ecd.model.settings.Settings; import org.chorem.ecd.model.settings.TvTimes; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.RecordMapper; import org.jooq.impl.DSL; import org.jooq.util.postgres.PostgresDataType; import javax.enterprise.context.ApplicationScoped; import java.util.Optional; import static org.chorem.ecd.mapping.tables.Settings.SETTINGS;
package org.chorem.ecd.dao; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class SettingsDao extends AbstractDao<Settings, Integer> { public SettingsDao() { super(Settings.class, SETTINGS, SETTINGS.ID::eq); }
// Path: src/main/java/org/chorem/ecd/model/settings/Location.java // public class Location { // private int id; // // private String name; // // private String weatherForecastUrl; // // public Location() { // } // // public Location(String name, String weatherForecastUrl) { // this.name = name; // this.weatherForecastUrl = weatherForecastUrl; // } // // 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; // } // // public String getWeatherForecastUrl() { // return weatherForecastUrl; // } // // public void setWeatherForecastUrl(String weatherForecastUrl) { // this.weatherForecastUrl = weatherForecastUrl; // } // // } // // Path: src/main/java/org/chorem/ecd/model/settings/Settings.java // public class Settings { // private Location location; // // private TvTimes tvTimes; // // public Location getLocation() { // return location; // } // // public void setLocation(Location location) { // this.location = location; // } // // public TvTimes getTvTimes() { // return tvTimes; // } // // public void setTvTimes(TvTimes tvTimes) { // this.tvTimes = tvTimes; // } // } // // Path: src/main/java/org/chorem/ecd/model/settings/TvTimes.java // public class TvTimes { // // private String wakeupTime; // // private String sleepTime; // // public TvTimes() { // // } // // public TvTimes(String wakeupTime, String sleepTime) { // this.wakeupTime = wakeupTime; // this.sleepTime = sleepTime; // } // // public String getWakeupTime() { // return wakeupTime; // } // // public void setWakeupTime(String wakeupTime) { // this.wakeupTime = wakeupTime; // } // // public String getSleepTime() { // return sleepTime; // } // // public void setSleepTime(String sleepTime) { // this.sleepTime = sleepTime; // } // // } // Path: src/main/java/org/chorem/ecd/dao/SettingsDao.java import org.chorem.ecd.model.settings.Location; import org.chorem.ecd.model.settings.Settings; import org.chorem.ecd.model.settings.TvTimes; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.RecordMapper; import org.jooq.impl.DSL; import org.jooq.util.postgres.PostgresDataType; import javax.enterprise.context.ApplicationScoped; import java.util.Optional; import static org.chorem.ecd.mapping.tables.Settings.SETTINGS; package org.chorem.ecd.dao; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class SettingsDao extends AbstractDao<Settings, Integer> { public SettingsDao() { super(Settings.class, SETTINGS, SETTINGS.ID::eq); }
public TvTimes getTvTimes() {
juga999/easy-com-display
src/main/java/org/chorem/ecd/dao/SettingsDao.java
// Path: src/main/java/org/chorem/ecd/model/settings/Location.java // public class Location { // private int id; // // private String name; // // private String weatherForecastUrl; // // public Location() { // } // // public Location(String name, String weatherForecastUrl) { // this.name = name; // this.weatherForecastUrl = weatherForecastUrl; // } // // 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; // } // // public String getWeatherForecastUrl() { // return weatherForecastUrl; // } // // public void setWeatherForecastUrl(String weatherForecastUrl) { // this.weatherForecastUrl = weatherForecastUrl; // } // // } // // Path: src/main/java/org/chorem/ecd/model/settings/Settings.java // public class Settings { // private Location location; // // private TvTimes tvTimes; // // public Location getLocation() { // return location; // } // // public void setLocation(Location location) { // this.location = location; // } // // public TvTimes getTvTimes() { // return tvTimes; // } // // public void setTvTimes(TvTimes tvTimes) { // this.tvTimes = tvTimes; // } // } // // Path: src/main/java/org/chorem/ecd/model/settings/TvTimes.java // public class TvTimes { // // private String wakeupTime; // // private String sleepTime; // // public TvTimes() { // // } // // public TvTimes(String wakeupTime, String sleepTime) { // this.wakeupTime = wakeupTime; // this.sleepTime = sleepTime; // } // // public String getWakeupTime() { // return wakeupTime; // } // // public void setWakeupTime(String wakeupTime) { // this.wakeupTime = wakeupTime; // } // // public String getSleepTime() { // return sleepTime; // } // // public void setSleepTime(String sleepTime) { // this.sleepTime = sleepTime; // } // // }
import org.chorem.ecd.model.settings.Location; import org.chorem.ecd.model.settings.Settings; import org.chorem.ecd.model.settings.TvTimes; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.RecordMapper; import org.jooq.impl.DSL; import org.jooq.util.postgres.PostgresDataType; import javax.enterprise.context.ApplicationScoped; import java.util.Optional; import static org.chorem.ecd.mapping.tables.Settings.SETTINGS;
package org.chorem.ecd.dao; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class SettingsDao extends AbstractDao<Settings, Integer> { public SettingsDao() { super(Settings.class, SETTINGS, SETTINGS.ID::eq); } public TvTimes getTvTimes() { DSLContext create = dataSource.getSqlContext(); TvTimes result = create.select(SETTINGS.TV_TIMES).from(SETTINGS).where(SETTINGS.ID.eq(1)) .fetchOptionalInto(String.class) .map(json -> gson.fromJson(json, TvTimes.class)) .orElse(new TvTimes()); return result; }
// Path: src/main/java/org/chorem/ecd/model/settings/Location.java // public class Location { // private int id; // // private String name; // // private String weatherForecastUrl; // // public Location() { // } // // public Location(String name, String weatherForecastUrl) { // this.name = name; // this.weatherForecastUrl = weatherForecastUrl; // } // // 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; // } // // public String getWeatherForecastUrl() { // return weatherForecastUrl; // } // // public void setWeatherForecastUrl(String weatherForecastUrl) { // this.weatherForecastUrl = weatherForecastUrl; // } // // } // // Path: src/main/java/org/chorem/ecd/model/settings/Settings.java // public class Settings { // private Location location; // // private TvTimes tvTimes; // // public Location getLocation() { // return location; // } // // public void setLocation(Location location) { // this.location = location; // } // // public TvTimes getTvTimes() { // return tvTimes; // } // // public void setTvTimes(TvTimes tvTimes) { // this.tvTimes = tvTimes; // } // } // // Path: src/main/java/org/chorem/ecd/model/settings/TvTimes.java // public class TvTimes { // // private String wakeupTime; // // private String sleepTime; // // public TvTimes() { // // } // // public TvTimes(String wakeupTime, String sleepTime) { // this.wakeupTime = wakeupTime; // this.sleepTime = sleepTime; // } // // public String getWakeupTime() { // return wakeupTime; // } // // public void setWakeupTime(String wakeupTime) { // this.wakeupTime = wakeupTime; // } // // public String getSleepTime() { // return sleepTime; // } // // public void setSleepTime(String sleepTime) { // this.sleepTime = sleepTime; // } // // } // Path: src/main/java/org/chorem/ecd/dao/SettingsDao.java import org.chorem.ecd.model.settings.Location; import org.chorem.ecd.model.settings.Settings; import org.chorem.ecd.model.settings.TvTimes; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.RecordMapper; import org.jooq.impl.DSL; import org.jooq.util.postgres.PostgresDataType; import javax.enterprise.context.ApplicationScoped; import java.util.Optional; import static org.chorem.ecd.mapping.tables.Settings.SETTINGS; package org.chorem.ecd.dao; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class SettingsDao extends AbstractDao<Settings, Integer> { public SettingsDao() { super(Settings.class, SETTINGS, SETTINGS.ID::eq); } public TvTimes getTvTimes() { DSLContext create = dataSource.getSqlContext(); TvTimes result = create.select(SETTINGS.TV_TIMES).from(SETTINGS).where(SETTINGS.ID.eq(1)) .fetchOptionalInto(String.class) .map(json -> gson.fromJson(json, TvTimes.class)) .orElse(new TvTimes()); return result; }
public Location getLocation() {
juga999/easy-com-display
src/main/java/org/chorem/ecd/task/EcdPeriodicTask.java
// Path: src/main/java/org/chorem/ecd/service/JsonService.java // @ApplicationScoped // public class JsonService implements ResponseTransformer { // // private Gson gson; // // @Override // public String render(Object obj) { // return getGson().toJson(obj); // } // // public Gson getGson() { // if (gson == null) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter()); // gson = gsonBuilder.create(); // } // return gson; // } // // public void saveToJson(Object obj, Path path) throws IOException { // String json = getGson().toJson(obj); // Files.createDirectories(path.getParent()); // Files.write(path, json.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); // // } // // public <T> T loadFromJson(Class<T> type, Path path) throws IOException { // if (Files.exists(path)) { // String json = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); // return getGson().fromJson(json, type); // } else { // return null; // } // } // // private static final class LocalDateTimeAdapter implements JsonSerializer<LocalDateTime>, JsonDeserializer<LocalDateTime> { // private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME; // // @Override // public LocalDateTime deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { // return FORMATTER.parse(jsonElement.getAsString(), LocalDateTime::from); // } // // @Override // public JsonElement serialize(LocalDateTime localDateTime, Type type, JsonSerializationContext context) { // return new JsonPrimitive(FORMATTER.format(localDateTime)); // } // } // } // // Path: src/main/java/org/chorem/ecd/EcdConfig.java // @ApplicationScoped // public class EcdConfig { // // private static final Logger logger = LoggerFactory.getLogger(EcdConfig.class); // // private final Properties props; // // public static final String STREAMS_DIR = "streams"; // public static final String NEWS_DIR = "news"; // public static final String WEATHER_DIR = "weather"; // // public EcdConfig() { // props = new Properties(); // try { // props.load(getClass().getClassLoader().getResourceAsStream("ecd.properties")); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } // } // // public String getDataSourceUrl() { // return props.getProperty("ecd.datasource.url"); // } // // public String getDataSourceLogin() { // return props.getProperty("ecd.datasource.login"); // } // // public String getDataSourcePwd() { // return props.getProperty("ecd.datasource.pwd"); // } // // public String getApiPathPrefix() { // return "/api/ecd"; // } // // public String getMediaPathPrefix() { // return "/media/ecd"; // } // // public String getDataDir() { // return props.getProperty("ecd.data.dir"); // } // // public String getUploadDir() { return props.getProperty("ecd.upload.dir"); } // // public String getUnoconvCmd() { // return props.getProperty("ecd.cmd.unoconv"); // } // // public String getResizeCmd() { // return props.getProperty("ecd.cmd.resize"); // } // // public String getLocationSearchUrlFormat() { // return props.getProperty("ecd.location.searchUrlFormat"); // } // // public Integer getDefaultStreamTiming() { // return Integer.valueOf(props.getProperty("ecd.default.streamTiming")); // } // // public Path getStreamsPath() { // return Paths.get(getDataDir(), STREAMS_DIR); // } // // public Path getAggregatedNewsPath() { // return Paths.get(getDataDir(), NEWS_DIR, "aggregated.json"); // } // // public Path getWeatherForecastPath() { // return Paths.get(getDataDir(), WEATHER_DIR, "forecast.json"); // } // // }
import org.chorem.ecd.service.JsonService; import org.chorem.ecd.EcdConfig; import java.util.concurrent.TimeUnit;
package org.chorem.ecd.task; /** * @author Julien Gaston (gaston@codelutin.com) */ public abstract class EcdPeriodicTask implements Runnable { protected EcdConfig config;
// Path: src/main/java/org/chorem/ecd/service/JsonService.java // @ApplicationScoped // public class JsonService implements ResponseTransformer { // // private Gson gson; // // @Override // public String render(Object obj) { // return getGson().toJson(obj); // } // // public Gson getGson() { // if (gson == null) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter()); // gson = gsonBuilder.create(); // } // return gson; // } // // public void saveToJson(Object obj, Path path) throws IOException { // String json = getGson().toJson(obj); // Files.createDirectories(path.getParent()); // Files.write(path, json.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); // // } // // public <T> T loadFromJson(Class<T> type, Path path) throws IOException { // if (Files.exists(path)) { // String json = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); // return getGson().fromJson(json, type); // } else { // return null; // } // } // // private static final class LocalDateTimeAdapter implements JsonSerializer<LocalDateTime>, JsonDeserializer<LocalDateTime> { // private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME; // // @Override // public LocalDateTime deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { // return FORMATTER.parse(jsonElement.getAsString(), LocalDateTime::from); // } // // @Override // public JsonElement serialize(LocalDateTime localDateTime, Type type, JsonSerializationContext context) { // return new JsonPrimitive(FORMATTER.format(localDateTime)); // } // } // } // // Path: src/main/java/org/chorem/ecd/EcdConfig.java // @ApplicationScoped // public class EcdConfig { // // private static final Logger logger = LoggerFactory.getLogger(EcdConfig.class); // // private final Properties props; // // public static final String STREAMS_DIR = "streams"; // public static final String NEWS_DIR = "news"; // public static final String WEATHER_DIR = "weather"; // // public EcdConfig() { // props = new Properties(); // try { // props.load(getClass().getClassLoader().getResourceAsStream("ecd.properties")); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } // } // // public String getDataSourceUrl() { // return props.getProperty("ecd.datasource.url"); // } // // public String getDataSourceLogin() { // return props.getProperty("ecd.datasource.login"); // } // // public String getDataSourcePwd() { // return props.getProperty("ecd.datasource.pwd"); // } // // public String getApiPathPrefix() { // return "/api/ecd"; // } // // public String getMediaPathPrefix() { // return "/media/ecd"; // } // // public String getDataDir() { // return props.getProperty("ecd.data.dir"); // } // // public String getUploadDir() { return props.getProperty("ecd.upload.dir"); } // // public String getUnoconvCmd() { // return props.getProperty("ecd.cmd.unoconv"); // } // // public String getResizeCmd() { // return props.getProperty("ecd.cmd.resize"); // } // // public String getLocationSearchUrlFormat() { // return props.getProperty("ecd.location.searchUrlFormat"); // } // // public Integer getDefaultStreamTiming() { // return Integer.valueOf(props.getProperty("ecd.default.streamTiming")); // } // // public Path getStreamsPath() { // return Paths.get(getDataDir(), STREAMS_DIR); // } // // public Path getAggregatedNewsPath() { // return Paths.get(getDataDir(), NEWS_DIR, "aggregated.json"); // } // // public Path getWeatherForecastPath() { // return Paths.get(getDataDir(), WEATHER_DIR, "forecast.json"); // } // // } // Path: src/main/java/org/chorem/ecd/task/EcdPeriodicTask.java import org.chorem.ecd.service.JsonService; import org.chorem.ecd.EcdConfig; import java.util.concurrent.TimeUnit; package org.chorem.ecd.task; /** * @author Julien Gaston (gaston@codelutin.com) */ public abstract class EcdPeriodicTask implements Runnable { protected EcdConfig config;
protected JsonService jsonService;
juga999/easy-com-display
src/main/java/org/chorem/ecd/filter/AbstractFilter.java
// Path: src/main/java/org/chorem/ecd/service/AuthService.java // @ApplicationScoped // public class AuthService { // // private static final Logger logger = LoggerFactory.getLogger(AuthService.class); // // @Inject // private PersonDao personDao; // // private final Algorithm algorithm; // // private final JWTVerifier verifier; // // public AuthService() throws UnsupportedEncodingException { // algorithm = Algorithm.HMAC512("secretpassphrase"); // verifier = JWT.require(algorithm).withIssuer("auth0").build(); // } // // @TransactionRequired // public String getSignedToken(String subject, String password) { // if (Strings.isNullOrEmpty(subject) || Strings.isNullOrEmpty(password)) { // return null; // } // // Person person = new Person(); // person.setName("John Doe"); // personDao.addPerson(person); // // Instant now = Instant.now(); // //now = null; // Instant expirationInstant = Instant.now().plus(Duration.ofMinutes(20)); // // String token = JWT.create() // .withIssuer("auth0") // .withSubject(subject) // .withIssuedAt(Date.from(now)) // .withExpiresAt(Date.from(expirationInstant)) // .sign(algorithm); // // return token; // } // // public Payload decodeSignedToken(String signedToken) { // try { // Payload verifiedToken = verifier.verify(signedToken); // return verifiedToken; // } catch(JWTVerificationException e) { // return null; // } // } // // }
import org.chorem.ecd.service.AuthService; import spark.Filter; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.Initialized; import javax.enterprise.event.Observes; import javax.inject.Inject;
package org.chorem.ecd.filter; /** * @author Julien Gaston (gaston@codelutin.com) */ abstract public class AbstractFilter implements Filter { @Inject
// Path: src/main/java/org/chorem/ecd/service/AuthService.java // @ApplicationScoped // public class AuthService { // // private static final Logger logger = LoggerFactory.getLogger(AuthService.class); // // @Inject // private PersonDao personDao; // // private final Algorithm algorithm; // // private final JWTVerifier verifier; // // public AuthService() throws UnsupportedEncodingException { // algorithm = Algorithm.HMAC512("secretpassphrase"); // verifier = JWT.require(algorithm).withIssuer("auth0").build(); // } // // @TransactionRequired // public String getSignedToken(String subject, String password) { // if (Strings.isNullOrEmpty(subject) || Strings.isNullOrEmpty(password)) { // return null; // } // // Person person = new Person(); // person.setName("John Doe"); // personDao.addPerson(person); // // Instant now = Instant.now(); // //now = null; // Instant expirationInstant = Instant.now().plus(Duration.ofMinutes(20)); // // String token = JWT.create() // .withIssuer("auth0") // .withSubject(subject) // .withIssuedAt(Date.from(now)) // .withExpiresAt(Date.from(expirationInstant)) // .sign(algorithm); // // return token; // } // // public Payload decodeSignedToken(String signedToken) { // try { // Payload verifiedToken = verifier.verify(signedToken); // return verifiedToken; // } catch(JWTVerificationException e) { // return null; // } // } // // } // Path: src/main/java/org/chorem/ecd/filter/AbstractFilter.java import org.chorem.ecd.service.AuthService; import spark.Filter; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.Initialized; import javax.enterprise.event.Observes; import javax.inject.Inject; package org.chorem.ecd.filter; /** * @author Julien Gaston (gaston@codelutin.com) */ abstract public class AbstractFilter implements Filter { @Inject
protected AuthService authService;
juga999/easy-com-display
src/main/java/org/chorem/ecd/endpoint/DebugEndpoint.java
// Path: src/main/java/org/chorem/ecd/service/MediaConverterService.java // @ApplicationScoped // public class MediaConverterService { // // private static final Logger logger = LoggerFactory.getLogger(MediaConverterService.class); // // @Inject // private EcdConfig config; // // public String getUnoconvVersion() { // return getVersion(config.getUnoconvCmd()); // } // // public String getConvertVersion() { // return getVersion(config.getResizeCmd()); // } // // public List<SignageStreamFrame> extractFrames(Path source, Path destDir) throws IOException { // List<String> cmdLineArgs = Arrays.asList(config.getUnoconvCmd(), // "-vvv", // "--doctype=presentation", // "--format=html", // "-e PublishMode=0", // "-e Format=2", // "-e Width=1024", // "-e Compression=\"50%\"", // "-e IsExportContentsPage=false", // "--output=" + Paths.get(destDir.toString(), File.separator, ".").toString(), // source.toString()); // // executeCmd(cmdLineArgs); // // Comparator<Path> pathsWithDigitsComparator = (p1, p2) -> { // int p1Sequence = Integer.parseInt(CharMatcher.digit().retainFrom(p1.getFileName().toString())); // int p2Sequence = Integer.parseInt(CharMatcher.digit().retainFrom(p2.getFileName().toString())); // return p1Sequence - p2Sequence; // }; // // Set<Path> toRemove = Files.list(destDir) // .filter(p -> getFileExtension(p).equalsIgnoreCase("html")) // .collect(Collectors.toSet()); // for (Path path : toRemove) { // Files.delete(path); // } // // SortedSet<Path> imagePaths = Files.list(destDir) // .filter(p -> getFileExtension(p).equalsIgnoreCase("png")) // .collect(ImmutableSortedSet.toImmutableSortedSet(pathsWithDigitsComparator)); // // List<SignageStreamFrame> frames = Lists.newArrayList(); // // for (Path imagePath : imagePaths) { // Path thumbnailPath = createThumbnail(imagePath); // SignageStreamFrame frame = new SignageStreamFrame(imagePath.getFileName(), thumbnailPath.getFileName()); // frames.add(frame); // } // // return frames; // } // // public Path createThumbnail(Path imagePath) throws IOException { // Path resizedImagePath = getResizedImagePath(imagePath); // List<String> cmdLineArgs = Arrays.asList(config.getResizeCmd(), // "-resize", // "140x", // imagePath.toString(), // resizedImagePath.toString()); // // executeCmd(cmdLineArgs); // // return resizedImagePath; // } // // private static String executeCmd(List<String> cmdLineArgs) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); // DefaultExecutor exec = new DefaultExecutor(); // exec.setStreamHandler(streamHandler); // // CommandLine cmdLine = CommandLine.parse(cmdLineArgs.stream().collect(Collectors.joining(" "))); // // exec.execute(cmdLine); // // return outputStream.toString(); // } // // private String getVersion(String cmd) { // String version = ""; // List<String> cmdLineArgs = Arrays.asList(cmd, "--version"); // try { // version = executeCmd(cmdLineArgs); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } // return version; // } // // private String getFileExtension(Path path) { // return com.google.common.io.Files.getFileExtension(path.toString()); // } // // private String getNameWithoutExtension(Path path) { // return com.google.common.io.Files.getNameWithoutExtension(path.toString()); // } // // private Path getResizedImagePath(Path imagePath) { // String imageFileNameWithouExtension = getNameWithoutExtension(imagePath); // String imageFileExtenstion = getFileExtension(imagePath); // // return imagePath.resolveSibling(imageFileNameWithouExtension + "-small." + imageFileExtenstion); // } // }
import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import org.chorem.ecd.service.MediaConverterService; import spark.Request; import spark.Response; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.util.Map;
package org.chorem.ecd.endpoint; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class DebugEndpoint extends Endpoint { @Inject
// Path: src/main/java/org/chorem/ecd/service/MediaConverterService.java // @ApplicationScoped // public class MediaConverterService { // // private static final Logger logger = LoggerFactory.getLogger(MediaConverterService.class); // // @Inject // private EcdConfig config; // // public String getUnoconvVersion() { // return getVersion(config.getUnoconvCmd()); // } // // public String getConvertVersion() { // return getVersion(config.getResizeCmd()); // } // // public List<SignageStreamFrame> extractFrames(Path source, Path destDir) throws IOException { // List<String> cmdLineArgs = Arrays.asList(config.getUnoconvCmd(), // "-vvv", // "--doctype=presentation", // "--format=html", // "-e PublishMode=0", // "-e Format=2", // "-e Width=1024", // "-e Compression=\"50%\"", // "-e IsExportContentsPage=false", // "--output=" + Paths.get(destDir.toString(), File.separator, ".").toString(), // source.toString()); // // executeCmd(cmdLineArgs); // // Comparator<Path> pathsWithDigitsComparator = (p1, p2) -> { // int p1Sequence = Integer.parseInt(CharMatcher.digit().retainFrom(p1.getFileName().toString())); // int p2Sequence = Integer.parseInt(CharMatcher.digit().retainFrom(p2.getFileName().toString())); // return p1Sequence - p2Sequence; // }; // // Set<Path> toRemove = Files.list(destDir) // .filter(p -> getFileExtension(p).equalsIgnoreCase("html")) // .collect(Collectors.toSet()); // for (Path path : toRemove) { // Files.delete(path); // } // // SortedSet<Path> imagePaths = Files.list(destDir) // .filter(p -> getFileExtension(p).equalsIgnoreCase("png")) // .collect(ImmutableSortedSet.toImmutableSortedSet(pathsWithDigitsComparator)); // // List<SignageStreamFrame> frames = Lists.newArrayList(); // // for (Path imagePath : imagePaths) { // Path thumbnailPath = createThumbnail(imagePath); // SignageStreamFrame frame = new SignageStreamFrame(imagePath.getFileName(), thumbnailPath.getFileName()); // frames.add(frame); // } // // return frames; // } // // public Path createThumbnail(Path imagePath) throws IOException { // Path resizedImagePath = getResizedImagePath(imagePath); // List<String> cmdLineArgs = Arrays.asList(config.getResizeCmd(), // "-resize", // "140x", // imagePath.toString(), // resizedImagePath.toString()); // // executeCmd(cmdLineArgs); // // return resizedImagePath; // } // // private static String executeCmd(List<String> cmdLineArgs) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); // DefaultExecutor exec = new DefaultExecutor(); // exec.setStreamHandler(streamHandler); // // CommandLine cmdLine = CommandLine.parse(cmdLineArgs.stream().collect(Collectors.joining(" "))); // // exec.execute(cmdLine); // // return outputStream.toString(); // } // // private String getVersion(String cmd) { // String version = ""; // List<String> cmdLineArgs = Arrays.asList(cmd, "--version"); // try { // version = executeCmd(cmdLineArgs); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } // return version; // } // // private String getFileExtension(Path path) { // return com.google.common.io.Files.getFileExtension(path.toString()); // } // // private String getNameWithoutExtension(Path path) { // return com.google.common.io.Files.getNameWithoutExtension(path.toString()); // } // // private Path getResizedImagePath(Path imagePath) { // String imageFileNameWithouExtension = getNameWithoutExtension(imagePath); // String imageFileExtenstion = getFileExtension(imagePath); // // return imagePath.resolveSibling(imageFileNameWithouExtension + "-small." + imageFileExtenstion); // } // } // Path: src/main/java/org/chorem/ecd/endpoint/DebugEndpoint.java import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import org.chorem.ecd.service.MediaConverterService; import spark.Request; import spark.Response; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.util.Map; package org.chorem.ecd.endpoint; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class DebugEndpoint extends Endpoint { @Inject
private MediaConverterService mediaConverterService;
juga999/easy-com-display
src/main/java/org/chorem/ecd/task/WeatherForecastBuilderPeriodicTask.java
// Path: src/main/java/org/chorem/ecd/model/weather/WeatherForecast.java // public class WeatherForecast { // // private String provider; // // private String period; // // private String temperature; // // private String feltTemperature; // // private String sky; // // private String rain; // // private String wind; // // private String humidity; // // public WeatherForecast() { // } // // public String getProvider() { // return provider; // } // // public void setProvider(String provider) { // this.provider = provider; // } // // public String getPeriod() { // return period; // } // // public void setPeriod(String period) { // this.period = period; // } // // public String getTemperature() { // return temperature; // } // // public void setTemperature(String temperature) { // this.temperature = temperature; // } // // public String getFeltTemperature() { // return feltTemperature; // } // // public void setFeltTemperature(String feltTemperature) { // this.feltTemperature = feltTemperature; // } // // public String getSky() { // return sky; // } // // public void setSky(String sky) { // this.sky = sky; // } // // public String getRain() { // return rain; // } // // public void setRain(String rain) { // this.rain = rain; // } // // public String getWind() { // return wind; // } // // public void setWind(String wind) { // this.wind = wind; // } // // public String getHumidity() { // return humidity; // } // // public void setHumidity(String humidity) { // this.humidity = humidity; // } // }
import com.google.common.collect.Range; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.commons.io.IOUtils; import org.chorem.ecd.model.weather.WeatherForecast; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Calendar; import java.util.concurrent.TimeUnit;
package org.chorem.ecd.task; /** * @author Julien Gaston (gaston@codelutin.com) */ public class WeatherForecastBuilderPeriodicTask extends EcdPeriodicTask { private static final Logger logger = LoggerFactory.getLogger(WeatherForecastBuilderPeriodicTask.class); private URL forecastUrl; public static final String NAME = "WeatherForecastBuilder"; private static final Range<Integer> MORNING_RANGE = Range.closed(4, 12); private static final Range<Integer> AFTERNOON_RANGE = Range.closed(13, 18); public WeatherForecastBuilderPeriodicTask(String forecastUrl) { String url = forecastUrl.replace("/meteo/localite/", "/services/json/"); try { this.forecastUrl = new URL(url); } catch (MalformedURLException e) { logger.error(e.getMessage(), e); } } @Override public void run() { try {
// Path: src/main/java/org/chorem/ecd/model/weather/WeatherForecast.java // public class WeatherForecast { // // private String provider; // // private String period; // // private String temperature; // // private String feltTemperature; // // private String sky; // // private String rain; // // private String wind; // // private String humidity; // // public WeatherForecast() { // } // // public String getProvider() { // return provider; // } // // public void setProvider(String provider) { // this.provider = provider; // } // // public String getPeriod() { // return period; // } // // public void setPeriod(String period) { // this.period = period; // } // // public String getTemperature() { // return temperature; // } // // public void setTemperature(String temperature) { // this.temperature = temperature; // } // // public String getFeltTemperature() { // return feltTemperature; // } // // public void setFeltTemperature(String feltTemperature) { // this.feltTemperature = feltTemperature; // } // // public String getSky() { // return sky; // } // // public void setSky(String sky) { // this.sky = sky; // } // // public String getRain() { // return rain; // } // // public void setRain(String rain) { // this.rain = rain; // } // // public String getWind() { // return wind; // } // // public void setWind(String wind) { // this.wind = wind; // } // // public String getHumidity() { // return humidity; // } // // public void setHumidity(String humidity) { // this.humidity = humidity; // } // } // Path: src/main/java/org/chorem/ecd/task/WeatherForecastBuilderPeriodicTask.java import com.google.common.collect.Range; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.commons.io.IOUtils; import org.chorem.ecd.model.weather.WeatherForecast; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Calendar; import java.util.concurrent.TimeUnit; package org.chorem.ecd.task; /** * @author Julien Gaston (gaston@codelutin.com) */ public class WeatherForecastBuilderPeriodicTask extends EcdPeriodicTask { private static final Logger logger = LoggerFactory.getLogger(WeatherForecastBuilderPeriodicTask.class); private URL forecastUrl; public static final String NAME = "WeatherForecastBuilder"; private static final Range<Integer> MORNING_RANGE = Range.closed(4, 12); private static final Range<Integer> AFTERNOON_RANGE = Range.closed(13, 18); public WeatherForecastBuilderPeriodicTask(String forecastUrl) { String url = forecastUrl.replace("/meteo/localite/", "/services/json/"); try { this.forecastUrl = new URL(url); } catch (MalformedURLException e) { logger.error(e.getMessage(), e); } } @Override public void run() { try {
WeatherForecast forecast = fetchWeatherForecast();
juga999/easy-com-display
src/main/java/org/chorem/ecd/endpoint/LocationEndpoint.java
// Path: src/main/java/org/chorem/ecd/model/settings/Location.java // public class Location { // private int id; // // private String name; // // private String weatherForecastUrl; // // public Location() { // } // // public Location(String name, String weatherForecastUrl) { // this.name = name; // this.weatherForecastUrl = weatherForecastUrl; // } // // 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; // } // // public String getWeatherForecastUrl() { // return weatherForecastUrl; // } // // public void setWeatherForecastUrl(String weatherForecastUrl) { // this.weatherForecastUrl = weatherForecastUrl; // } // // } // // Path: src/main/java/org/chorem/ecd/service/LocationService.java // @ApplicationScoped // public class LocationService { // // private static final Logger logger = LoggerFactory.getLogger(LocationService.class); // // @Inject // protected SettingsDao settingsDao; // // @Inject // protected EcdConfig config; // // @Inject // protected JsonService jsonService; // // @Inject // protected PeriodicTasksExecutorService periodicTasksExecutorService; // // @PostConstruct // public void init() { // periodicTasksExecutorService.schedule(getWeatherForecastBuilderTask()); // } // // public WeatherForecast getWeatherForecast() { // try { // WeatherForecast weatherForecast = jsonService.loadFromJson(WeatherForecast.class, config.getWeatherForecastPath()); // return Optional.ofNullable(weatherForecast).orElse(new WeatherForecast()); // } catch (IOException e) { // logger.error(e.getMessage(), e); // return null; // } // } // // public Location getLocation() { // return settingsDao.getLocation(); // } // // @TransactionRequired // public void setLocation(Location location) { // String weatherForecastUrl = location.getWeatherForecastUrl().replace("/meteo/localite/", "/services/json/"); // location.setWeatherForecastUrl(weatherForecastUrl); // settingsDao.setLocation(location); // // periodicTasksExecutorService.schedule(getWeatherForecastBuilderTask()); // } // // private WeatherForecastBuilderPeriodicTask getWeatherForecastBuilderTask() { // String forecastUrl = settingsDao.getLocation().getWeatherForecastUrl(); // WeatherForecastBuilderPeriodicTask task = new WeatherForecastBuilderPeriodicTask(forecastUrl); // task.setConfig(config); // task.setJsonService(jsonService); // return task; // } // // }
import org.chorem.ecd.model.settings.Location; import org.chorem.ecd.service.LocationService; import spark.Request; import spark.Response; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject;
package org.chorem.ecd.endpoint; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class LocationEndpoint extends Endpoint { @Inject
// Path: src/main/java/org/chorem/ecd/model/settings/Location.java // public class Location { // private int id; // // private String name; // // private String weatherForecastUrl; // // public Location() { // } // // public Location(String name, String weatherForecastUrl) { // this.name = name; // this.weatherForecastUrl = weatherForecastUrl; // } // // 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; // } // // public String getWeatherForecastUrl() { // return weatherForecastUrl; // } // // public void setWeatherForecastUrl(String weatherForecastUrl) { // this.weatherForecastUrl = weatherForecastUrl; // } // // } // // Path: src/main/java/org/chorem/ecd/service/LocationService.java // @ApplicationScoped // public class LocationService { // // private static final Logger logger = LoggerFactory.getLogger(LocationService.class); // // @Inject // protected SettingsDao settingsDao; // // @Inject // protected EcdConfig config; // // @Inject // protected JsonService jsonService; // // @Inject // protected PeriodicTasksExecutorService periodicTasksExecutorService; // // @PostConstruct // public void init() { // periodicTasksExecutorService.schedule(getWeatherForecastBuilderTask()); // } // // public WeatherForecast getWeatherForecast() { // try { // WeatherForecast weatherForecast = jsonService.loadFromJson(WeatherForecast.class, config.getWeatherForecastPath()); // return Optional.ofNullable(weatherForecast).orElse(new WeatherForecast()); // } catch (IOException e) { // logger.error(e.getMessage(), e); // return null; // } // } // // public Location getLocation() { // return settingsDao.getLocation(); // } // // @TransactionRequired // public void setLocation(Location location) { // String weatherForecastUrl = location.getWeatherForecastUrl().replace("/meteo/localite/", "/services/json/"); // location.setWeatherForecastUrl(weatherForecastUrl); // settingsDao.setLocation(location); // // periodicTasksExecutorService.schedule(getWeatherForecastBuilderTask()); // } // // private WeatherForecastBuilderPeriodicTask getWeatherForecastBuilderTask() { // String forecastUrl = settingsDao.getLocation().getWeatherForecastUrl(); // WeatherForecastBuilderPeriodicTask task = new WeatherForecastBuilderPeriodicTask(forecastUrl); // task.setConfig(config); // task.setJsonService(jsonService); // return task; // } // // } // Path: src/main/java/org/chorem/ecd/endpoint/LocationEndpoint.java import org.chorem.ecd.model.settings.Location; import org.chorem.ecd.service.LocationService; import spark.Request; import spark.Response; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; package org.chorem.ecd.endpoint; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class LocationEndpoint extends Endpoint { @Inject
protected LocationService locationService;
juga999/easy-com-display
src/main/java/org/chorem/ecd/endpoint/LocationEndpoint.java
// Path: src/main/java/org/chorem/ecd/model/settings/Location.java // public class Location { // private int id; // // private String name; // // private String weatherForecastUrl; // // public Location() { // } // // public Location(String name, String weatherForecastUrl) { // this.name = name; // this.weatherForecastUrl = weatherForecastUrl; // } // // 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; // } // // public String getWeatherForecastUrl() { // return weatherForecastUrl; // } // // public void setWeatherForecastUrl(String weatherForecastUrl) { // this.weatherForecastUrl = weatherForecastUrl; // } // // } // // Path: src/main/java/org/chorem/ecd/service/LocationService.java // @ApplicationScoped // public class LocationService { // // private static final Logger logger = LoggerFactory.getLogger(LocationService.class); // // @Inject // protected SettingsDao settingsDao; // // @Inject // protected EcdConfig config; // // @Inject // protected JsonService jsonService; // // @Inject // protected PeriodicTasksExecutorService periodicTasksExecutorService; // // @PostConstruct // public void init() { // periodicTasksExecutorService.schedule(getWeatherForecastBuilderTask()); // } // // public WeatherForecast getWeatherForecast() { // try { // WeatherForecast weatherForecast = jsonService.loadFromJson(WeatherForecast.class, config.getWeatherForecastPath()); // return Optional.ofNullable(weatherForecast).orElse(new WeatherForecast()); // } catch (IOException e) { // logger.error(e.getMessage(), e); // return null; // } // } // // public Location getLocation() { // return settingsDao.getLocation(); // } // // @TransactionRequired // public void setLocation(Location location) { // String weatherForecastUrl = location.getWeatherForecastUrl().replace("/meteo/localite/", "/services/json/"); // location.setWeatherForecastUrl(weatherForecastUrl); // settingsDao.setLocation(location); // // periodicTasksExecutorService.schedule(getWeatherForecastBuilderTask()); // } // // private WeatherForecastBuilderPeriodicTask getWeatherForecastBuilderTask() { // String forecastUrl = settingsDao.getLocation().getWeatherForecastUrl(); // WeatherForecastBuilderPeriodicTask task = new WeatherForecastBuilderPeriodicTask(forecastUrl); // task.setConfig(config); // task.setJsonService(jsonService); // return task; // } // // }
import org.chorem.ecd.model.settings.Location; import org.chorem.ecd.service.LocationService; import spark.Request; import spark.Response; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject;
package org.chorem.ecd.endpoint; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class LocationEndpoint extends Endpoint { @Inject protected LocationService locationService; @Override protected void init() { registerJsonProducer(ecdApiPath("/cms/weather"), this::getWeatherForecast); registerJsonProducer(ecdApiPath("/settings/location"), this::getLocation); registerFormDataConsumer(ecdApiPath("/settings/location"), this::setLocation); } private Object getWeatherForecast(Request request, Response response) { return locationService.getWeatherForecast(); } private Object getLocation(Request req, Response resp) { return locationService.getLocation(); } private Object setLocation(Request req, Response resp) throws Exception {
// Path: src/main/java/org/chorem/ecd/model/settings/Location.java // public class Location { // private int id; // // private String name; // // private String weatherForecastUrl; // // public Location() { // } // // public Location(String name, String weatherForecastUrl) { // this.name = name; // this.weatherForecastUrl = weatherForecastUrl; // } // // 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; // } // // public String getWeatherForecastUrl() { // return weatherForecastUrl; // } // // public void setWeatherForecastUrl(String weatherForecastUrl) { // this.weatherForecastUrl = weatherForecastUrl; // } // // } // // Path: src/main/java/org/chorem/ecd/service/LocationService.java // @ApplicationScoped // public class LocationService { // // private static final Logger logger = LoggerFactory.getLogger(LocationService.class); // // @Inject // protected SettingsDao settingsDao; // // @Inject // protected EcdConfig config; // // @Inject // protected JsonService jsonService; // // @Inject // protected PeriodicTasksExecutorService periodicTasksExecutorService; // // @PostConstruct // public void init() { // periodicTasksExecutorService.schedule(getWeatherForecastBuilderTask()); // } // // public WeatherForecast getWeatherForecast() { // try { // WeatherForecast weatherForecast = jsonService.loadFromJson(WeatherForecast.class, config.getWeatherForecastPath()); // return Optional.ofNullable(weatherForecast).orElse(new WeatherForecast()); // } catch (IOException e) { // logger.error(e.getMessage(), e); // return null; // } // } // // public Location getLocation() { // return settingsDao.getLocation(); // } // // @TransactionRequired // public void setLocation(Location location) { // String weatherForecastUrl = location.getWeatherForecastUrl().replace("/meteo/localite/", "/services/json/"); // location.setWeatherForecastUrl(weatherForecastUrl); // settingsDao.setLocation(location); // // periodicTasksExecutorService.schedule(getWeatherForecastBuilderTask()); // } // // private WeatherForecastBuilderPeriodicTask getWeatherForecastBuilderTask() { // String forecastUrl = settingsDao.getLocation().getWeatherForecastUrl(); // WeatherForecastBuilderPeriodicTask task = new WeatherForecastBuilderPeriodicTask(forecastUrl); // task.setConfig(config); // task.setJsonService(jsonService); // return task; // } // // } // Path: src/main/java/org/chorem/ecd/endpoint/LocationEndpoint.java import org.chorem.ecd.model.settings.Location; import org.chorem.ecd.service.LocationService; import spark.Request; import spark.Response; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; package org.chorem.ecd.endpoint; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class LocationEndpoint extends Endpoint { @Inject protected LocationService locationService; @Override protected void init() { registerJsonProducer(ecdApiPath("/cms/weather"), this::getWeatherForecast); registerJsonProducer(ecdApiPath("/settings/location"), this::getLocation); registerFormDataConsumer(ecdApiPath("/settings/location"), this::setLocation); } private Object getWeatherForecast(Request request, Response response) { return locationService.getWeatherForecast(); } private Object getLocation(Request req, Response resp) { return locationService.getLocation(); } private Object setLocation(Request req, Response resp) throws Exception {
Location location = getObject(req, Location.class);