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 |
|---|---|---|---|---|---|---|
JHK/jLange | src/main/java/org/jlange/proxy/inbound/HttpPipelineFactory.java | // Path: src/main/java/org/jlange/proxy/util/Config.java
// public class Config {
//
// public static final Integer OUTBOUND_TIMEOUT = getConfig().getInteger("org.jlange.outbound.connection_timeout", 30);
// public static final Integer MAX_USED_CONNECTIONS = getConfig().getInteger("org.jlange.outbound.max_used_connections", 12);
// public static final RemoteAddress PROXY_CHAIN = buildProxyChain();
//
// public static final Boolean HTTP_ENABLED = getConfig().getBoolean("org.jlange.proxy.http.enabled", true);
// public static final Integer HTTP_PORT = getConfig().getInteger("org.jlange.proxy.http.port", 8080);
//
// public static final Boolean SPDY_ENABLED = getConfig().getBoolean("org.jlange.proxy.spdy.enabled", false);
// public static final Integer SPDY_PORT = getConfig().getInteger("org.jlange.proxy.spdy.port", 8443);
// public static final String SPDY_KEY_STORE = getConfig().getString("org.jlange.proxy.spdy.ssl.store");
// public static final String SPDY_KEY_PASS = getConfig().getString("org.jlange.proxy.spdy.ssl.key");
//
// public static final String VIA_HOSTNAME = getConfig().getString("org.jlange.proxy.via.hostname", "jLange");
// public static final String VIA_COMMENT = getConfig().getString("org.jlange.proxy.via.comment", null);
// public static final Integer COMPRESSION_LEVEL = getConfig().getInteger("org.jlange.proxy.compression_level", 7);
// public static final Integer CHUNK_SIZE = getConfig().getInteger("org.jlange.proxy.chunk_size", 8196);
// public static final File TMP_DIRECTORY = buildTmpDirectory();
//
// public static final String[] PLUGINS_RESPONSE = getConfig().getStringArray("org.jlange.plugin.response");
// public static final String[] PLUGINS_PREDEFINED = getConfig().getStringArray("org.jlange.plugin.predefined");
//
// public static Configuration getPluginConfig(Class<?> plugin) {
// if (pluginConfig.get(plugin) == null) {
// try {
// pluginConfig.put(plugin, new PropertiesConfiguration(plugin.getName() + ".properties"));
// } catch (ConfigurationException e) {
// pluginConfig.put(plugin, new PropertiesConfiguration());
// }
// }
//
// return pluginConfig.get(plugin);
// }
//
// private static File buildTmpDirectory() {
// File tmpBase = new File(getConfig().getString("org.jlange.proxy.tmp", "/tmp"));
//
// if (!tmpBase.isDirectory())
// throw new IllegalArgumentException("tmp is no directory");
//
// File tmpDir = new File(tmpBase, "jLange-" + HTTP_PORT + "-" + SPDY_PORT);
// tmpDir.mkdirs();
// tmpDir.deleteOnExit();
//
// return tmpDir;
// }
//
// private static RemoteAddress buildProxyChain() {
// String host = getConfig().getString("org.jlange.outbound.proxy.host");
// Integer port = getConfig().getInteger("org.jlange.outbound.proxy.port", null);
//
// if (host != null && port != null)
// return new RemoteAddress(host, port);
// else
// return null;
// }
//
// private static Configuration config;
// private static Map<Class<?>, Configuration> pluginConfig = new HashMap<Class<?>, Configuration>();
//
// private static Configuration getConfig() {
// if (config == null) {
// try {
// config = new PropertiesConfiguration("jLange.properties");
// } catch (ConfigurationException e) {
// e.printStackTrace();
// System.exit(1);
// }
// }
// return config;
// }
// }
//
// Path: src/main/java/org/jlange/proxy/util/IdleShutdownHandler.java
// public class IdleShutdownHandler extends IdleStateHandler implements ChannelHandler {
//
// public final static Timer timer = new HashedWheelTimer();
//
// private final Logger log = LoggerFactory.getLogger(getClass());
//
// public IdleShutdownHandler(final int readerIdleTimeSeconds, final int writerIdleTimeSeconds) {
// super(timer, readerIdleTimeSeconds, writerIdleTimeSeconds, 0);
// }
//
// @Override
// protected void channelIdle(final ChannelHandlerContext ctx, final IdleState state, final long lastActivityTimeMillis) {
// log.info("Channel {} - shutdown due idle time exceeded", ctx.getChannel().getId());
// ctx.getChannel().close();
// }
//
// }
| import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;
import org.jlange.proxy.util.Config;
import org.jlange.proxy.util.IdleShutdownHandler; | /*
* Copyright (C) 2012 Julian Knocke
*
* This file is part of jLange.
*
* jLange is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* jLange is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with jLange. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jlange.proxy.inbound;
public class HttpPipelineFactory implements ChannelPipelineFactory {
@Override
public ChannelPipeline getPipeline() {
final ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("deflater", new HttpContentCompressor(Config.COMPRESSION_LEVEL)); | // Path: src/main/java/org/jlange/proxy/util/Config.java
// public class Config {
//
// public static final Integer OUTBOUND_TIMEOUT = getConfig().getInteger("org.jlange.outbound.connection_timeout", 30);
// public static final Integer MAX_USED_CONNECTIONS = getConfig().getInteger("org.jlange.outbound.max_used_connections", 12);
// public static final RemoteAddress PROXY_CHAIN = buildProxyChain();
//
// public static final Boolean HTTP_ENABLED = getConfig().getBoolean("org.jlange.proxy.http.enabled", true);
// public static final Integer HTTP_PORT = getConfig().getInteger("org.jlange.proxy.http.port", 8080);
//
// public static final Boolean SPDY_ENABLED = getConfig().getBoolean("org.jlange.proxy.spdy.enabled", false);
// public static final Integer SPDY_PORT = getConfig().getInteger("org.jlange.proxy.spdy.port", 8443);
// public static final String SPDY_KEY_STORE = getConfig().getString("org.jlange.proxy.spdy.ssl.store");
// public static final String SPDY_KEY_PASS = getConfig().getString("org.jlange.proxy.spdy.ssl.key");
//
// public static final String VIA_HOSTNAME = getConfig().getString("org.jlange.proxy.via.hostname", "jLange");
// public static final String VIA_COMMENT = getConfig().getString("org.jlange.proxy.via.comment", null);
// public static final Integer COMPRESSION_LEVEL = getConfig().getInteger("org.jlange.proxy.compression_level", 7);
// public static final Integer CHUNK_SIZE = getConfig().getInteger("org.jlange.proxy.chunk_size", 8196);
// public static final File TMP_DIRECTORY = buildTmpDirectory();
//
// public static final String[] PLUGINS_RESPONSE = getConfig().getStringArray("org.jlange.plugin.response");
// public static final String[] PLUGINS_PREDEFINED = getConfig().getStringArray("org.jlange.plugin.predefined");
//
// public static Configuration getPluginConfig(Class<?> plugin) {
// if (pluginConfig.get(plugin) == null) {
// try {
// pluginConfig.put(plugin, new PropertiesConfiguration(plugin.getName() + ".properties"));
// } catch (ConfigurationException e) {
// pluginConfig.put(plugin, new PropertiesConfiguration());
// }
// }
//
// return pluginConfig.get(plugin);
// }
//
// private static File buildTmpDirectory() {
// File tmpBase = new File(getConfig().getString("org.jlange.proxy.tmp", "/tmp"));
//
// if (!tmpBase.isDirectory())
// throw new IllegalArgumentException("tmp is no directory");
//
// File tmpDir = new File(tmpBase, "jLange-" + HTTP_PORT + "-" + SPDY_PORT);
// tmpDir.mkdirs();
// tmpDir.deleteOnExit();
//
// return tmpDir;
// }
//
// private static RemoteAddress buildProxyChain() {
// String host = getConfig().getString("org.jlange.outbound.proxy.host");
// Integer port = getConfig().getInteger("org.jlange.outbound.proxy.port", null);
//
// if (host != null && port != null)
// return new RemoteAddress(host, port);
// else
// return null;
// }
//
// private static Configuration config;
// private static Map<Class<?>, Configuration> pluginConfig = new HashMap<Class<?>, Configuration>();
//
// private static Configuration getConfig() {
// if (config == null) {
// try {
// config = new PropertiesConfiguration("jLange.properties");
// } catch (ConfigurationException e) {
// e.printStackTrace();
// System.exit(1);
// }
// }
// return config;
// }
// }
//
// Path: src/main/java/org/jlange/proxy/util/IdleShutdownHandler.java
// public class IdleShutdownHandler extends IdleStateHandler implements ChannelHandler {
//
// public final static Timer timer = new HashedWheelTimer();
//
// private final Logger log = LoggerFactory.getLogger(getClass());
//
// public IdleShutdownHandler(final int readerIdleTimeSeconds, final int writerIdleTimeSeconds) {
// super(timer, readerIdleTimeSeconds, writerIdleTimeSeconds, 0);
// }
//
// @Override
// protected void channelIdle(final ChannelHandlerContext ctx, final IdleState state, final long lastActivityTimeMillis) {
// log.info("Channel {} - shutdown due idle time exceeded", ctx.getChannel().getId());
// ctx.getChannel().close();
// }
//
// }
// Path: src/main/java/org/jlange/proxy/inbound/HttpPipelineFactory.java
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;
import org.jlange.proxy.util.Config;
import org.jlange.proxy.util.IdleShutdownHandler;
/*
* Copyright (C) 2012 Julian Knocke
*
* This file is part of jLange.
*
* jLange is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* jLange is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with jLange. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jlange.proxy.inbound;
public class HttpPipelineFactory implements ChannelPipelineFactory {
@Override
public ChannelPipeline getPipeline() {
final ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("deflater", new HttpContentCompressor(Config.COMPRESSION_LEVEL)); | pipeline.addLast("idle", new IdleShutdownHandler(300, 0)); |
JHK/jLange | src/main/java/org/jlange/proxy/outbound/HttpPipelineFactory.java | // Path: src/main/java/org/jlange/proxy/util/Config.java
// public class Config {
//
// public static final Integer OUTBOUND_TIMEOUT = getConfig().getInteger("org.jlange.outbound.connection_timeout", 30);
// public static final Integer MAX_USED_CONNECTIONS = getConfig().getInteger("org.jlange.outbound.max_used_connections", 12);
// public static final RemoteAddress PROXY_CHAIN = buildProxyChain();
//
// public static final Boolean HTTP_ENABLED = getConfig().getBoolean("org.jlange.proxy.http.enabled", true);
// public static final Integer HTTP_PORT = getConfig().getInteger("org.jlange.proxy.http.port", 8080);
//
// public static final Boolean SPDY_ENABLED = getConfig().getBoolean("org.jlange.proxy.spdy.enabled", false);
// public static final Integer SPDY_PORT = getConfig().getInteger("org.jlange.proxy.spdy.port", 8443);
// public static final String SPDY_KEY_STORE = getConfig().getString("org.jlange.proxy.spdy.ssl.store");
// public static final String SPDY_KEY_PASS = getConfig().getString("org.jlange.proxy.spdy.ssl.key");
//
// public static final String VIA_HOSTNAME = getConfig().getString("org.jlange.proxy.via.hostname", "jLange");
// public static final String VIA_COMMENT = getConfig().getString("org.jlange.proxy.via.comment", null);
// public static final Integer COMPRESSION_LEVEL = getConfig().getInteger("org.jlange.proxy.compression_level", 7);
// public static final Integer CHUNK_SIZE = getConfig().getInteger("org.jlange.proxy.chunk_size", 8196);
// public static final File TMP_DIRECTORY = buildTmpDirectory();
//
// public static final String[] PLUGINS_RESPONSE = getConfig().getStringArray("org.jlange.plugin.response");
// public static final String[] PLUGINS_PREDEFINED = getConfig().getStringArray("org.jlange.plugin.predefined");
//
// public static Configuration getPluginConfig(Class<?> plugin) {
// if (pluginConfig.get(plugin) == null) {
// try {
// pluginConfig.put(plugin, new PropertiesConfiguration(plugin.getName() + ".properties"));
// } catch (ConfigurationException e) {
// pluginConfig.put(plugin, new PropertiesConfiguration());
// }
// }
//
// return pluginConfig.get(plugin);
// }
//
// private static File buildTmpDirectory() {
// File tmpBase = new File(getConfig().getString("org.jlange.proxy.tmp", "/tmp"));
//
// if (!tmpBase.isDirectory())
// throw new IllegalArgumentException("tmp is no directory");
//
// File tmpDir = new File(tmpBase, "jLange-" + HTTP_PORT + "-" + SPDY_PORT);
// tmpDir.mkdirs();
// tmpDir.deleteOnExit();
//
// return tmpDir;
// }
//
// private static RemoteAddress buildProxyChain() {
// String host = getConfig().getString("org.jlange.outbound.proxy.host");
// Integer port = getConfig().getInteger("org.jlange.outbound.proxy.port", null);
//
// if (host != null && port != null)
// return new RemoteAddress(host, port);
// else
// return null;
// }
//
// private static Configuration config;
// private static Map<Class<?>, Configuration> pluginConfig = new HashMap<Class<?>, Configuration>();
//
// private static Configuration getConfig() {
// if (config == null) {
// try {
// config = new PropertiesConfiguration("jLange.properties");
// } catch (ConfigurationException e) {
// e.printStackTrace();
// System.exit(1);
// }
// }
// return config;
// }
// }
//
// Path: src/main/java/org/jlange/proxy/util/IdleShutdownHandler.java
// public class IdleShutdownHandler extends IdleStateHandler implements ChannelHandler {
//
// public final static Timer timer = new HashedWheelTimer();
//
// private final Logger log = LoggerFactory.getLogger(getClass());
//
// public IdleShutdownHandler(final int readerIdleTimeSeconds, final int writerIdleTimeSeconds) {
// super(timer, readerIdleTimeSeconds, writerIdleTimeSeconds, 0);
// }
//
// @Override
// protected void channelIdle(final ChannelHandlerContext ctx, final IdleState state, final long lastActivityTimeMillis) {
// log.info("Channel {} - shutdown due idle time exceeded", ctx.getChannel().getId());
// ctx.getChannel().close();
// }
//
// }
| import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.codec.http.HttpContentDecompressor;
import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
import org.jlange.proxy.util.Config;
import org.jlange.proxy.util.IdleShutdownHandler; | /*
* Copyright (C) 2012 Julian Knocke
*
* This file is part of jLange.
*
* jLange is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* jLange is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with jLange. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jlange.proxy.outbound;
public class HttpPipelineFactory implements ChannelPipelineFactory {
public ChannelPipeline getPipeline() {
final ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("encoder", new HttpRequestEncoder());
pipeline.addLast("decoder", new HttpResponseDecoder(8192, 8192 * 2, 8192 * 2));
pipeline.addLast("inflater", new HttpContentDecompressor());
pipeline.addLast("plugin", new PluginHandler()); | // Path: src/main/java/org/jlange/proxy/util/Config.java
// public class Config {
//
// public static final Integer OUTBOUND_TIMEOUT = getConfig().getInteger("org.jlange.outbound.connection_timeout", 30);
// public static final Integer MAX_USED_CONNECTIONS = getConfig().getInteger("org.jlange.outbound.max_used_connections", 12);
// public static final RemoteAddress PROXY_CHAIN = buildProxyChain();
//
// public static final Boolean HTTP_ENABLED = getConfig().getBoolean("org.jlange.proxy.http.enabled", true);
// public static final Integer HTTP_PORT = getConfig().getInteger("org.jlange.proxy.http.port", 8080);
//
// public static final Boolean SPDY_ENABLED = getConfig().getBoolean("org.jlange.proxy.spdy.enabled", false);
// public static final Integer SPDY_PORT = getConfig().getInteger("org.jlange.proxy.spdy.port", 8443);
// public static final String SPDY_KEY_STORE = getConfig().getString("org.jlange.proxy.spdy.ssl.store");
// public static final String SPDY_KEY_PASS = getConfig().getString("org.jlange.proxy.spdy.ssl.key");
//
// public static final String VIA_HOSTNAME = getConfig().getString("org.jlange.proxy.via.hostname", "jLange");
// public static final String VIA_COMMENT = getConfig().getString("org.jlange.proxy.via.comment", null);
// public static final Integer COMPRESSION_LEVEL = getConfig().getInteger("org.jlange.proxy.compression_level", 7);
// public static final Integer CHUNK_SIZE = getConfig().getInteger("org.jlange.proxy.chunk_size", 8196);
// public static final File TMP_DIRECTORY = buildTmpDirectory();
//
// public static final String[] PLUGINS_RESPONSE = getConfig().getStringArray("org.jlange.plugin.response");
// public static final String[] PLUGINS_PREDEFINED = getConfig().getStringArray("org.jlange.plugin.predefined");
//
// public static Configuration getPluginConfig(Class<?> plugin) {
// if (pluginConfig.get(plugin) == null) {
// try {
// pluginConfig.put(plugin, new PropertiesConfiguration(plugin.getName() + ".properties"));
// } catch (ConfigurationException e) {
// pluginConfig.put(plugin, new PropertiesConfiguration());
// }
// }
//
// return pluginConfig.get(plugin);
// }
//
// private static File buildTmpDirectory() {
// File tmpBase = new File(getConfig().getString("org.jlange.proxy.tmp", "/tmp"));
//
// if (!tmpBase.isDirectory())
// throw new IllegalArgumentException("tmp is no directory");
//
// File tmpDir = new File(tmpBase, "jLange-" + HTTP_PORT + "-" + SPDY_PORT);
// tmpDir.mkdirs();
// tmpDir.deleteOnExit();
//
// return tmpDir;
// }
//
// private static RemoteAddress buildProxyChain() {
// String host = getConfig().getString("org.jlange.outbound.proxy.host");
// Integer port = getConfig().getInteger("org.jlange.outbound.proxy.port", null);
//
// if (host != null && port != null)
// return new RemoteAddress(host, port);
// else
// return null;
// }
//
// private static Configuration config;
// private static Map<Class<?>, Configuration> pluginConfig = new HashMap<Class<?>, Configuration>();
//
// private static Configuration getConfig() {
// if (config == null) {
// try {
// config = new PropertiesConfiguration("jLange.properties");
// } catch (ConfigurationException e) {
// e.printStackTrace();
// System.exit(1);
// }
// }
// return config;
// }
// }
//
// Path: src/main/java/org/jlange/proxy/util/IdleShutdownHandler.java
// public class IdleShutdownHandler extends IdleStateHandler implements ChannelHandler {
//
// public final static Timer timer = new HashedWheelTimer();
//
// private final Logger log = LoggerFactory.getLogger(getClass());
//
// public IdleShutdownHandler(final int readerIdleTimeSeconds, final int writerIdleTimeSeconds) {
// super(timer, readerIdleTimeSeconds, writerIdleTimeSeconds, 0);
// }
//
// @Override
// protected void channelIdle(final ChannelHandlerContext ctx, final IdleState state, final long lastActivityTimeMillis) {
// log.info("Channel {} - shutdown due idle time exceeded", ctx.getChannel().getId());
// ctx.getChannel().close();
// }
//
// }
// Path: src/main/java/org/jlange/proxy/outbound/HttpPipelineFactory.java
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.codec.http.HttpContentDecompressor;
import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
import org.jlange.proxy.util.Config;
import org.jlange.proxy.util.IdleShutdownHandler;
/*
* Copyright (C) 2012 Julian Knocke
*
* This file is part of jLange.
*
* jLange is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* jLange is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with jLange. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jlange.proxy.outbound;
public class HttpPipelineFactory implements ChannelPipelineFactory {
public ChannelPipeline getPipeline() {
final ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("encoder", new HttpRequestEncoder());
pipeline.addLast("decoder", new HttpResponseDecoder(8192, 8192 * 2, 8192 * 2));
pipeline.addLast("inflater", new HttpContentDecompressor());
pipeline.addLast("plugin", new PluginHandler()); | pipeline.addLast("idle", new IdleShutdownHandler(0, Config.OUTBOUND_TIMEOUT)); |
JHK/jLange | src/main/java/org/jlange/proxy/outbound/HttpPipelineFactory.java | // Path: src/main/java/org/jlange/proxy/util/Config.java
// public class Config {
//
// public static final Integer OUTBOUND_TIMEOUT = getConfig().getInteger("org.jlange.outbound.connection_timeout", 30);
// public static final Integer MAX_USED_CONNECTIONS = getConfig().getInteger("org.jlange.outbound.max_used_connections", 12);
// public static final RemoteAddress PROXY_CHAIN = buildProxyChain();
//
// public static final Boolean HTTP_ENABLED = getConfig().getBoolean("org.jlange.proxy.http.enabled", true);
// public static final Integer HTTP_PORT = getConfig().getInteger("org.jlange.proxy.http.port", 8080);
//
// public static final Boolean SPDY_ENABLED = getConfig().getBoolean("org.jlange.proxy.spdy.enabled", false);
// public static final Integer SPDY_PORT = getConfig().getInteger("org.jlange.proxy.spdy.port", 8443);
// public static final String SPDY_KEY_STORE = getConfig().getString("org.jlange.proxy.spdy.ssl.store");
// public static final String SPDY_KEY_PASS = getConfig().getString("org.jlange.proxy.spdy.ssl.key");
//
// public static final String VIA_HOSTNAME = getConfig().getString("org.jlange.proxy.via.hostname", "jLange");
// public static final String VIA_COMMENT = getConfig().getString("org.jlange.proxy.via.comment", null);
// public static final Integer COMPRESSION_LEVEL = getConfig().getInteger("org.jlange.proxy.compression_level", 7);
// public static final Integer CHUNK_SIZE = getConfig().getInteger("org.jlange.proxy.chunk_size", 8196);
// public static final File TMP_DIRECTORY = buildTmpDirectory();
//
// public static final String[] PLUGINS_RESPONSE = getConfig().getStringArray("org.jlange.plugin.response");
// public static final String[] PLUGINS_PREDEFINED = getConfig().getStringArray("org.jlange.plugin.predefined");
//
// public static Configuration getPluginConfig(Class<?> plugin) {
// if (pluginConfig.get(plugin) == null) {
// try {
// pluginConfig.put(plugin, new PropertiesConfiguration(plugin.getName() + ".properties"));
// } catch (ConfigurationException e) {
// pluginConfig.put(plugin, new PropertiesConfiguration());
// }
// }
//
// return pluginConfig.get(plugin);
// }
//
// private static File buildTmpDirectory() {
// File tmpBase = new File(getConfig().getString("org.jlange.proxy.tmp", "/tmp"));
//
// if (!tmpBase.isDirectory())
// throw new IllegalArgumentException("tmp is no directory");
//
// File tmpDir = new File(tmpBase, "jLange-" + HTTP_PORT + "-" + SPDY_PORT);
// tmpDir.mkdirs();
// tmpDir.deleteOnExit();
//
// return tmpDir;
// }
//
// private static RemoteAddress buildProxyChain() {
// String host = getConfig().getString("org.jlange.outbound.proxy.host");
// Integer port = getConfig().getInteger("org.jlange.outbound.proxy.port", null);
//
// if (host != null && port != null)
// return new RemoteAddress(host, port);
// else
// return null;
// }
//
// private static Configuration config;
// private static Map<Class<?>, Configuration> pluginConfig = new HashMap<Class<?>, Configuration>();
//
// private static Configuration getConfig() {
// if (config == null) {
// try {
// config = new PropertiesConfiguration("jLange.properties");
// } catch (ConfigurationException e) {
// e.printStackTrace();
// System.exit(1);
// }
// }
// return config;
// }
// }
//
// Path: src/main/java/org/jlange/proxy/util/IdleShutdownHandler.java
// public class IdleShutdownHandler extends IdleStateHandler implements ChannelHandler {
//
// public final static Timer timer = new HashedWheelTimer();
//
// private final Logger log = LoggerFactory.getLogger(getClass());
//
// public IdleShutdownHandler(final int readerIdleTimeSeconds, final int writerIdleTimeSeconds) {
// super(timer, readerIdleTimeSeconds, writerIdleTimeSeconds, 0);
// }
//
// @Override
// protected void channelIdle(final ChannelHandlerContext ctx, final IdleState state, final long lastActivityTimeMillis) {
// log.info("Channel {} - shutdown due idle time exceeded", ctx.getChannel().getId());
// ctx.getChannel().close();
// }
//
// }
| import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.codec.http.HttpContentDecompressor;
import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
import org.jlange.proxy.util.Config;
import org.jlange.proxy.util.IdleShutdownHandler; | /*
* Copyright (C) 2012 Julian Knocke
*
* This file is part of jLange.
*
* jLange is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* jLange is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with jLange. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jlange.proxy.outbound;
public class HttpPipelineFactory implements ChannelPipelineFactory {
public ChannelPipeline getPipeline() {
final ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("encoder", new HttpRequestEncoder());
pipeline.addLast("decoder", new HttpResponseDecoder(8192, 8192 * 2, 8192 * 2));
pipeline.addLast("inflater", new HttpContentDecompressor());
pipeline.addLast("plugin", new PluginHandler()); | // Path: src/main/java/org/jlange/proxy/util/Config.java
// public class Config {
//
// public static final Integer OUTBOUND_TIMEOUT = getConfig().getInteger("org.jlange.outbound.connection_timeout", 30);
// public static final Integer MAX_USED_CONNECTIONS = getConfig().getInteger("org.jlange.outbound.max_used_connections", 12);
// public static final RemoteAddress PROXY_CHAIN = buildProxyChain();
//
// public static final Boolean HTTP_ENABLED = getConfig().getBoolean("org.jlange.proxy.http.enabled", true);
// public static final Integer HTTP_PORT = getConfig().getInteger("org.jlange.proxy.http.port", 8080);
//
// public static final Boolean SPDY_ENABLED = getConfig().getBoolean("org.jlange.proxy.spdy.enabled", false);
// public static final Integer SPDY_PORT = getConfig().getInteger("org.jlange.proxy.spdy.port", 8443);
// public static final String SPDY_KEY_STORE = getConfig().getString("org.jlange.proxy.spdy.ssl.store");
// public static final String SPDY_KEY_PASS = getConfig().getString("org.jlange.proxy.spdy.ssl.key");
//
// public static final String VIA_HOSTNAME = getConfig().getString("org.jlange.proxy.via.hostname", "jLange");
// public static final String VIA_COMMENT = getConfig().getString("org.jlange.proxy.via.comment", null);
// public static final Integer COMPRESSION_LEVEL = getConfig().getInteger("org.jlange.proxy.compression_level", 7);
// public static final Integer CHUNK_SIZE = getConfig().getInteger("org.jlange.proxy.chunk_size", 8196);
// public static final File TMP_DIRECTORY = buildTmpDirectory();
//
// public static final String[] PLUGINS_RESPONSE = getConfig().getStringArray("org.jlange.plugin.response");
// public static final String[] PLUGINS_PREDEFINED = getConfig().getStringArray("org.jlange.plugin.predefined");
//
// public static Configuration getPluginConfig(Class<?> plugin) {
// if (pluginConfig.get(plugin) == null) {
// try {
// pluginConfig.put(plugin, new PropertiesConfiguration(plugin.getName() + ".properties"));
// } catch (ConfigurationException e) {
// pluginConfig.put(plugin, new PropertiesConfiguration());
// }
// }
//
// return pluginConfig.get(plugin);
// }
//
// private static File buildTmpDirectory() {
// File tmpBase = new File(getConfig().getString("org.jlange.proxy.tmp", "/tmp"));
//
// if (!tmpBase.isDirectory())
// throw new IllegalArgumentException("tmp is no directory");
//
// File tmpDir = new File(tmpBase, "jLange-" + HTTP_PORT + "-" + SPDY_PORT);
// tmpDir.mkdirs();
// tmpDir.deleteOnExit();
//
// return tmpDir;
// }
//
// private static RemoteAddress buildProxyChain() {
// String host = getConfig().getString("org.jlange.outbound.proxy.host");
// Integer port = getConfig().getInteger("org.jlange.outbound.proxy.port", null);
//
// if (host != null && port != null)
// return new RemoteAddress(host, port);
// else
// return null;
// }
//
// private static Configuration config;
// private static Map<Class<?>, Configuration> pluginConfig = new HashMap<Class<?>, Configuration>();
//
// private static Configuration getConfig() {
// if (config == null) {
// try {
// config = new PropertiesConfiguration("jLange.properties");
// } catch (ConfigurationException e) {
// e.printStackTrace();
// System.exit(1);
// }
// }
// return config;
// }
// }
//
// Path: src/main/java/org/jlange/proxy/util/IdleShutdownHandler.java
// public class IdleShutdownHandler extends IdleStateHandler implements ChannelHandler {
//
// public final static Timer timer = new HashedWheelTimer();
//
// private final Logger log = LoggerFactory.getLogger(getClass());
//
// public IdleShutdownHandler(final int readerIdleTimeSeconds, final int writerIdleTimeSeconds) {
// super(timer, readerIdleTimeSeconds, writerIdleTimeSeconds, 0);
// }
//
// @Override
// protected void channelIdle(final ChannelHandlerContext ctx, final IdleState state, final long lastActivityTimeMillis) {
// log.info("Channel {} - shutdown due idle time exceeded", ctx.getChannel().getId());
// ctx.getChannel().close();
// }
//
// }
// Path: src/main/java/org/jlange/proxy/outbound/HttpPipelineFactory.java
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.codec.http.HttpContentDecompressor;
import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
import org.jlange.proxy.util.Config;
import org.jlange.proxy.util.IdleShutdownHandler;
/*
* Copyright (C) 2012 Julian Knocke
*
* This file is part of jLange.
*
* jLange is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* jLange is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with jLange. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jlange.proxy.outbound;
public class HttpPipelineFactory implements ChannelPipelineFactory {
public ChannelPipeline getPipeline() {
final ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("encoder", new HttpRequestEncoder());
pipeline.addLast("decoder", new HttpResponseDecoder(8192, 8192 * 2, 8192 * 2));
pipeline.addLast("inflater", new HttpContentDecompressor());
pipeline.addLast("plugin", new PluginHandler()); | pipeline.addLast("idle", new IdleShutdownHandler(0, Config.OUTBOUND_TIMEOUT)); |
mkyral/josm-tracer | src/org/openstreetmap/josm/plugins/tracer/connectways/ClipObjectArea.java | // Path: src/org/openstreetmap/josm/plugins/tracer/PostTraceNotifications.java
// public class PostTraceNotifications {
// private final List<String> m_list = new ArrayList<> ();
//
// public void clear() {
// synchronized(m_list) {
// m_list.clear();
// }
// }
//
// public void add(String s) {
// System.out.println("Notify: " + s);
// synchronized(m_list) {
// m_list.add(s);
// }
// }
//
// public void show () {
// StringBuilder sb = new StringBuilder();
// synchronized(m_list) {
// if (m_list.isEmpty())
// return;
// for (String s: m_list) {
// if (sb.length() != 0)
// sb.append("\n");
// sb.append(s);
// }
// m_list.clear();
// }
// TracerUtils.showNotification(sb.toString(), "warning");
// }
// }
| import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.plugins.tracer.PostTraceNotifications;
import static org.openstreetmap.josm.tools.I18n.tr; | /**
* Tracer - plugin for JOSM
* Jan Bilak, Marian Kyral, Martin Svec
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openstreetmap.josm.plugins.tracer.connectways;
public class ClipObjectArea {
private final WayEditor m_editor;
private final ClipAreasSettings m_settings; | // Path: src/org/openstreetmap/josm/plugins/tracer/PostTraceNotifications.java
// public class PostTraceNotifications {
// private final List<String> m_list = new ArrayList<> ();
//
// public void clear() {
// synchronized(m_list) {
// m_list.clear();
// }
// }
//
// public void add(String s) {
// System.out.println("Notify: " + s);
// synchronized(m_list) {
// m_list.add(s);
// }
// }
//
// public void show () {
// StringBuilder sb = new StringBuilder();
// synchronized(m_list) {
// if (m_list.isEmpty())
// return;
// for (String s: m_list) {
// if (sb.length() != 0)
// sb.append("\n");
// sb.append(s);
// }
// m_list.clear();
// }
// TracerUtils.showNotification(sb.toString(), "warning");
// }
// }
// Path: src/org/openstreetmap/josm/plugins/tracer/connectways/ClipObjectArea.java
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.plugins.tracer.PostTraceNotifications;
import static org.openstreetmap.josm.tools.I18n.tr;
/**
* Tracer - plugin for JOSM
* Jan Bilak, Marian Kyral, Martin Svec
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openstreetmap.josm.plugins.tracer.connectways;
public class ClipObjectArea {
private final WayEditor m_editor;
private final ClipAreasSettings m_settings; | private final PostTraceNotifications m_postTraceNotifications; |
mkyral/josm-tracer | src/org/openstreetmap/josm/plugins/tracer/connectways/RetraceUpdater.java | // Path: src/org/openstreetmap/josm/plugins/tracer/PostTraceNotifications.java
// public class PostTraceNotifications {
// private final List<String> m_list = new ArrayList<> ();
//
// public void clear() {
// synchronized(m_list) {
// m_list.clear();
// }
// }
//
// public void add(String s) {
// System.out.println("Notify: " + s);
// synchronized(m_list) {
// m_list.add(s);
// }
// }
//
// public void show () {
// StringBuilder sb = new StringBuilder();
// synchronized(m_list) {
// if (m_list.isEmpty())
// return;
// for (String s: m_list) {
// if (sb.length() != 0)
// sb.append("\n");
// sb.append(s);
// }
// m_list.clear();
// }
// TracerUtils.showNotification(sb.toString(), "warning");
// }
// }
| import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openstreetmap.josm.plugins.tracer.PostTraceNotifications;
import org.openstreetmap.josm.spi.preferences.Config;
import static org.openstreetmap.josm.tools.I18n.tr; | /**
* Tracer - plugin for JOSM
* Jan Bilak, Marian Kyral, Martin Svec
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openstreetmap.josm.plugins.tracer.connectways;
public class RetraceUpdater {
private final boolean m_convertOldStyleMultipolygons; | // Path: src/org/openstreetmap/josm/plugins/tracer/PostTraceNotifications.java
// public class PostTraceNotifications {
// private final List<String> m_list = new ArrayList<> ();
//
// public void clear() {
// synchronized(m_list) {
// m_list.clear();
// }
// }
//
// public void add(String s) {
// System.out.println("Notify: " + s);
// synchronized(m_list) {
// m_list.add(s);
// }
// }
//
// public void show () {
// StringBuilder sb = new StringBuilder();
// synchronized(m_list) {
// if (m_list.isEmpty())
// return;
// for (String s: m_list) {
// if (sb.length() != 0)
// sb.append("\n");
// sb.append(s);
// }
// m_list.clear();
// }
// TracerUtils.showNotification(sb.toString(), "warning");
// }
// }
// Path: src/org/openstreetmap/josm/plugins/tracer/connectways/RetraceUpdater.java
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openstreetmap.josm.plugins.tracer.PostTraceNotifications;
import org.openstreetmap.josm.spi.preferences.Config;
import static org.openstreetmap.josm.tools.I18n.tr;
/**
* Tracer - plugin for JOSM
* Jan Bilak, Marian Kyral, Martin Svec
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openstreetmap.josm.plugins.tracer.connectways;
public class RetraceUpdater {
private final boolean m_convertOldStyleMultipolygons; | private final PostTraceNotifications m_postTraceNotifications; |
mkyral/josm-tracer | src/org/openstreetmap/josm/plugins/tracer/connectways/ClipAreas.java | // Path: src/org/openstreetmap/josm/plugins/tracer/PostTraceNotifications.java
// public class PostTraceNotifications {
// private final List<String> m_list = new ArrayList<> ();
//
// public void clear() {
// synchronized(m_list) {
// m_list.clear();
// }
// }
//
// public void add(String s) {
// System.out.println("Notify: " + s);
// synchronized(m_list) {
// m_list.add(s);
// }
// }
//
// public void show () {
// StringBuilder sb = new StringBuilder();
// synchronized(m_list) {
// if (m_list.isEmpty())
// return;
// for (String s: m_list) {
// if (sb.length() != 0)
// sb.append("\n");
// sb.append(s);
// }
// m_list.clear();
// }
// TracerUtils.showNotification(sb.toString(), "warning");
// }
// }
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import org.openstreetmap.josm.plugins.tracer.PostTraceNotifications;
import static org.openstreetmap.josm.tools.I18n.tr;
import org.openstreetmap.josm.tools.Pair; | /**
* Tracer - plugin for JOSM
* Jan Bilak, Marian Kyral, Martin Svec
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openstreetmap.josm.plugins.tracer.connectways;
public class ClipAreas {
private final WayEditor m_editor;
private final ClipAreasSettings m_settings; | // Path: src/org/openstreetmap/josm/plugins/tracer/PostTraceNotifications.java
// public class PostTraceNotifications {
// private final List<String> m_list = new ArrayList<> ();
//
// public void clear() {
// synchronized(m_list) {
// m_list.clear();
// }
// }
//
// public void add(String s) {
// System.out.println("Notify: " + s);
// synchronized(m_list) {
// m_list.add(s);
// }
// }
//
// public void show () {
// StringBuilder sb = new StringBuilder();
// synchronized(m_list) {
// if (m_list.isEmpty())
// return;
// for (String s: m_list) {
// if (sb.length() != 0)
// sb.append("\n");
// sb.append(s);
// }
// m_list.clear();
// }
// TracerUtils.showNotification(sb.toString(), "warning");
// }
// }
// Path: src/org/openstreetmap/josm/plugins/tracer/connectways/ClipAreas.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import org.openstreetmap.josm.plugins.tracer.PostTraceNotifications;
import static org.openstreetmap.josm.tools.I18n.tr;
import org.openstreetmap.josm.tools.Pair;
/**
* Tracer - plugin for JOSM
* Jan Bilak, Marian Kyral, Martin Svec
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openstreetmap.josm.plugins.tracer.connectways;
public class ClipAreas {
private final WayEditor m_editor;
private final ClipAreasSettings m_settings; | private final PostTraceNotifications m_postTraceNotifications; |
mkyral/josm-tracer | src/org/openstreetmap/josm/plugins/tracer/modules/lpis/LpisServer.java | // Path: src/org/openstreetmap/josm/plugins/tracer/connectways/LatLonSize.java
// public class LatLonSize {
// private final double m_lat;
// private final double m_lon;
//
// public LatLonSize(double lat, double lon) {
// m_lat = lat;
// m_lon = lon;
// }
//
// public double latSize() {
// return m_lat;
// }
//
// public double lonSize() {
// return m_lon;
// }
//
// public boolean isZero() {
// return m_lat == 0 && m_lon == 0;
// }
//
// public static final LatLonSize Zero = new LatLonSize(0, 0);
//
// public static LatLonSize get(LatLon ll, double radius_in_meters) {
// double meters_per_degree_lat = GeomUtils.getMetersPerDegreeOfLatitude(ll);
// double meters_per_degree_lon = GeomUtils.getMetersPerDegreeOfLongitude(ll);
// double radius_lat = radius_in_meters / meters_per_degree_lat;
// double radius_lon = radius_in_meters / meters_per_degree_lon;
// return new LatLonSize(radius_lat, radius_lon);
// }
//
// public static LatLonSize get(BBox box, double radius_in_meters) {
// double meters_per_degree_lat1 = GeomUtils.getMetersPerDegreeOfLatitude(box.getTopLeft());
// double meters_per_degree_lon1 = GeomUtils.getMetersPerDegreeOfLongitude(box.getTopLeft());
// double meters_per_degree_lat2 = GeomUtils.getMetersPerDegreeOfLatitude(box.getBottomRight());
// double meters_per_degree_lon2 = GeomUtils.getMetersPerDegreeOfLongitude(box.getBottomRight());
// double radius_lat = radius_in_meters / Math.min(meters_per_degree_lat1, meters_per_degree_lat2);
// double radius_lon = radius_in_meters / Math.min(meters_per_degree_lon1, meters_per_degree_lon2);
// return new LatLonSize(radius_lat, radius_lon);
// }
// }
| import org.xml.sax.SAXException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.data.osm.BBox;
import org.openstreetmap.josm.plugins.tracer.TracerUtils;
import org.openstreetmap.josm.plugins.tracer.connectways.LatLonSize; | /**
* Tracer - plugin for JOSM (RUIAN support)
* Jan Bilak, Marian Kyral
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openstreetmap.josm.plugins.tracer.modules.lpis;
public class LpisServer {
private final String m_url;
private final LpisCache m_lpisCache;
// LpisRecords have fixed constant coord adjustment
private static final double adjustLat = 0.0;
private static final double adjustLon = 0.0;
| // Path: src/org/openstreetmap/josm/plugins/tracer/connectways/LatLonSize.java
// public class LatLonSize {
// private final double m_lat;
// private final double m_lon;
//
// public LatLonSize(double lat, double lon) {
// m_lat = lat;
// m_lon = lon;
// }
//
// public double latSize() {
// return m_lat;
// }
//
// public double lonSize() {
// return m_lon;
// }
//
// public boolean isZero() {
// return m_lat == 0 && m_lon == 0;
// }
//
// public static final LatLonSize Zero = new LatLonSize(0, 0);
//
// public static LatLonSize get(LatLon ll, double radius_in_meters) {
// double meters_per_degree_lat = GeomUtils.getMetersPerDegreeOfLatitude(ll);
// double meters_per_degree_lon = GeomUtils.getMetersPerDegreeOfLongitude(ll);
// double radius_lat = radius_in_meters / meters_per_degree_lat;
// double radius_lon = radius_in_meters / meters_per_degree_lon;
// return new LatLonSize(radius_lat, radius_lon);
// }
//
// public static LatLonSize get(BBox box, double radius_in_meters) {
// double meters_per_degree_lat1 = GeomUtils.getMetersPerDegreeOfLatitude(box.getTopLeft());
// double meters_per_degree_lon1 = GeomUtils.getMetersPerDegreeOfLongitude(box.getTopLeft());
// double meters_per_degree_lat2 = GeomUtils.getMetersPerDegreeOfLatitude(box.getBottomRight());
// double meters_per_degree_lon2 = GeomUtils.getMetersPerDegreeOfLongitude(box.getBottomRight());
// double radius_lat = radius_in_meters / Math.min(meters_per_degree_lat1, meters_per_degree_lat2);
// double radius_lon = radius_in_meters / Math.min(meters_per_degree_lon1, meters_per_degree_lon2);
// return new LatLonSize(radius_lat, radius_lon);
// }
// }
// Path: src/org/openstreetmap/josm/plugins/tracer/modules/lpis/LpisServer.java
import org.xml.sax.SAXException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.data.osm.BBox;
import org.openstreetmap.josm.plugins.tracer.TracerUtils;
import org.openstreetmap.josm.plugins.tracer.connectways.LatLonSize;
/**
* Tracer - plugin for JOSM (RUIAN support)
* Jan Bilak, Marian Kyral
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openstreetmap.josm.plugins.tracer.modules.lpis;
public class LpisServer {
private final String m_url;
private final LpisCache m_lpisCache;
// LpisRecords have fixed constant coord adjustment
private static final double adjustLat = 0.0;
private static final double adjustLon = 0.0;
| public LpisServer(String url, LatLonSize cache_tile_size) { |
mkyral/josm-tracer | src/org/openstreetmap/josm/plugins/tracer/connectways/AngPolygonClipper.java | // Path: src/org/openstreetmap/josm/plugins/tracer/clipper/Path.java
// public class Path extends ArrayList<Point2d> {
// void reverse() {
// Collections.reverse(this);
// }
// }
//
// Path: src/org/openstreetmap/josm/plugins/tracer/clipper/Paths.java
// public class Paths extends ArrayList<Path>{
//
// }
| import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openstreetmap.josm.data.Bounds;
import org.openstreetmap.josm.data.coor.EastNorth;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.data.projection.ProjectionRegistry;
import org.openstreetmap.josm.plugins.tracer.clipper.ClipType;
import org.openstreetmap.josm.plugins.tracer.clipper.Clipper;
import org.openstreetmap.josm.plugins.tracer.clipper.ClipperException;
import org.openstreetmap.josm.plugins.tracer.clipper.Path;
import org.openstreetmap.josm.plugins.tracer.clipper.Paths;
import org.openstreetmap.josm.plugins.tracer.clipper.Point2d;
import org.openstreetmap.josm.plugins.tracer.clipper.PolyNode;
import org.openstreetmap.josm.plugins.tracer.clipper.PolyTree;
import org.openstreetmap.josm.plugins.tracer.clipper.PolyType; | }
}
for (List<EdNode> list: m_inners) {
for (EdNode n: list) {
if (!m_subjectNodes.contains(n))
if (!n.isInsideBounds(bounds, LatLonSize.Zero)) {
System.out.println("Clip adds new inner node outside downloaded area: " + Long.toString(n.getUniqueId()) + ", " + n.getCoor().toDisplayString());
return true;
}
cur_nodes.add(n);
}
}
// Test removed subject nodes not occurring in current nodes
for (EdNode node: m_subjectNodes) {
if (!cur_nodes.contains(node))
if (!node.isInsideBounds(bounds, LatLonSize.Zero)) {
System.out.println("Clip removes node outside downloaded area: " + Long.toString(node.getUniqueId()) + ", " + node.getCoor().toDisplayString());
return true;
}
}
return false;
}
private void processPolyNode(PolyNode pn, List<List<EdNode>> aouters, List<List<EdNode>> ainners, double subj_area) {
List<List<EdNode>> outers = aouters;
List<List<EdNode>> inners = ainners;
| // Path: src/org/openstreetmap/josm/plugins/tracer/clipper/Path.java
// public class Path extends ArrayList<Point2d> {
// void reverse() {
// Collections.reverse(this);
// }
// }
//
// Path: src/org/openstreetmap/josm/plugins/tracer/clipper/Paths.java
// public class Paths extends ArrayList<Path>{
//
// }
// Path: src/org/openstreetmap/josm/plugins/tracer/connectways/AngPolygonClipper.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openstreetmap.josm.data.Bounds;
import org.openstreetmap.josm.data.coor.EastNorth;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.data.projection.ProjectionRegistry;
import org.openstreetmap.josm.plugins.tracer.clipper.ClipType;
import org.openstreetmap.josm.plugins.tracer.clipper.Clipper;
import org.openstreetmap.josm.plugins.tracer.clipper.ClipperException;
import org.openstreetmap.josm.plugins.tracer.clipper.Path;
import org.openstreetmap.josm.plugins.tracer.clipper.Paths;
import org.openstreetmap.josm.plugins.tracer.clipper.Point2d;
import org.openstreetmap.josm.plugins.tracer.clipper.PolyNode;
import org.openstreetmap.josm.plugins.tracer.clipper.PolyTree;
import org.openstreetmap.josm.plugins.tracer.clipper.PolyType;
}
}
for (List<EdNode> list: m_inners) {
for (EdNode n: list) {
if (!m_subjectNodes.contains(n))
if (!n.isInsideBounds(bounds, LatLonSize.Zero)) {
System.out.println("Clip adds new inner node outside downloaded area: " + Long.toString(n.getUniqueId()) + ", " + n.getCoor().toDisplayString());
return true;
}
cur_nodes.add(n);
}
}
// Test removed subject nodes not occurring in current nodes
for (EdNode node: m_subjectNodes) {
if (!cur_nodes.contains(node))
if (!node.isInsideBounds(bounds, LatLonSize.Zero)) {
System.out.println("Clip removes node outside downloaded area: " + Long.toString(node.getUniqueId()) + ", " + node.getCoor().toDisplayString());
return true;
}
}
return false;
}
private void processPolyNode(PolyNode pn, List<List<EdNode>> aouters, List<List<EdNode>> ainners, double subj_area) {
List<List<EdNode>> outers = aouters;
List<List<EdNode>> inners = ainners;
| Path path = pn.getContour(); |
mkyral/josm-tracer | src/org/openstreetmap/josm/plugins/tracer/connectways/AngPolygonClipper.java | // Path: src/org/openstreetmap/josm/plugins/tracer/clipper/Path.java
// public class Path extends ArrayList<Point2d> {
// void reverse() {
// Collections.reverse(this);
// }
// }
//
// Path: src/org/openstreetmap/josm/plugins/tracer/clipper/Paths.java
// public class Paths extends ArrayList<Path>{
//
// }
| import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openstreetmap.josm.data.Bounds;
import org.openstreetmap.josm.data.coor.EastNorth;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.data.projection.ProjectionRegistry;
import org.openstreetmap.josm.plugins.tracer.clipper.ClipType;
import org.openstreetmap.josm.plugins.tracer.clipper.Clipper;
import org.openstreetmap.josm.plugins.tracer.clipper.ClipperException;
import org.openstreetmap.josm.plugins.tracer.clipper.Path;
import org.openstreetmap.josm.plugins.tracer.clipper.Paths;
import org.openstreetmap.josm.plugins.tracer.clipper.Point2d;
import org.openstreetmap.josm.plugins.tracer.clipper.PolyNode;
import org.openstreetmap.josm.plugins.tracer.clipper.PolyTree;
import org.openstreetmap.josm.plugins.tracer.clipper.PolyType; | // present JOSM projection! Or try to rewrite clipper to floating point...
private final static double fixedPointScale = 10000000000.0;
private Point2d nodeToPoint2d(EdNode node) {
EastNorth en = node.getEastNorth();
long x = (long)(en.getX() * fixedPointScale);
long y = (long)(en.getY() * fixedPointScale);
Point2d pt = new Point2d(x, y);
m_nodesMap.put(node.getCoor().getRoundedToOsmPrecision(), node);
return pt;
}
private EdNode point2dToNode(Point2d pt) {
// perform inverse projection to LatLon
double x = ((double)pt.X) / fixedPointScale;
double y = ((double)pt.Y) / fixedPointScale;
EastNorth en = new EastNorth (x,y);
LatLon ll = ProjectionRegistry.getProjection().eastNorth2latlon(en);
// lookup in LatLon map
EdNode node = m_nodesMap.get(ll.getRoundedToOsmPrecision());
if (node != null)
return node;
// create new node
node = m_editor.newNode(ll);
m_nodesMap.put(ll, node);
return node;
}
| // Path: src/org/openstreetmap/josm/plugins/tracer/clipper/Path.java
// public class Path extends ArrayList<Point2d> {
// void reverse() {
// Collections.reverse(this);
// }
// }
//
// Path: src/org/openstreetmap/josm/plugins/tracer/clipper/Paths.java
// public class Paths extends ArrayList<Path>{
//
// }
// Path: src/org/openstreetmap/josm/plugins/tracer/connectways/AngPolygonClipper.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openstreetmap.josm.data.Bounds;
import org.openstreetmap.josm.data.coor.EastNorth;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.data.projection.ProjectionRegistry;
import org.openstreetmap.josm.plugins.tracer.clipper.ClipType;
import org.openstreetmap.josm.plugins.tracer.clipper.Clipper;
import org.openstreetmap.josm.plugins.tracer.clipper.ClipperException;
import org.openstreetmap.josm.plugins.tracer.clipper.Path;
import org.openstreetmap.josm.plugins.tracer.clipper.Paths;
import org.openstreetmap.josm.plugins.tracer.clipper.Point2d;
import org.openstreetmap.josm.plugins.tracer.clipper.PolyNode;
import org.openstreetmap.josm.plugins.tracer.clipper.PolyTree;
import org.openstreetmap.josm.plugins.tracer.clipper.PolyType;
// present JOSM projection! Or try to rewrite clipper to floating point...
private final static double fixedPointScale = 10000000000.0;
private Point2d nodeToPoint2d(EdNode node) {
EastNorth en = node.getEastNorth();
long x = (long)(en.getX() * fixedPointScale);
long y = (long)(en.getY() * fixedPointScale);
Point2d pt = new Point2d(x, y);
m_nodesMap.put(node.getCoor().getRoundedToOsmPrecision(), node);
return pt;
}
private EdNode point2dToNode(Point2d pt) {
// perform inverse projection to LatLon
double x = ((double)pt.X) / fixedPointScale;
double y = ((double)pt.Y) / fixedPointScale;
EastNorth en = new EastNorth (x,y);
LatLon ll = ProjectionRegistry.getProjection().eastNorth2latlon(en);
// lookup in LatLon map
EdNode node = m_nodesMap.get(ll.getRoundedToOsmPrecision());
if (node != null)
return node;
// create new node
node = m_editor.newNode(ll);
m_nodesMap.put(ll, node);
return node;
}
| private Paths edObjectToPaths(EdObject obj, boolean issubj) { |
Adobe-Marketing-Cloud/analytics-live-stream-api-samples | solutions/lab4/java/test/java/lab4/test/LiveStreamConnectionTest.java | // Path: solutions/lab4/java/src/lab4/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
//
// Path: lab4/java/src/lab4/LiveStreamConnection.java
// public class LiveStreamConnection {
//
// public static final Logger log = LoggerFactory.getLogger(LiveStreamConnection.class);
//
// public static final int VISITOR_ID_SAMPLE_PERIOD_SECONDS = 90;
//
// protected String endpointUrl;
// protected String accessToken;
//
// public LiveStreamConnection(String endpointUrl, String accessToken)
// {
// }
//
// public void open() throws IOException {
// // Use your code or the solution from lab3 to open the connection.
// // Then, extract the visitor ID from each hit record by taking the visIdHigh and
// // visIdLow fields from the record and combining them (you can concatenate them
// // as strings). Store these visitor IDs in a data structure and maintain a count of
// // how many times each visitor ID is presented. Do this for at least 90 seconds.
// // Optionally, calculate the average number of hit records per visit, and determine
// // how many visits contain exactly the average number of hit records.
// }
// }
| import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab4.TokenRequest;
import lab4.LiveStreamConnection;
import lab.Credentials; | package lab4.test;
public class LiveStreamConnectionTest
{
final Logger log = LoggerFactory.getLogger(LiveStreamConnectionTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testLiveStreamConnection()
throws Exception
{
Credentials credentials = new Credentials(); | // Path: solutions/lab4/java/src/lab4/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
//
// Path: lab4/java/src/lab4/LiveStreamConnection.java
// public class LiveStreamConnection {
//
// public static final Logger log = LoggerFactory.getLogger(LiveStreamConnection.class);
//
// public static final int VISITOR_ID_SAMPLE_PERIOD_SECONDS = 90;
//
// protected String endpointUrl;
// protected String accessToken;
//
// public LiveStreamConnection(String endpointUrl, String accessToken)
// {
// }
//
// public void open() throws IOException {
// // Use your code or the solution from lab3 to open the connection.
// // Then, extract the visitor ID from each hit record by taking the visIdHigh and
// // visIdLow fields from the record and combining them (you can concatenate them
// // as strings). Store these visitor IDs in a data structure and maintain a count of
// // how many times each visitor ID is presented. Do this for at least 90 seconds.
// // Optionally, calculate the average number of hit records per visit, and determine
// // how many visits contain exactly the average number of hit records.
// }
// }
// Path: solutions/lab4/java/test/java/lab4/test/LiveStreamConnectionTest.java
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab4.TokenRequest;
import lab4.LiveStreamConnection;
import lab.Credentials;
package lab4.test;
public class LiveStreamConnectionTest
{
final Logger log = LoggerFactory.getLogger(LiveStreamConnectionTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testLiveStreamConnection()
throws Exception
{
Credentials credentials = new Credentials(); | TokenRequest request = new TokenRequest(credentials.getClientId(), credentials.getClientSecret()); |
Adobe-Marketing-Cloud/analytics-live-stream-api-samples | solutions/lab4/java/test/java/lab4/test/LiveStreamConnectionTest.java | // Path: solutions/lab4/java/src/lab4/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
//
// Path: lab4/java/src/lab4/LiveStreamConnection.java
// public class LiveStreamConnection {
//
// public static final Logger log = LoggerFactory.getLogger(LiveStreamConnection.class);
//
// public static final int VISITOR_ID_SAMPLE_PERIOD_SECONDS = 90;
//
// protected String endpointUrl;
// protected String accessToken;
//
// public LiveStreamConnection(String endpointUrl, String accessToken)
// {
// }
//
// public void open() throws IOException {
// // Use your code or the solution from lab3 to open the connection.
// // Then, extract the visitor ID from each hit record by taking the visIdHigh and
// // visIdLow fields from the record and combining them (you can concatenate them
// // as strings). Store these visitor IDs in a data structure and maintain a count of
// // how many times each visitor ID is presented. Do this for at least 90 seconds.
// // Optionally, calculate the average number of hit records per visit, and determine
// // how many visits contain exactly the average number of hit records.
// }
// }
| import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab4.TokenRequest;
import lab4.LiveStreamConnection;
import lab.Credentials; | package lab4.test;
public class LiveStreamConnectionTest
{
final Logger log = LoggerFactory.getLogger(LiveStreamConnectionTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testLiveStreamConnection()
throws Exception
{
Credentials credentials = new Credentials();
TokenRequest request = new TokenRequest(credentials.getClientId(), credentials.getClientSecret());
String response = request.request();
assertNotNull(response);
log.info("response is:\n"+response);
String accessToken = request.parseResponse(response);
assertNotNull(response);
log.info("access_token is: "+accessToken);
| // Path: solutions/lab4/java/src/lab4/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
//
// Path: lab4/java/src/lab4/LiveStreamConnection.java
// public class LiveStreamConnection {
//
// public static final Logger log = LoggerFactory.getLogger(LiveStreamConnection.class);
//
// public static final int VISITOR_ID_SAMPLE_PERIOD_SECONDS = 90;
//
// protected String endpointUrl;
// protected String accessToken;
//
// public LiveStreamConnection(String endpointUrl, String accessToken)
// {
// }
//
// public void open() throws IOException {
// // Use your code or the solution from lab3 to open the connection.
// // Then, extract the visitor ID from each hit record by taking the visIdHigh and
// // visIdLow fields from the record and combining them (you can concatenate them
// // as strings). Store these visitor IDs in a data structure and maintain a count of
// // how many times each visitor ID is presented. Do this for at least 90 seconds.
// // Optionally, calculate the average number of hit records per visit, and determine
// // how many visits contain exactly the average number of hit records.
// }
// }
// Path: solutions/lab4/java/test/java/lab4/test/LiveStreamConnectionTest.java
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab4.TokenRequest;
import lab4.LiveStreamConnection;
import lab.Credentials;
package lab4.test;
public class LiveStreamConnectionTest
{
final Logger log = LoggerFactory.getLogger(LiveStreamConnectionTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testLiveStreamConnection()
throws Exception
{
Credentials credentials = new Credentials();
TokenRequest request = new TokenRequest(credentials.getClientId(), credentials.getClientSecret());
String response = request.request();
assertNotNull(response);
log.info("response is:\n"+response);
String accessToken = request.parseResponse(response);
assertNotNull(response);
log.info("access_token is: "+accessToken);
| LiveStreamConnection connection = new LiveStreamConnection(credentials.getLivestreamEndpointUrl(), accessToken); |
Adobe-Marketing-Cloud/analytics-live-stream-api-samples | solutions/lab2/java/test/java/lab2/test/LiveStreamConnectionTest.java | // Path: solutions/lab2/java/src/lab2/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
//
// Path: solutions/lab2/java/src/lab2/LiveStreamConnection.java
// public class LiveStreamConnection {
//
// public static final Logger log = LoggerFactory.getLogger(LiveStreamConnection.class);
//
// protected String endpointUrl;
// protected String accessToken;
//
// public LiveStreamConnection(String endpointUrl, String accessToken)
// {
// this.endpointUrl = endpointUrl;
// this.accessToken = accessToken;
// }
//
// public void open() throws IOException {
// log.debug("opening live stream connection to " + this.endpointUrl);
// URL url = new URL(this.endpointUrl);
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Bearer " + this.accessToken);
// connection.setRequestProperty("Accept-Encoding", "gzip");
// connection.setRequestMethod("GET");
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
// throw new IOException(connection.getResponseMessage() + " (" + connection.getResponseCode() + ")");
// }
//
// InputStream inputStream = new GZIPInputStream(connection.getInputStream());
// BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// System.out.println(line);
// calculate_lag(line);
// System.out.println("-------------------------------------");
// }
// }
// }
//
// public void calculate_lag(String record) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(record, Map.class);
// Integer timestamp = (Integer)jsonModel.get("receivedTimeGMT");
// if (timestamp == null) {
// log.error("unable to find receivedTimeGMT field in record for lag calculation");
// } else {
// long now = System.currentTimeMillis() / 1000; // now should be in seconds
// System.out.println("calculate_lag: record lag is " + (now - timestamp.longValue()) + " seconds");
// }
// }
// }
| import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab2.TokenRequest;
import lab2.LiveStreamConnection;
import lab.Credentials; | package lab2.test;
public class LiveStreamConnectionTest
{
final Logger log = LoggerFactory.getLogger(LiveStreamConnectionTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testLiveStreamConnection()
throws Exception
{
Credentials credentials = new Credentials(); | // Path: solutions/lab2/java/src/lab2/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
//
// Path: solutions/lab2/java/src/lab2/LiveStreamConnection.java
// public class LiveStreamConnection {
//
// public static final Logger log = LoggerFactory.getLogger(LiveStreamConnection.class);
//
// protected String endpointUrl;
// protected String accessToken;
//
// public LiveStreamConnection(String endpointUrl, String accessToken)
// {
// this.endpointUrl = endpointUrl;
// this.accessToken = accessToken;
// }
//
// public void open() throws IOException {
// log.debug("opening live stream connection to " + this.endpointUrl);
// URL url = new URL(this.endpointUrl);
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Bearer " + this.accessToken);
// connection.setRequestProperty("Accept-Encoding", "gzip");
// connection.setRequestMethod("GET");
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
// throw new IOException(connection.getResponseMessage() + " (" + connection.getResponseCode() + ")");
// }
//
// InputStream inputStream = new GZIPInputStream(connection.getInputStream());
// BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// System.out.println(line);
// calculate_lag(line);
// System.out.println("-------------------------------------");
// }
// }
// }
//
// public void calculate_lag(String record) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(record, Map.class);
// Integer timestamp = (Integer)jsonModel.get("receivedTimeGMT");
// if (timestamp == null) {
// log.error("unable to find receivedTimeGMT field in record for lag calculation");
// } else {
// long now = System.currentTimeMillis() / 1000; // now should be in seconds
// System.out.println("calculate_lag: record lag is " + (now - timestamp.longValue()) + " seconds");
// }
// }
// }
// Path: solutions/lab2/java/test/java/lab2/test/LiveStreamConnectionTest.java
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab2.TokenRequest;
import lab2.LiveStreamConnection;
import lab.Credentials;
package lab2.test;
public class LiveStreamConnectionTest
{
final Logger log = LoggerFactory.getLogger(LiveStreamConnectionTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testLiveStreamConnection()
throws Exception
{
Credentials credentials = new Credentials(); | TokenRequest request = new TokenRequest(credentials.getClientId(), credentials.getClientSecret()); |
Adobe-Marketing-Cloud/analytics-live-stream-api-samples | solutions/lab2/java/test/java/lab2/test/LiveStreamConnectionTest.java | // Path: solutions/lab2/java/src/lab2/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
//
// Path: solutions/lab2/java/src/lab2/LiveStreamConnection.java
// public class LiveStreamConnection {
//
// public static final Logger log = LoggerFactory.getLogger(LiveStreamConnection.class);
//
// protected String endpointUrl;
// protected String accessToken;
//
// public LiveStreamConnection(String endpointUrl, String accessToken)
// {
// this.endpointUrl = endpointUrl;
// this.accessToken = accessToken;
// }
//
// public void open() throws IOException {
// log.debug("opening live stream connection to " + this.endpointUrl);
// URL url = new URL(this.endpointUrl);
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Bearer " + this.accessToken);
// connection.setRequestProperty("Accept-Encoding", "gzip");
// connection.setRequestMethod("GET");
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
// throw new IOException(connection.getResponseMessage() + " (" + connection.getResponseCode() + ")");
// }
//
// InputStream inputStream = new GZIPInputStream(connection.getInputStream());
// BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// System.out.println(line);
// calculate_lag(line);
// System.out.println("-------------------------------------");
// }
// }
// }
//
// public void calculate_lag(String record) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(record, Map.class);
// Integer timestamp = (Integer)jsonModel.get("receivedTimeGMT");
// if (timestamp == null) {
// log.error("unable to find receivedTimeGMT field in record for lag calculation");
// } else {
// long now = System.currentTimeMillis() / 1000; // now should be in seconds
// System.out.println("calculate_lag: record lag is " + (now - timestamp.longValue()) + " seconds");
// }
// }
// }
| import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab2.TokenRequest;
import lab2.LiveStreamConnection;
import lab.Credentials; | package lab2.test;
public class LiveStreamConnectionTest
{
final Logger log = LoggerFactory.getLogger(LiveStreamConnectionTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testLiveStreamConnection()
throws Exception
{
Credentials credentials = new Credentials();
TokenRequest request = new TokenRequest(credentials.getClientId(), credentials.getClientSecret());
String response = request.request();
assertNotNull(response);
log.info("response is:\n"+response);
String accessToken = request.parseResponse(response);
assertNotNull(response);
log.info("access_token is: "+accessToken);
| // Path: solutions/lab2/java/src/lab2/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
//
// Path: solutions/lab2/java/src/lab2/LiveStreamConnection.java
// public class LiveStreamConnection {
//
// public static final Logger log = LoggerFactory.getLogger(LiveStreamConnection.class);
//
// protected String endpointUrl;
// protected String accessToken;
//
// public LiveStreamConnection(String endpointUrl, String accessToken)
// {
// this.endpointUrl = endpointUrl;
// this.accessToken = accessToken;
// }
//
// public void open() throws IOException {
// log.debug("opening live stream connection to " + this.endpointUrl);
// URL url = new URL(this.endpointUrl);
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Bearer " + this.accessToken);
// connection.setRequestProperty("Accept-Encoding", "gzip");
// connection.setRequestMethod("GET");
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
// throw new IOException(connection.getResponseMessage() + " (" + connection.getResponseCode() + ")");
// }
//
// InputStream inputStream = new GZIPInputStream(connection.getInputStream());
// BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// System.out.println(line);
// calculate_lag(line);
// System.out.println("-------------------------------------");
// }
// }
// }
//
// public void calculate_lag(String record) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(record, Map.class);
// Integer timestamp = (Integer)jsonModel.get("receivedTimeGMT");
// if (timestamp == null) {
// log.error("unable to find receivedTimeGMT field in record for lag calculation");
// } else {
// long now = System.currentTimeMillis() / 1000; // now should be in seconds
// System.out.println("calculate_lag: record lag is " + (now - timestamp.longValue()) + " seconds");
// }
// }
// }
// Path: solutions/lab2/java/test/java/lab2/test/LiveStreamConnectionTest.java
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab2.TokenRequest;
import lab2.LiveStreamConnection;
import lab.Credentials;
package lab2.test;
public class LiveStreamConnectionTest
{
final Logger log = LoggerFactory.getLogger(LiveStreamConnectionTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testLiveStreamConnection()
throws Exception
{
Credentials credentials = new Credentials();
TokenRequest request = new TokenRequest(credentials.getClientId(), credentials.getClientSecret());
String response = request.request();
assertNotNull(response);
log.info("response is:\n"+response);
String accessToken = request.parseResponse(response);
assertNotNull(response);
log.info("access_token is: "+accessToken);
| LiveStreamConnection connection = new LiveStreamConnection(credentials.getLivestreamEndpointUrl(), accessToken); |
Adobe-Marketing-Cloud/analytics-live-stream-api-samples | solutions/lab3/java/test/java/lab3/test/LiveStreamConnectionTest.java | // Path: solutions/lab3/java/src/lab3/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
//
// Path: lab3/java/src/lab3/LiveStreamConnection.java
// public class LiveStreamConnection {
//
// public static final Logger log = LoggerFactory.getLogger(LiveStreamConnection.class);
//
// public static final int STREAM_RATE_SAMPLE_PERIOD_SECONDS = 60;
//
// protected String endpointUrl;
// protected String accessToken;
//
// public LiveStreamConnection(String endpointUrl, String accessToken)
// {
// }
//
// public void open() throws IOException {
// // Use your code or the solution from lab2 to open the connection.
// // Then, calculate the stream rate in records per second after counting
// // for at least 60 seconds. Optionally, you can also calculate the
// // transfer rate in kbytes per seconds.
// }
// }
| import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab3.TokenRequest;
import lab3.LiveStreamConnection;
import lab.Credentials; | package lab3.test;
public class LiveStreamConnectionTest
{
final Logger log = LoggerFactory.getLogger(LiveStreamConnectionTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testLiveStreamConnection()
throws Exception
{
Credentials credentials = new Credentials(); | // Path: solutions/lab3/java/src/lab3/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
//
// Path: lab3/java/src/lab3/LiveStreamConnection.java
// public class LiveStreamConnection {
//
// public static final Logger log = LoggerFactory.getLogger(LiveStreamConnection.class);
//
// public static final int STREAM_RATE_SAMPLE_PERIOD_SECONDS = 60;
//
// protected String endpointUrl;
// protected String accessToken;
//
// public LiveStreamConnection(String endpointUrl, String accessToken)
// {
// }
//
// public void open() throws IOException {
// // Use your code or the solution from lab2 to open the connection.
// // Then, calculate the stream rate in records per second after counting
// // for at least 60 seconds. Optionally, you can also calculate the
// // transfer rate in kbytes per seconds.
// }
// }
// Path: solutions/lab3/java/test/java/lab3/test/LiveStreamConnectionTest.java
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab3.TokenRequest;
import lab3.LiveStreamConnection;
import lab.Credentials;
package lab3.test;
public class LiveStreamConnectionTest
{
final Logger log = LoggerFactory.getLogger(LiveStreamConnectionTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testLiveStreamConnection()
throws Exception
{
Credentials credentials = new Credentials(); | TokenRequest request = new TokenRequest(credentials.getClientId(), credentials.getClientSecret()); |
Adobe-Marketing-Cloud/analytics-live-stream-api-samples | solutions/lab3/java/test/java/lab3/test/LiveStreamConnectionTest.java | // Path: solutions/lab3/java/src/lab3/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
//
// Path: lab3/java/src/lab3/LiveStreamConnection.java
// public class LiveStreamConnection {
//
// public static final Logger log = LoggerFactory.getLogger(LiveStreamConnection.class);
//
// public static final int STREAM_RATE_SAMPLE_PERIOD_SECONDS = 60;
//
// protected String endpointUrl;
// protected String accessToken;
//
// public LiveStreamConnection(String endpointUrl, String accessToken)
// {
// }
//
// public void open() throws IOException {
// // Use your code or the solution from lab2 to open the connection.
// // Then, calculate the stream rate in records per second after counting
// // for at least 60 seconds. Optionally, you can also calculate the
// // transfer rate in kbytes per seconds.
// }
// }
| import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab3.TokenRequest;
import lab3.LiveStreamConnection;
import lab.Credentials; | package lab3.test;
public class LiveStreamConnectionTest
{
final Logger log = LoggerFactory.getLogger(LiveStreamConnectionTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testLiveStreamConnection()
throws Exception
{
Credentials credentials = new Credentials();
TokenRequest request = new TokenRequest(credentials.getClientId(), credentials.getClientSecret());
String response = request.request();
assertNotNull(response);
log.info("response is:\n"+response);
String accessToken = request.parseResponse(response);
assertNotNull(response);
log.info("access_token is: "+accessToken);
| // Path: solutions/lab3/java/src/lab3/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
//
// Path: lab3/java/src/lab3/LiveStreamConnection.java
// public class LiveStreamConnection {
//
// public static final Logger log = LoggerFactory.getLogger(LiveStreamConnection.class);
//
// public static final int STREAM_RATE_SAMPLE_PERIOD_SECONDS = 60;
//
// protected String endpointUrl;
// protected String accessToken;
//
// public LiveStreamConnection(String endpointUrl, String accessToken)
// {
// }
//
// public void open() throws IOException {
// // Use your code or the solution from lab2 to open the connection.
// // Then, calculate the stream rate in records per second after counting
// // for at least 60 seconds. Optionally, you can also calculate the
// // transfer rate in kbytes per seconds.
// }
// }
// Path: solutions/lab3/java/test/java/lab3/test/LiveStreamConnectionTest.java
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab3.TokenRequest;
import lab3.LiveStreamConnection;
import lab.Credentials;
package lab3.test;
public class LiveStreamConnectionTest
{
final Logger log = LoggerFactory.getLogger(LiveStreamConnectionTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testLiveStreamConnection()
throws Exception
{
Credentials credentials = new Credentials();
TokenRequest request = new TokenRequest(credentials.getClientId(), credentials.getClientSecret());
String response = request.request();
assertNotNull(response);
log.info("response is:\n"+response);
String accessToken = request.parseResponse(response);
assertNotNull(response);
log.info("access_token is: "+accessToken);
| LiveStreamConnection connection = new LiveStreamConnection(credentials.getLivestreamEndpointUrl(), accessToken); |
Adobe-Marketing-Cloud/analytics-live-stream-api-samples | solutions/lab4/java/test/java/lab4/test/TokenRequestTest.java | // Path: solutions/lab4/java/src/lab4/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
| import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab4.TokenRequest;
import lab.Credentials; | package lab4.test;
public class TokenRequestTest
{
final Logger log = LoggerFactory.getLogger(TokenRequestTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testRequest()
throws Exception
{
Credentials credentials = new Credentials(); | // Path: solutions/lab4/java/src/lab4/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
// Path: solutions/lab4/java/test/java/lab4/test/TokenRequestTest.java
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab4.TokenRequest;
import lab.Credentials;
package lab4.test;
public class TokenRequestTest
{
final Logger log = LoggerFactory.getLogger(TokenRequestTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testRequest()
throws Exception
{
Credentials credentials = new Credentials(); | TokenRequest request = new TokenRequest(credentials.getClientId(), credentials.getClientSecret()); |
Adobe-Marketing-Cloud/analytics-live-stream-api-samples | solutions/lab2/java/test/java/lab2/test/TokenRequestTest.java | // Path: solutions/lab2/java/src/lab2/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
| import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab2.TokenRequest;
import lab.Credentials; | package lab2.test;
public class TokenRequestTest
{
final Logger log = LoggerFactory.getLogger(TokenRequestTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testRequest()
throws Exception
{
Credentials credentials = new Credentials(); | // Path: solutions/lab2/java/src/lab2/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
// Path: solutions/lab2/java/test/java/lab2/test/TokenRequestTest.java
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab2.TokenRequest;
import lab.Credentials;
package lab2.test;
public class TokenRequestTest
{
final Logger log = LoggerFactory.getLogger(TokenRequestTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testRequest()
throws Exception
{
Credentials credentials = new Credentials(); | TokenRequest request = new TokenRequest(credentials.getClientId(), credentials.getClientSecret()); |
Adobe-Marketing-Cloud/analytics-live-stream-api-samples | solutions/lab1/java/test/java/lab1/test/TokenRequestTest.java | // Path: solutions/lab1/java/src/lab1/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
| import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab.Credentials;
import lab1.TokenRequest; | package lab1.test;
public class TokenRequestTest
{
final Logger log = LoggerFactory.getLogger(TokenRequestTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testRequest()
throws Exception
{
Credentials credentials = new Credentials(); | // Path: solutions/lab1/java/src/lab1/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
// Path: solutions/lab1/java/test/java/lab1/test/TokenRequestTest.java
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab.Credentials;
import lab1.TokenRequest;
package lab1.test;
public class TokenRequestTest
{
final Logger log = LoggerFactory.getLogger(TokenRequestTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testRequest()
throws Exception
{
Credentials credentials = new Credentials(); | TokenRequest request = new TokenRequest(credentials.getClientId(), credentials.getClientSecret()); |
Adobe-Marketing-Cloud/analytics-live-stream-api-samples | solutions/lab3/java/test/java/lab3/test/TokenRequestTest.java | // Path: solutions/lab3/java/src/lab3/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
| import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab3.TokenRequest;
import lab.Credentials; | package lab3.test;
public class TokenRequestTest
{
final Logger log = LoggerFactory.getLogger(TokenRequestTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testRequest()
throws Exception
{
Credentials credentials = new Credentials(); | // Path: solutions/lab3/java/src/lab3/TokenRequest.java
// public class TokenRequest {
//
// public static final Logger log = LoggerFactory.getLogger(TokenRequest.class);
//
// protected String clientId;
// protected String clientSecret;
//
// public TokenRequest(String clientId, String clientSecret)
// {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// public String request() throws IOException {
// log.debug("initiating request for token");
// Credentials credentials = new Credentials();
// URL url = new URL(credentials.getTokenServerUrl());
// String postData = "grant_type=client_credentials";
// String basicAuth = this.clientId + ":" + this.clientSecret;
// HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
// connection.setReadTimeout(10000);
// connection.setConnectTimeout(10000);
// connection.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(basicAuth.getBytes()));
// connection.setRequestMethod("POST");
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setDoOutput(true);
// connection.getOutputStream().write(postData.getBytes());
//
// log.debug("HTTP response code "+connection.getResponseCode());
//
// if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// StringBuffer response = new StringBuffer();
// BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// String line;
// while ((line = reader.readLine()) != null) {
// if (line.length() > 0) {
// response.append(line);
// }
// }
// if (connection != null) {
// connection.disconnect();
// }
// return response.toString();
// }
//
// if (connection != null) {
// connection.disconnect();
// }
// throw new IOException("unexpected response from " + credentials.getTokenServerUrl() + ":" + connection.getResponseCode() + ":" + connection.getResponseMessage());
// }
//
// public String parseResponse(String response) throws IOException {
// ObjectMapper mapper = new ObjectMapper();
// Map<String, Object> jsonModel = mapper.readValue(response, Map.class);
// String accessToken = (String)jsonModel.get("access_token");
// if (accessToken == null) {
// throw new IOException("access_token field not found in response body");
// }
// log.debug("access token: "+accessToken);
// return accessToken;
// }
// }
// Path: solutions/lab3/java/test/java/lab3/test/TokenRequestTest.java
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lab3.TokenRequest;
import lab.Credentials;
package lab3.test;
public class TokenRequestTest
{
final Logger log = LoggerFactory.getLogger(TokenRequestTest.class);
@BeforeClass
public static void setUp()
throws Exception
{
}
@AfterClass
public static void tearDown()
throws Exception
{
}
@Test
public void testRequest()
throws Exception
{
Credentials credentials = new Credentials(); | TokenRequest request = new TokenRequest(credentials.getClientId(), credentials.getClientSecret()); |
eczarny/ada | src/main/java/com/divisiblebyzero/network/Message.java | // Path: src/main/java/com/divisiblebyzero/chess/Move.java
// public class Move implements Serializable {
// private static final long serialVersionUID = 8308554798560064235L;
//
// private Position x, y;
// private long score;
//
// public Move() {
// this.x = new Position();
// this.y = new Position();
//
// this.score = 0;
// }
//
// public Move(Position x, Position y) {
// this.x = x;
// this.y = y;
// }
//
// public Move(byte bytes[]) {
// this.x = new Position((int)bytes[0], (int)bytes[1]);
// this.y = new Position((int)bytes[2], (int)bytes[3]);
// }
//
// public Position getX() {
// return this.x;
// }
//
// public void setX(Position x) {
// this.x = x;
// }
//
// public Position getY() {
// return this.y;
// }
//
// public void setY(Position y) {
// this.y = y;
// }
//
// public long getScore() {
// return this.score;
// }
//
// public void setScore(long score) {
// this.score = score;
// }
//
// public String toString() {
// return this.x + " to " + this.y + " (" + this.score + ")";
// }
// }
| import java.io.Serializable;
import com.divisiblebyzero.chess.Move; | package com.divisiblebyzero.network;
public class Message implements Serializable {
private static final long serialVersionUID = 25177896777329389L;
| // Path: src/main/java/com/divisiblebyzero/chess/Move.java
// public class Move implements Serializable {
// private static final long serialVersionUID = 8308554798560064235L;
//
// private Position x, y;
// private long score;
//
// public Move() {
// this.x = new Position();
// this.y = new Position();
//
// this.score = 0;
// }
//
// public Move(Position x, Position y) {
// this.x = x;
// this.y = y;
// }
//
// public Move(byte bytes[]) {
// this.x = new Position((int)bytes[0], (int)bytes[1]);
// this.y = new Position((int)bytes[2], (int)bytes[3]);
// }
//
// public Position getX() {
// return this.x;
// }
//
// public void setX(Position x) {
// this.x = x;
// }
//
// public Position getY() {
// return this.y;
// }
//
// public void setY(Position y) {
// this.y = y;
// }
//
// public long getScore() {
// return this.score;
// }
//
// public void setScore(long score) {
// this.score = score;
// }
//
// public String toString() {
// return this.x + " to " + this.y + " (" + this.score + ")";
// }
// }
// Path: src/main/java/com/divisiblebyzero/network/Message.java
import java.io.Serializable;
import com.divisiblebyzero.chess.Move;
package com.divisiblebyzero.network;
public class Message implements Serializable {
private static final long serialVersionUID = 25177896777329389L;
| private Move move; |
eczarny/ada | src/main/java/com/divisiblebyzero/chess/Piece.java | // Path: src/main/java/com/divisiblebyzero/utilities/ResourceUtility.java
// public class ResourceUtility {
// private static Logger logger = Logger.getLogger(ResourceUtility.class);
//
// public static Image getImage(String filename) throws IOException {
// return ImageIO.read(ResourceUtility.class.getResource(filename));
// }
//
// public static void playAudioFile(String filename) {
// try {
// ResourceUtility.getClip(filename).start();
// } catch (LineUnavailableException e) {
// logger.error("The specified audio resource is already in use: " + filename, e);
// } catch (UnsupportedAudioFileException e) {
// logger.error("The specified audio resource is unsupported: " + filename, e);
// } catch (IOException e) {
// logger.error("The specified audio resource does not exist or cannot be opened: " + filename, e);
// }
// }
//
// private static Clip getClip(String filename) throws LineUnavailableException, UnsupportedAudioFileException, IOException {
// ResourceUtility resourceUtility = new ResourceUtility();
// Clip clip = AudioSystem.getClip();
//
// clip.open(AudioSystem.getAudioInputStream(resourceUtility.getResourceURL(filename)));
//
// return clip;
// }
//
// private URL getResourceURL(String resource) {
// return getClass().getClassLoader().getResource(resource);
// }
// }
| import java.awt.Image;
import java.io.IOException;
import java.io.Serializable;
import org.apache.log4j.Logger;
import com.divisiblebyzero.utilities.ResourceUtility; | package com.divisiblebyzero.chess;
public class Piece implements Serializable {
private static final long serialVersionUID = -890551245339740761L;
private transient Image image;
private Position position;
private int color;
private int type;
/* Constants for piece resources. */
private static final String EXTENSION = ".png";
private static final String PATH = "/images/pieces/";
private static final String STYLE = "alpha";
/* Possible piece types. */
public static class Type {
public static final int KING = 0;
public static final int QUEEN = 1;
public static final int ROOK = 2;
public static final int BISHOP = 3;
public static final int KNIGHT = 4;
public static final int PAWN = 5;
}
/* Possible piece colors. */
public static class Color {
public static final int BLACK = 0;
public static final int WHITE = 1;
}
private static Logger logger = Logger.getLogger(Piece.class);
public Piece() {
this.position = null;
this.color = -1;
this.type = -1;
}
public Piece(Position position) {
this.position = position;
this.color = -1;
this.type = -1;
}
public Piece(int color, int type) {
this.position = null;
this.color = color;
this.type = type;
}
public Position getPosition() {
return this.position;
}
public void setPosition(Position position) {
this.position = position;
}
public int getColor() {
return this.color;
}
public void setColor(int color) {
this.color = color;
}
public int getType() {
return this.type;
}
public void setType(int type) {
this.type = type;
}
public Image getImage() {
if (this.image == null) {
try {
this.image = this.getImage(STYLE, this.getIdentifier());
} catch (IOException e) {
logger.error("Unable to load artwork from location: " + this.getImagePath(STYLE, this.getIdentifier()), e);
}
}
return this.image;
}
public String toString() {
String result = "Piece (Color: ";
if (this.color == Piece.Color.WHITE) {
result = result + "White";
} else {
result = result + "Black";
}
result = result + ", Type: ";
switch(this.type) {
case Piece.Type.KING:
result = result + "King";
break;
case Piece.Type.QUEEN:
result = result + "Queen";
break;
case Piece.Type.ROOK:
result = result + "Rook";
break;
case Piece.Type.BISHOP:
result = result + "Bishop";
break;
case Piece.Type.KNIGHT:
result = result + "Knight";
break;
case Piece.Type.PAWN:
result = result + "Pawn";
break;
default:
result = result + "Unknown";
break;
}
result = result + ", Position: " + this.position + ")";
return result;
}
private String getIdentifier() {
return (String.valueOf((char)(66 + ((this.color * 20) + (this.color * 1)))) + String.valueOf(this.type));
}
private Image getImage(String style, String identifier) throws IOException { | // Path: src/main/java/com/divisiblebyzero/utilities/ResourceUtility.java
// public class ResourceUtility {
// private static Logger logger = Logger.getLogger(ResourceUtility.class);
//
// public static Image getImage(String filename) throws IOException {
// return ImageIO.read(ResourceUtility.class.getResource(filename));
// }
//
// public static void playAudioFile(String filename) {
// try {
// ResourceUtility.getClip(filename).start();
// } catch (LineUnavailableException e) {
// logger.error("The specified audio resource is already in use: " + filename, e);
// } catch (UnsupportedAudioFileException e) {
// logger.error("The specified audio resource is unsupported: " + filename, e);
// } catch (IOException e) {
// logger.error("The specified audio resource does not exist or cannot be opened: " + filename, e);
// }
// }
//
// private static Clip getClip(String filename) throws LineUnavailableException, UnsupportedAudioFileException, IOException {
// ResourceUtility resourceUtility = new ResourceUtility();
// Clip clip = AudioSystem.getClip();
//
// clip.open(AudioSystem.getAudioInputStream(resourceUtility.getResourceURL(filename)));
//
// return clip;
// }
//
// private URL getResourceURL(String resource) {
// return getClass().getClassLoader().getResource(resource);
// }
// }
// Path: src/main/java/com/divisiblebyzero/chess/Piece.java
import java.awt.Image;
import java.io.IOException;
import java.io.Serializable;
import org.apache.log4j.Logger;
import com.divisiblebyzero.utilities.ResourceUtility;
package com.divisiblebyzero.chess;
public class Piece implements Serializable {
private static final long serialVersionUID = -890551245339740761L;
private transient Image image;
private Position position;
private int color;
private int type;
/* Constants for piece resources. */
private static final String EXTENSION = ".png";
private static final String PATH = "/images/pieces/";
private static final String STYLE = "alpha";
/* Possible piece types. */
public static class Type {
public static final int KING = 0;
public static final int QUEEN = 1;
public static final int ROOK = 2;
public static final int BISHOP = 3;
public static final int KNIGHT = 4;
public static final int PAWN = 5;
}
/* Possible piece colors. */
public static class Color {
public static final int BLACK = 0;
public static final int WHITE = 1;
}
private static Logger logger = Logger.getLogger(Piece.class);
public Piece() {
this.position = null;
this.color = -1;
this.type = -1;
}
public Piece(Position position) {
this.position = position;
this.color = -1;
this.type = -1;
}
public Piece(int color, int type) {
this.position = null;
this.color = color;
this.type = type;
}
public Position getPosition() {
return this.position;
}
public void setPosition(Position position) {
this.position = position;
}
public int getColor() {
return this.color;
}
public void setColor(int color) {
this.color = color;
}
public int getType() {
return this.type;
}
public void setType(int type) {
this.type = type;
}
public Image getImage() {
if (this.image == null) {
try {
this.image = this.getImage(STYLE, this.getIdentifier());
} catch (IOException e) {
logger.error("Unable to load artwork from location: " + this.getImagePath(STYLE, this.getIdentifier()), e);
}
}
return this.image;
}
public String toString() {
String result = "Piece (Color: ";
if (this.color == Piece.Color.WHITE) {
result = result + "White";
} else {
result = result + "Black";
}
result = result + ", Type: ";
switch(this.type) {
case Piece.Type.KING:
result = result + "King";
break;
case Piece.Type.QUEEN:
result = result + "Queen";
break;
case Piece.Type.ROOK:
result = result + "Rook";
break;
case Piece.Type.BISHOP:
result = result + "Bishop";
break;
case Piece.Type.KNIGHT:
result = result + "Knight";
break;
case Piece.Type.PAWN:
result = result + "Pawn";
break;
default:
result = result + "Unknown";
break;
}
result = result + ", Position: " + this.position + ")";
return result;
}
private String getIdentifier() {
return (String.valueOf((char)(66 + ((this.color * 20) + (this.color * 1)))) + String.valueOf(this.type));
}
private Image getImage(String style, String identifier) throws IOException { | return ResourceUtility.getImage(this.getImagePath(style, identifier)); |
jaquadro/ForgeMods | ExtraButtons/src/com/jaquadro/minecraft/extrabuttons/client/ClientProxy.java | // Path: ExtraButtons/src/com/jaquadro/minecraft/extrabuttons/CommonProxy.java
// public class CommonProxy
// {
// public void registerRenderers ()
// { }
// }
//
// Path: ExtraButtons/src/com/jaquadro/minecraft/extrabuttons/client/renderer/DelayButtonRenderer.java
// @SideOnly(Side.CLIENT)
// public class DelayButtonRenderer implements ISimpleBlockRenderingHandler
// {
// @Override
// public void renderInventoryBlock (Block block, int metadata, int modelID, RenderBlocks renderer)
// {
// DelayButton dbBlock = (DelayButton)block;
// if (dbBlock == null)
// return;
//
// GL11.glPushMatrix();
// GL11.glScalef(1.5f, 1.5f, 1.5f);
// GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F);
// GL11.glTranslatef(-.5f, -0.5625f, -.0625f);
//
// dbBlock.setBlockForPanelRender(DelayButton.defaultTileEntity);
// renderer.setRenderBoundsFromBlock(block);
// renderStandaloneBlock(renderer, block);
//
// dbBlock.setBlockForButtonRender(DelayButton.defaultTileEntity);
// renderer.setRenderBoundsFromBlock(block);
// renderStandaloneBlock(renderer, block);
//
// GL11.glPopMatrix();
// }
//
// @Override
// public boolean renderWorldBlock (IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer)
// {
// DelayButton dbBlock = (DelayButton)block;
// if (dbBlock == null)
// return false;
//
// TileEntity te = world.getTileEntity(x, y, z);
//
// dbBlock.setBlockForPanelRender(te);
// renderer.setRenderBoundsFromBlock(dbBlock);
// renderer.renderStandardBlock(block, x, y, z);
//
// dbBlock.setBlockForButtonRender(te);
// renderer.setRenderBoundsFromBlock(block);
// renderer.renderStandardBlock(block, x, y, z);
//
// return true;
// }
//
// @Override
// public boolean shouldRender3DInInventory (int modelId)
// {
// return true;
// }
//
// @Override
// public int getRenderId ()
// {
// return ClientProxy.delayButtonRenderID;
// }
//
// private void renderStandaloneBlock (RenderBlocks renderBlocks, Block block)
// {
// renderStandaloneBlock(renderBlocks, block, 1f, 1f, 1f);
// }
//
// private void renderStandaloneBlock (RenderBlocks renderBlocks, Block block, float r, float g, float b)
// {
// Tessellator tessellator = Tessellator.instance;
//
// tessellator.startDrawingQuads();
// tessellator.setColorOpaque_F(.5f * r, .5f * g, .5f * b);
// tessellator.setNormal(0f, -1f, 0f);
// renderBlocks.renderFaceYNeg(block, 0, 0, 0, block.getBlockTextureFromSide(0));
// tessellator.draw();
//
// tessellator.startDrawingQuads();
// tessellator.setColorOpaque_F(1f * r, 1f * g, 1f * b);
// tessellator.setNormal(0f, 1f, 0f);
// renderBlocks.renderFaceYPos(block, 0, 0, 0, block.getBlockTextureFromSide(1));
// tessellator.draw();
//
// tessellator.startDrawingQuads();
// tessellator.setColorOpaque_F(.8f * r, .8f * g, .8f * b);
// tessellator.setNormal(0f, 0f, -1f);
// renderBlocks.renderFaceZNeg(block, 0, 0, 0, block.getBlockTextureFromSide(2));
// tessellator.draw();
//
// tessellator.startDrawingQuads();
// tessellator.setColorOpaque_F(.8f * r, .8f * g, .8f * b);
// tessellator.setNormal(0f, 0f, 1f);
// renderBlocks.renderFaceZPos(block, 0, 0, 0, block.getBlockTextureFromSide(3));
// tessellator.draw();
//
// tessellator.startDrawingQuads();
// tessellator.setColorOpaque_F(.6f * r, .6f * g, .6f * b);
// tessellator.setNormal(-1f, 0f, 0f);
// renderBlocks.renderFaceXNeg(block, 0, 0, 0, block.getBlockTextureFromSide(4));
// tessellator.draw();
//
// tessellator.startDrawingQuads();
// tessellator.setColorOpaque_F(.6f * r, .6f * g, .6f * b);
// tessellator.setNormal(1f, 0f, 0f);
// renderBlocks.renderFaceXPos(block, 0, 0, 0, block.getBlockTextureFromSide(5));
// tessellator.draw();
// }
// }
| import com.jaquadro.minecraft.extrabuttons.CommonProxy;
import com.jaquadro.minecraft.extrabuttons.client.renderer.DelayButtonRenderer;
import cpw.mods.fml.client.registry.RenderingRegistry; | package com.jaquadro.minecraft.extrabuttons.client;
public class ClientProxy extends CommonProxy
{
public static int delayButtonRenderID;
@Override
public void registerRenderers ()
{
delayButtonRenderID = RenderingRegistry.getNextAvailableRenderId();
| // Path: ExtraButtons/src/com/jaquadro/minecraft/extrabuttons/CommonProxy.java
// public class CommonProxy
// {
// public void registerRenderers ()
// { }
// }
//
// Path: ExtraButtons/src/com/jaquadro/minecraft/extrabuttons/client/renderer/DelayButtonRenderer.java
// @SideOnly(Side.CLIENT)
// public class DelayButtonRenderer implements ISimpleBlockRenderingHandler
// {
// @Override
// public void renderInventoryBlock (Block block, int metadata, int modelID, RenderBlocks renderer)
// {
// DelayButton dbBlock = (DelayButton)block;
// if (dbBlock == null)
// return;
//
// GL11.glPushMatrix();
// GL11.glScalef(1.5f, 1.5f, 1.5f);
// GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F);
// GL11.glTranslatef(-.5f, -0.5625f, -.0625f);
//
// dbBlock.setBlockForPanelRender(DelayButton.defaultTileEntity);
// renderer.setRenderBoundsFromBlock(block);
// renderStandaloneBlock(renderer, block);
//
// dbBlock.setBlockForButtonRender(DelayButton.defaultTileEntity);
// renderer.setRenderBoundsFromBlock(block);
// renderStandaloneBlock(renderer, block);
//
// GL11.glPopMatrix();
// }
//
// @Override
// public boolean renderWorldBlock (IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer)
// {
// DelayButton dbBlock = (DelayButton)block;
// if (dbBlock == null)
// return false;
//
// TileEntity te = world.getTileEntity(x, y, z);
//
// dbBlock.setBlockForPanelRender(te);
// renderer.setRenderBoundsFromBlock(dbBlock);
// renderer.renderStandardBlock(block, x, y, z);
//
// dbBlock.setBlockForButtonRender(te);
// renderer.setRenderBoundsFromBlock(block);
// renderer.renderStandardBlock(block, x, y, z);
//
// return true;
// }
//
// @Override
// public boolean shouldRender3DInInventory (int modelId)
// {
// return true;
// }
//
// @Override
// public int getRenderId ()
// {
// return ClientProxy.delayButtonRenderID;
// }
//
// private void renderStandaloneBlock (RenderBlocks renderBlocks, Block block)
// {
// renderStandaloneBlock(renderBlocks, block, 1f, 1f, 1f);
// }
//
// private void renderStandaloneBlock (RenderBlocks renderBlocks, Block block, float r, float g, float b)
// {
// Tessellator tessellator = Tessellator.instance;
//
// tessellator.startDrawingQuads();
// tessellator.setColorOpaque_F(.5f * r, .5f * g, .5f * b);
// tessellator.setNormal(0f, -1f, 0f);
// renderBlocks.renderFaceYNeg(block, 0, 0, 0, block.getBlockTextureFromSide(0));
// tessellator.draw();
//
// tessellator.startDrawingQuads();
// tessellator.setColorOpaque_F(1f * r, 1f * g, 1f * b);
// tessellator.setNormal(0f, 1f, 0f);
// renderBlocks.renderFaceYPos(block, 0, 0, 0, block.getBlockTextureFromSide(1));
// tessellator.draw();
//
// tessellator.startDrawingQuads();
// tessellator.setColorOpaque_F(.8f * r, .8f * g, .8f * b);
// tessellator.setNormal(0f, 0f, -1f);
// renderBlocks.renderFaceZNeg(block, 0, 0, 0, block.getBlockTextureFromSide(2));
// tessellator.draw();
//
// tessellator.startDrawingQuads();
// tessellator.setColorOpaque_F(.8f * r, .8f * g, .8f * b);
// tessellator.setNormal(0f, 0f, 1f);
// renderBlocks.renderFaceZPos(block, 0, 0, 0, block.getBlockTextureFromSide(3));
// tessellator.draw();
//
// tessellator.startDrawingQuads();
// tessellator.setColorOpaque_F(.6f * r, .6f * g, .6f * b);
// tessellator.setNormal(-1f, 0f, 0f);
// renderBlocks.renderFaceXNeg(block, 0, 0, 0, block.getBlockTextureFromSide(4));
// tessellator.draw();
//
// tessellator.startDrawingQuads();
// tessellator.setColorOpaque_F(.6f * r, .6f * g, .6f * b);
// tessellator.setNormal(1f, 0f, 0f);
// renderBlocks.renderFaceXPos(block, 0, 0, 0, block.getBlockTextureFromSide(5));
// tessellator.draw();
// }
// }
// Path: ExtraButtons/src/com/jaquadro/minecraft/extrabuttons/client/ClientProxy.java
import com.jaquadro.minecraft.extrabuttons.CommonProxy;
import com.jaquadro.minecraft.extrabuttons.client.renderer.DelayButtonRenderer;
import cpw.mods.fml.client.registry.RenderingRegistry;
package com.jaquadro.minecraft.extrabuttons.client;
public class ClientProxy extends CommonProxy
{
public static int delayButtonRenderID;
@Override
public void registerRenderers ()
{
delayButtonRenderID = RenderingRegistry.getNextAvailableRenderId();
| RenderingRegistry.registerBlockHandler(delayButtonRenderID, new DelayButtonRenderer()); |
jaquadro/ForgeMods | HungerStrike/src/com/jaquadro/minecraft/hungerstrike/proxy/ClientProxy.java | // Path: HungerStrike/src/com/jaquadro/minecraft/hungerstrike/proxy/CommonProxy.java
// public class CommonProxy
// {
// public PlayerHandler playerHandler;
//
// public CommonProxy () {
// playerHandler = new PlayerHandler();
// }
//
// @SubscribeEvent
// public void tick (TickEvent.PlayerTickEvent event) {
// playerHandler.tick(event.player, event.phase, event.side);
// }
//
// @SubscribeEvent
// public void entityConstructing (EntityEvent.EntityConstructing event) {
// if (event.entity instanceof EntityPlayer && ExtendedPlayer.get((EntityPlayer) event.entity) == null)
// ExtendedPlayer.register((EntityPlayer) event.entity);
// }
//
// @SubscribeEvent
// public void livingDeath (LivingDeathEvent event) {
// if (!event.entity.worldObj.isRemote && event.entity instanceof EntityPlayerMP)
// playerHandler.storeData((EntityPlayer) event.entity);
// }
//
// @SubscribeEvent
// public void entityJoinWorld (EntityJoinWorldEvent event) {
// if (!event.entity.worldObj.isRemote && event.entity instanceof EntityPlayerMP) {
// playerHandler.restoreData((EntityPlayer) event.entity);
// HungerStrike.packetPipeline.sendTo(new SyncExtendedPlayerPacket((EntityPlayer) event.entity), (EntityPlayerMP) event.entity);
// HungerStrike.packetPipeline.sendTo(new SyncConfigPacket(), (EntityPlayerMP) event.entity);
// }
// }
// }
//
// Path: HungerStrike/src/com/jaquadro/minecraft/hungerstrike/HungerStrike.java
// @Mod(modid = HungerStrike.MOD_ID, name = HungerStrike.MOD_NAME, version = HungerStrike.MOD_VERSION)
// public class HungerStrike
// {
// public static final String MOD_ID = "hungerstrike";
// static final String MOD_NAME = "Hunger Strike";
// static final String MOD_VERSION = "1.7.10.4";
// static final String SOURCE_PATH = "com.jaquadro.minecraft.hungerstrike.";
//
// @Mod.Instance(MOD_ID)
// public static HungerStrike instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "proxy.ClientProxy", serverSide = SOURCE_PATH + "proxy.CommonProxy")
// public static CommonProxy proxy;
//
// public static final PacketPipeline packetPipeline = new PacketPipeline();
//
// public static ConfigManager config = new ConfigManager();
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// FMLCommonHandler.instance().bus().register(proxy);
//
// config.setup(event.getSuggestedConfigurationFile());
// }
//
// @Mod.EventHandler
// public void load (FMLInitializationEvent event) {
// MinecraftForge.EVENT_BUS.register(proxy);
//
// packetPipeline.initialise();
// packetPipeline.registerPacket(SyncExtendedPlayerPacket.class);
// packetPipeline.registerPacket(SyncConfigPacket.class);
// }
//
// @Mod.EventHandler
// public void postInit (FMLPostInitializationEvent event) {
// packetPipeline.postInitialise();
//
// if (config.getFoodStackSize() > -1) {
// for (Object obj : GameData.itemRegistry) {
// Item item = (Item) obj;
// if (item instanceof ItemFood)
// item.setMaxStackSize(config.getFoodStackSize());
// }
// }
// }
//
// @Mod.EventHandler
// public void serverStarted (FMLServerStartedEvent event) {
// CommandHandler handler = (CommandHandler) MinecraftServer.getServer().getCommandManager();
// handler.registerCommand(new CommandHungerStrike());
// }
//
//
// }
| import com.jaquadro.minecraft.hungerstrike.proxy.CommonProxy;
import com.jaquadro.minecraft.hungerstrike.HungerStrike;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.client.Minecraft;
import net.minecraftforge.client.event.RenderGameOverlayEvent; | package com.jaquadro.minecraft.hungerstrike.proxy;
public class ClientProxy extends CommonProxy {
@SubscribeEvent
public void renderGameOverlay (RenderGameOverlayEvent event) {
if (event.type == RenderGameOverlayEvent.ElementType.FOOD) { | // Path: HungerStrike/src/com/jaquadro/minecraft/hungerstrike/proxy/CommonProxy.java
// public class CommonProxy
// {
// public PlayerHandler playerHandler;
//
// public CommonProxy () {
// playerHandler = new PlayerHandler();
// }
//
// @SubscribeEvent
// public void tick (TickEvent.PlayerTickEvent event) {
// playerHandler.tick(event.player, event.phase, event.side);
// }
//
// @SubscribeEvent
// public void entityConstructing (EntityEvent.EntityConstructing event) {
// if (event.entity instanceof EntityPlayer && ExtendedPlayer.get((EntityPlayer) event.entity) == null)
// ExtendedPlayer.register((EntityPlayer) event.entity);
// }
//
// @SubscribeEvent
// public void livingDeath (LivingDeathEvent event) {
// if (!event.entity.worldObj.isRemote && event.entity instanceof EntityPlayerMP)
// playerHandler.storeData((EntityPlayer) event.entity);
// }
//
// @SubscribeEvent
// public void entityJoinWorld (EntityJoinWorldEvent event) {
// if (!event.entity.worldObj.isRemote && event.entity instanceof EntityPlayerMP) {
// playerHandler.restoreData((EntityPlayer) event.entity);
// HungerStrike.packetPipeline.sendTo(new SyncExtendedPlayerPacket((EntityPlayer) event.entity), (EntityPlayerMP) event.entity);
// HungerStrike.packetPipeline.sendTo(new SyncConfigPacket(), (EntityPlayerMP) event.entity);
// }
// }
// }
//
// Path: HungerStrike/src/com/jaquadro/minecraft/hungerstrike/HungerStrike.java
// @Mod(modid = HungerStrike.MOD_ID, name = HungerStrike.MOD_NAME, version = HungerStrike.MOD_VERSION)
// public class HungerStrike
// {
// public static final String MOD_ID = "hungerstrike";
// static final String MOD_NAME = "Hunger Strike";
// static final String MOD_VERSION = "1.7.10.4";
// static final String SOURCE_PATH = "com.jaquadro.minecraft.hungerstrike.";
//
// @Mod.Instance(MOD_ID)
// public static HungerStrike instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "proxy.ClientProxy", serverSide = SOURCE_PATH + "proxy.CommonProxy")
// public static CommonProxy proxy;
//
// public static final PacketPipeline packetPipeline = new PacketPipeline();
//
// public static ConfigManager config = new ConfigManager();
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// FMLCommonHandler.instance().bus().register(proxy);
//
// config.setup(event.getSuggestedConfigurationFile());
// }
//
// @Mod.EventHandler
// public void load (FMLInitializationEvent event) {
// MinecraftForge.EVENT_BUS.register(proxy);
//
// packetPipeline.initialise();
// packetPipeline.registerPacket(SyncExtendedPlayerPacket.class);
// packetPipeline.registerPacket(SyncConfigPacket.class);
// }
//
// @Mod.EventHandler
// public void postInit (FMLPostInitializationEvent event) {
// packetPipeline.postInitialise();
//
// if (config.getFoodStackSize() > -1) {
// for (Object obj : GameData.itemRegistry) {
// Item item = (Item) obj;
// if (item instanceof ItemFood)
// item.setMaxStackSize(config.getFoodStackSize());
// }
// }
// }
//
// @Mod.EventHandler
// public void serverStarted (FMLServerStartedEvent event) {
// CommandHandler handler = (CommandHandler) MinecraftServer.getServer().getCommandManager();
// handler.registerCommand(new CommandHungerStrike());
// }
//
//
// }
// Path: HungerStrike/src/com/jaquadro/minecraft/hungerstrike/proxy/ClientProxy.java
import com.jaquadro.minecraft.hungerstrike.proxy.CommonProxy;
import com.jaquadro.minecraft.hungerstrike.HungerStrike;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.client.Minecraft;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
package com.jaquadro.minecraft.hungerstrike.proxy;
public class ClientProxy extends CommonProxy {
@SubscribeEvent
public void renderGameOverlay (RenderGameOverlayEvent event) {
if (event.type == RenderGameOverlayEvent.ElementType.FOOD) { | if (!HungerStrike.config.isHungerBarHidden()) |
jaquadro/ForgeMods | HungerStrike/src/com/jaquadro/minecraft/hungerstrike/network/SyncConfigPacket.java | // Path: HungerStrike/src/com/jaquadro/minecraft/hungerstrike/ConfigManager.java
// public class ConfigManager
// {
// public enum Mode {
// NONE,
// LIST,
// ALL;
//
// public static Mode fromValueIgnoreCase (String value) {
// if (value.compareToIgnoreCase("NONE") == 0)
// return Mode.NONE;
// else if (value.compareToIgnoreCase("LIST") == 0)
// return Mode.LIST;
// else if (value.compareToIgnoreCase("ALL") == 0)
// return Mode.ALL;
//
// return Mode.LIST;
// }
// }
// private Configuration config;
//
// private Property modeProperty;
//
// private Mode mode = Mode.LIST;
// private double foodHealFactor = .5;
// private int foodStackSize = -1;
// private boolean hideHungerBar = true;
//
// public void setup (File location) {
// config = new Configuration(location);
// config.load();
//
// modeProperty = config.get(Configuration.CATEGORY_GENERAL, "Mode", "ALL");
// modeProperty.comment = "Mode can be set to NONE, LIST, or ALL\n" +
// "- NONE: Hunger Strike is disabled for all players.\n" +
// "- LIST: Hunger Strike is enabled for players added in-game with /hungerstrike command.\n" +
// "- ALL: Hunger Strike is enabled for all players.";
//
// Property foodHealProperty = config.get(Configuration.CATEGORY_GENERAL, "FoodHealFactor", .5f);
// foodHealProperty.comment = "How to translate food points into heart points when consuming food.\n" +
// "At the default value of 0.5, food fills your heart bar at half the rate it would fill hunger.";
//
// Property foodStackSizeProperty = config.get(Configuration.CATEGORY_GENERAL, "MaxFoodStackSize", -1);
// foodStackSizeProperty.comment = "Globally overrides the maximum stack size of food items.\n" +
// "This property affects all Vanilla and Mod food items that derive from ItemFood.\n" +
// "Set to -1 to retain the default stack size of each food item. Note: This will affect the\n" +
// "entire server, not just players on hunger strike.";
//
// Property hideHungerBarProperty = config.get(Configuration.CATEGORY_GENERAL, "HideHungerBar", true);
// hideHungerBarProperty.comment = "Controls whether or not the hunger bar is hidden for players\n" +
// "on hunger strike. If the hunger bar is left visible, it will remain filled at half capacity,\n" +
// "except when certain potion effects are active like hunger and regeneration.";
//
// mode = Mode.fromValueIgnoreCase(modeProperty.getString());
// foodHealFactor = foodHealProperty.getDouble(.5);
// foodStackSize = foodStackSizeProperty.getInt(-1);
// hideHungerBar = hideHungerBarProperty.getBoolean(true);
//
// config.save();
// }
//
// public double getFoodHealFactor () {
// return foodHealFactor;
// }
//
// public int getFoodStackSize () {
// return foodStackSize;
// }
//
// public boolean isHungerBarHidden () {
// return hideHungerBar;
// }
//
// public Mode getMode () {
// return mode;
// }
//
// public void setMode (Mode value) {
// setModeSoft(value);
//
// modeProperty.set(mode.toString());
// config.save();
// }
//
// public void setModeSoft (Mode value) {
// mode = value;
// }
// }
//
// Path: HungerStrike/src/com/jaquadro/minecraft/hungerstrike/HungerStrike.java
// @Mod(modid = HungerStrike.MOD_ID, name = HungerStrike.MOD_NAME, version = HungerStrike.MOD_VERSION)
// public class HungerStrike
// {
// public static final String MOD_ID = "hungerstrike";
// static final String MOD_NAME = "Hunger Strike";
// static final String MOD_VERSION = "1.7.10.4";
// static final String SOURCE_PATH = "com.jaquadro.minecraft.hungerstrike.";
//
// @Mod.Instance(MOD_ID)
// public static HungerStrike instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "proxy.ClientProxy", serverSide = SOURCE_PATH + "proxy.CommonProxy")
// public static CommonProxy proxy;
//
// public static final PacketPipeline packetPipeline = new PacketPipeline();
//
// public static ConfigManager config = new ConfigManager();
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// FMLCommonHandler.instance().bus().register(proxy);
//
// config.setup(event.getSuggestedConfigurationFile());
// }
//
// @Mod.EventHandler
// public void load (FMLInitializationEvent event) {
// MinecraftForge.EVENT_BUS.register(proxy);
//
// packetPipeline.initialise();
// packetPipeline.registerPacket(SyncExtendedPlayerPacket.class);
// packetPipeline.registerPacket(SyncConfigPacket.class);
// }
//
// @Mod.EventHandler
// public void postInit (FMLPostInitializationEvent event) {
// packetPipeline.postInitialise();
//
// if (config.getFoodStackSize() > -1) {
// for (Object obj : GameData.itemRegistry) {
// Item item = (Item) obj;
// if (item instanceof ItemFood)
// item.setMaxStackSize(config.getFoodStackSize());
// }
// }
// }
//
// @Mod.EventHandler
// public void serverStarted (FMLServerStartedEvent event) {
// CommandHandler handler = (CommandHandler) MinecraftServer.getServer().getCommandManager();
// handler.registerCommand(new CommandHungerStrike());
// }
//
//
// }
| import com.jaquadro.minecraft.hungerstrike.ConfigManager;
import com.jaquadro.minecraft.hungerstrike.HungerStrike;
import cpw.mods.fml.common.network.ByteBufUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagString; | package com.jaquadro.minecraft.hungerstrike.network;
public class SyncConfigPacket extends AbstractPacket
{
private NBTTagCompound data;
public SyncConfigPacket () {
data = new NBTTagCompound(); | // Path: HungerStrike/src/com/jaquadro/minecraft/hungerstrike/ConfigManager.java
// public class ConfigManager
// {
// public enum Mode {
// NONE,
// LIST,
// ALL;
//
// public static Mode fromValueIgnoreCase (String value) {
// if (value.compareToIgnoreCase("NONE") == 0)
// return Mode.NONE;
// else if (value.compareToIgnoreCase("LIST") == 0)
// return Mode.LIST;
// else if (value.compareToIgnoreCase("ALL") == 0)
// return Mode.ALL;
//
// return Mode.LIST;
// }
// }
// private Configuration config;
//
// private Property modeProperty;
//
// private Mode mode = Mode.LIST;
// private double foodHealFactor = .5;
// private int foodStackSize = -1;
// private boolean hideHungerBar = true;
//
// public void setup (File location) {
// config = new Configuration(location);
// config.load();
//
// modeProperty = config.get(Configuration.CATEGORY_GENERAL, "Mode", "ALL");
// modeProperty.comment = "Mode can be set to NONE, LIST, or ALL\n" +
// "- NONE: Hunger Strike is disabled for all players.\n" +
// "- LIST: Hunger Strike is enabled for players added in-game with /hungerstrike command.\n" +
// "- ALL: Hunger Strike is enabled for all players.";
//
// Property foodHealProperty = config.get(Configuration.CATEGORY_GENERAL, "FoodHealFactor", .5f);
// foodHealProperty.comment = "How to translate food points into heart points when consuming food.\n" +
// "At the default value of 0.5, food fills your heart bar at half the rate it would fill hunger.";
//
// Property foodStackSizeProperty = config.get(Configuration.CATEGORY_GENERAL, "MaxFoodStackSize", -1);
// foodStackSizeProperty.comment = "Globally overrides the maximum stack size of food items.\n" +
// "This property affects all Vanilla and Mod food items that derive from ItemFood.\n" +
// "Set to -1 to retain the default stack size of each food item. Note: This will affect the\n" +
// "entire server, not just players on hunger strike.";
//
// Property hideHungerBarProperty = config.get(Configuration.CATEGORY_GENERAL, "HideHungerBar", true);
// hideHungerBarProperty.comment = "Controls whether or not the hunger bar is hidden for players\n" +
// "on hunger strike. If the hunger bar is left visible, it will remain filled at half capacity,\n" +
// "except when certain potion effects are active like hunger and regeneration.";
//
// mode = Mode.fromValueIgnoreCase(modeProperty.getString());
// foodHealFactor = foodHealProperty.getDouble(.5);
// foodStackSize = foodStackSizeProperty.getInt(-1);
// hideHungerBar = hideHungerBarProperty.getBoolean(true);
//
// config.save();
// }
//
// public double getFoodHealFactor () {
// return foodHealFactor;
// }
//
// public int getFoodStackSize () {
// return foodStackSize;
// }
//
// public boolean isHungerBarHidden () {
// return hideHungerBar;
// }
//
// public Mode getMode () {
// return mode;
// }
//
// public void setMode (Mode value) {
// setModeSoft(value);
//
// modeProperty.set(mode.toString());
// config.save();
// }
//
// public void setModeSoft (Mode value) {
// mode = value;
// }
// }
//
// Path: HungerStrike/src/com/jaquadro/minecraft/hungerstrike/HungerStrike.java
// @Mod(modid = HungerStrike.MOD_ID, name = HungerStrike.MOD_NAME, version = HungerStrike.MOD_VERSION)
// public class HungerStrike
// {
// public static final String MOD_ID = "hungerstrike";
// static final String MOD_NAME = "Hunger Strike";
// static final String MOD_VERSION = "1.7.10.4";
// static final String SOURCE_PATH = "com.jaquadro.minecraft.hungerstrike.";
//
// @Mod.Instance(MOD_ID)
// public static HungerStrike instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "proxy.ClientProxy", serverSide = SOURCE_PATH + "proxy.CommonProxy")
// public static CommonProxy proxy;
//
// public static final PacketPipeline packetPipeline = new PacketPipeline();
//
// public static ConfigManager config = new ConfigManager();
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// FMLCommonHandler.instance().bus().register(proxy);
//
// config.setup(event.getSuggestedConfigurationFile());
// }
//
// @Mod.EventHandler
// public void load (FMLInitializationEvent event) {
// MinecraftForge.EVENT_BUS.register(proxy);
//
// packetPipeline.initialise();
// packetPipeline.registerPacket(SyncExtendedPlayerPacket.class);
// packetPipeline.registerPacket(SyncConfigPacket.class);
// }
//
// @Mod.EventHandler
// public void postInit (FMLPostInitializationEvent event) {
// packetPipeline.postInitialise();
//
// if (config.getFoodStackSize() > -1) {
// for (Object obj : GameData.itemRegistry) {
// Item item = (Item) obj;
// if (item instanceof ItemFood)
// item.setMaxStackSize(config.getFoodStackSize());
// }
// }
// }
//
// @Mod.EventHandler
// public void serverStarted (FMLServerStartedEvent event) {
// CommandHandler handler = (CommandHandler) MinecraftServer.getServer().getCommandManager();
// handler.registerCommand(new CommandHungerStrike());
// }
//
//
// }
// Path: HungerStrike/src/com/jaquadro/minecraft/hungerstrike/network/SyncConfigPacket.java
import com.jaquadro.minecraft.hungerstrike.ConfigManager;
import com.jaquadro.minecraft.hungerstrike.HungerStrike;
import cpw.mods.fml.common.network.ByteBufUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagString;
package com.jaquadro.minecraft.hungerstrike.network;
public class SyncConfigPacket extends AbstractPacket
{
private NBTTagCompound data;
public SyncConfigPacket () {
data = new NBTTagCompound(); | data.setTag("mode", new NBTTagString(HungerStrike.config.getMode().toString())); |
jaquadro/ForgeMods | ModularPots/src/com/jaquadro/minecraft/modularpots/client/renderer/FlowerLeafRenderer.java | // Path: ModularPots/src/com/jaquadro/minecraft/modularpots/block/BlockFlowerLeaves.java
// public class BlockFlowerLeaves extends BlockOldLeaf
// {
// private IIcon[] flowersTop;
// private IIcon[] flowersTopSide;
// private IIcon[] flowersSide;
//
// public BlockFlowerLeaves (String blockName) {
// setBlockName(blockName);
// setBlockTextureName("leaves");
// }
//
// /*@Override
// public IIcon getIcon (int var1, int var2) {
// return null;
// }*/
//
// @Override
// public boolean renderAsNormalBlock () {
// return false;
// }
//
// @Override
// public boolean isOpaqueCube () {
// return false;
// }
//
// @Override
// public boolean canPlaceBlockOnSide (World p_149707_1_, int p_149707_2_, int p_149707_3_, int p_149707_4_, int p_149707_5_) {
// return true;
// }
//
// @Override
// public boolean shouldSideBeRendered (IBlockAccess p_149646_1_, int p_149646_2_, int p_149646_3_, int p_149646_4_, int p_149646_5_) {
// return true;
// }
//
// @Override
// public int getRenderType () {
// return ClientProxy.flowerLeafRenderID;
// }
//
// @SideOnly(Side.CLIENT)
// public IIcon getFlowerIcon (IBlockAccess world, int x, int y, int z, int meta, int side) {
// boolean clear1 = world.getBlock(x, y + 1, z) != this;
// boolean clear2 = world.getBlock(x, y, z - 1) != this;
// boolean clear3 = world.getBlock(x, y, z + 1) != this;
// boolean clear4 = world.getBlock(x - 1, y, z) != this;
// boolean clear5 = world.getBlock(x + 1, y, z) != this;
//
// if (side == 1 && clear1)
// return flowersTop[meta & 3];
// else if ((side == 2 && clear2) || (side == 3 && clear3) || (side == 4 && clear4) || (side == 5 && clear5))
// return clear1 ? flowersTopSide[meta & 3] : flowersSide[meta & 3];
//
// return null;
// }
//
// /*@Override
// public String[] func_150125_e () {
// return new String[0];
// }*/
//
// @SideOnly(Side.CLIENT)
// @Override
// public void registerBlockIcons (IIconRegister register) {
// super.registerBlockIcons(register);
//
// flowersTop = new IIcon[4];
// flowersTopSide = new IIcon[4];
// flowersSide = new IIcon[4];
//
// for (int i = 0; i < 4; i++) {
// flowersTop[i] = register.registerIcon(ModularPots.MOD_ID + ":leaves_flowers_white");
// flowersTopSide[i] = register.registerIcon(ModularPots.MOD_ID + ":leaves_flowers_white_half");
// flowersSide[i] = register.registerIcon(ModularPots.MOD_ID + ":leaves_flowers_white_sparse");
// }
// }
// }
//
// Path: ModularPots/src/com/jaquadro/minecraft/modularpots/client/ClientProxy.java
// public class ClientProxy extends CommonProxy
// {
// public static int renderPass = 0;
// public static int largePotRenderID;
// public static int transformPlantRenderID;
// public static int thinLogRenderID;
// public static int flowerLeafRenderID;
// public static int thinLogFenceRenderID;
//
// @Override
// public void registerRenderers ()
// {
// largePotRenderID = RenderingRegistry.getNextAvailableRenderId();
// transformPlantRenderID = RenderingRegistry.getNextAvailableRenderId();
// thinLogRenderID = RenderingRegistry.getNextAvailableRenderId();
// flowerLeafRenderID = RenderingRegistry.getNextAvailableRenderId();
// thinLogFenceRenderID = RenderingRegistry.getNextAvailableRenderId();
//
// RenderingRegistry.registerBlockHandler(largePotRenderID, new LargePotRenderer());
// RenderingRegistry.registerBlockHandler(transformPlantRenderID, new TransformPlantRenderer());
// RenderingRegistry.registerBlockHandler(thinLogRenderID, new ThinLogRenderer());
// RenderingRegistry.registerBlockHandler(flowerLeafRenderID, new FlowerLeafRenderer());
// RenderingRegistry.registerBlockHandler(thinLogFenceRenderID, new ThinLogFenceRenderer());
// }
// }
| import com.jaquadro.minecraft.modularpots.block.BlockFlowerLeaves;
import com.jaquadro.minecraft.modularpots.client.ClientProxy;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess; | package com.jaquadro.minecraft.modularpots.client.renderer;
public class FlowerLeafRenderer implements ISimpleBlockRenderingHandler
{
@Override
public void renderInventoryBlock (Block block, int metadata, int modelId, RenderBlocks renderer) {
}
@Override
public boolean renderWorldBlock (IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { | // Path: ModularPots/src/com/jaquadro/minecraft/modularpots/block/BlockFlowerLeaves.java
// public class BlockFlowerLeaves extends BlockOldLeaf
// {
// private IIcon[] flowersTop;
// private IIcon[] flowersTopSide;
// private IIcon[] flowersSide;
//
// public BlockFlowerLeaves (String blockName) {
// setBlockName(blockName);
// setBlockTextureName("leaves");
// }
//
// /*@Override
// public IIcon getIcon (int var1, int var2) {
// return null;
// }*/
//
// @Override
// public boolean renderAsNormalBlock () {
// return false;
// }
//
// @Override
// public boolean isOpaqueCube () {
// return false;
// }
//
// @Override
// public boolean canPlaceBlockOnSide (World p_149707_1_, int p_149707_2_, int p_149707_3_, int p_149707_4_, int p_149707_5_) {
// return true;
// }
//
// @Override
// public boolean shouldSideBeRendered (IBlockAccess p_149646_1_, int p_149646_2_, int p_149646_3_, int p_149646_4_, int p_149646_5_) {
// return true;
// }
//
// @Override
// public int getRenderType () {
// return ClientProxy.flowerLeafRenderID;
// }
//
// @SideOnly(Side.CLIENT)
// public IIcon getFlowerIcon (IBlockAccess world, int x, int y, int z, int meta, int side) {
// boolean clear1 = world.getBlock(x, y + 1, z) != this;
// boolean clear2 = world.getBlock(x, y, z - 1) != this;
// boolean clear3 = world.getBlock(x, y, z + 1) != this;
// boolean clear4 = world.getBlock(x - 1, y, z) != this;
// boolean clear5 = world.getBlock(x + 1, y, z) != this;
//
// if (side == 1 && clear1)
// return flowersTop[meta & 3];
// else if ((side == 2 && clear2) || (side == 3 && clear3) || (side == 4 && clear4) || (side == 5 && clear5))
// return clear1 ? flowersTopSide[meta & 3] : flowersSide[meta & 3];
//
// return null;
// }
//
// /*@Override
// public String[] func_150125_e () {
// return new String[0];
// }*/
//
// @SideOnly(Side.CLIENT)
// @Override
// public void registerBlockIcons (IIconRegister register) {
// super.registerBlockIcons(register);
//
// flowersTop = new IIcon[4];
// flowersTopSide = new IIcon[4];
// flowersSide = new IIcon[4];
//
// for (int i = 0; i < 4; i++) {
// flowersTop[i] = register.registerIcon(ModularPots.MOD_ID + ":leaves_flowers_white");
// flowersTopSide[i] = register.registerIcon(ModularPots.MOD_ID + ":leaves_flowers_white_half");
// flowersSide[i] = register.registerIcon(ModularPots.MOD_ID + ":leaves_flowers_white_sparse");
// }
// }
// }
//
// Path: ModularPots/src/com/jaquadro/minecraft/modularpots/client/ClientProxy.java
// public class ClientProxy extends CommonProxy
// {
// public static int renderPass = 0;
// public static int largePotRenderID;
// public static int transformPlantRenderID;
// public static int thinLogRenderID;
// public static int flowerLeafRenderID;
// public static int thinLogFenceRenderID;
//
// @Override
// public void registerRenderers ()
// {
// largePotRenderID = RenderingRegistry.getNextAvailableRenderId();
// transformPlantRenderID = RenderingRegistry.getNextAvailableRenderId();
// thinLogRenderID = RenderingRegistry.getNextAvailableRenderId();
// flowerLeafRenderID = RenderingRegistry.getNextAvailableRenderId();
// thinLogFenceRenderID = RenderingRegistry.getNextAvailableRenderId();
//
// RenderingRegistry.registerBlockHandler(largePotRenderID, new LargePotRenderer());
// RenderingRegistry.registerBlockHandler(transformPlantRenderID, new TransformPlantRenderer());
// RenderingRegistry.registerBlockHandler(thinLogRenderID, new ThinLogRenderer());
// RenderingRegistry.registerBlockHandler(flowerLeafRenderID, new FlowerLeafRenderer());
// RenderingRegistry.registerBlockHandler(thinLogFenceRenderID, new ThinLogFenceRenderer());
// }
// }
// Path: ModularPots/src/com/jaquadro/minecraft/modularpots/client/renderer/FlowerLeafRenderer.java
import com.jaquadro.minecraft.modularpots.block.BlockFlowerLeaves;
import com.jaquadro.minecraft.modularpots.client.ClientProxy;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
package com.jaquadro.minecraft.modularpots.client.renderer;
public class FlowerLeafRenderer implements ISimpleBlockRenderingHandler
{
@Override
public void renderInventoryBlock (Block block, int metadata, int modelId, RenderBlocks renderer) {
}
@Override
public boolean renderWorldBlock (IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { | if (!(block instanceof BlockFlowerLeaves)) |
jaquadro/ForgeMods | ModularPots/src/com/jaquadro/minecraft/modularpots/client/renderer/FlowerLeafRenderer.java | // Path: ModularPots/src/com/jaquadro/minecraft/modularpots/block/BlockFlowerLeaves.java
// public class BlockFlowerLeaves extends BlockOldLeaf
// {
// private IIcon[] flowersTop;
// private IIcon[] flowersTopSide;
// private IIcon[] flowersSide;
//
// public BlockFlowerLeaves (String blockName) {
// setBlockName(blockName);
// setBlockTextureName("leaves");
// }
//
// /*@Override
// public IIcon getIcon (int var1, int var2) {
// return null;
// }*/
//
// @Override
// public boolean renderAsNormalBlock () {
// return false;
// }
//
// @Override
// public boolean isOpaqueCube () {
// return false;
// }
//
// @Override
// public boolean canPlaceBlockOnSide (World p_149707_1_, int p_149707_2_, int p_149707_3_, int p_149707_4_, int p_149707_5_) {
// return true;
// }
//
// @Override
// public boolean shouldSideBeRendered (IBlockAccess p_149646_1_, int p_149646_2_, int p_149646_3_, int p_149646_4_, int p_149646_5_) {
// return true;
// }
//
// @Override
// public int getRenderType () {
// return ClientProxy.flowerLeafRenderID;
// }
//
// @SideOnly(Side.CLIENT)
// public IIcon getFlowerIcon (IBlockAccess world, int x, int y, int z, int meta, int side) {
// boolean clear1 = world.getBlock(x, y + 1, z) != this;
// boolean clear2 = world.getBlock(x, y, z - 1) != this;
// boolean clear3 = world.getBlock(x, y, z + 1) != this;
// boolean clear4 = world.getBlock(x - 1, y, z) != this;
// boolean clear5 = world.getBlock(x + 1, y, z) != this;
//
// if (side == 1 && clear1)
// return flowersTop[meta & 3];
// else if ((side == 2 && clear2) || (side == 3 && clear3) || (side == 4 && clear4) || (side == 5 && clear5))
// return clear1 ? flowersTopSide[meta & 3] : flowersSide[meta & 3];
//
// return null;
// }
//
// /*@Override
// public String[] func_150125_e () {
// return new String[0];
// }*/
//
// @SideOnly(Side.CLIENT)
// @Override
// public void registerBlockIcons (IIconRegister register) {
// super.registerBlockIcons(register);
//
// flowersTop = new IIcon[4];
// flowersTopSide = new IIcon[4];
// flowersSide = new IIcon[4];
//
// for (int i = 0; i < 4; i++) {
// flowersTop[i] = register.registerIcon(ModularPots.MOD_ID + ":leaves_flowers_white");
// flowersTopSide[i] = register.registerIcon(ModularPots.MOD_ID + ":leaves_flowers_white_half");
// flowersSide[i] = register.registerIcon(ModularPots.MOD_ID + ":leaves_flowers_white_sparse");
// }
// }
// }
//
// Path: ModularPots/src/com/jaquadro/minecraft/modularpots/client/ClientProxy.java
// public class ClientProxy extends CommonProxy
// {
// public static int renderPass = 0;
// public static int largePotRenderID;
// public static int transformPlantRenderID;
// public static int thinLogRenderID;
// public static int flowerLeafRenderID;
// public static int thinLogFenceRenderID;
//
// @Override
// public void registerRenderers ()
// {
// largePotRenderID = RenderingRegistry.getNextAvailableRenderId();
// transformPlantRenderID = RenderingRegistry.getNextAvailableRenderId();
// thinLogRenderID = RenderingRegistry.getNextAvailableRenderId();
// flowerLeafRenderID = RenderingRegistry.getNextAvailableRenderId();
// thinLogFenceRenderID = RenderingRegistry.getNextAvailableRenderId();
//
// RenderingRegistry.registerBlockHandler(largePotRenderID, new LargePotRenderer());
// RenderingRegistry.registerBlockHandler(transformPlantRenderID, new TransformPlantRenderer());
// RenderingRegistry.registerBlockHandler(thinLogRenderID, new ThinLogRenderer());
// RenderingRegistry.registerBlockHandler(flowerLeafRenderID, new FlowerLeafRenderer());
// RenderingRegistry.registerBlockHandler(thinLogFenceRenderID, new ThinLogFenceRenderer());
// }
// }
| import com.jaquadro.minecraft.modularpots.block.BlockFlowerLeaves;
import com.jaquadro.minecraft.modularpots.client.ClientProxy;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess; | IIcon icon = block.getFlowerIcon(world, x, y, z, meta, 1);
if (icon != null)
renderer.renderFaceYPos(block, x, y + offset, z, icon);
icon = block.getFlowerIcon(world, x, y, z, meta, 2);
if (icon != null)
renderer.renderFaceZNeg(block, x, y, z - offset, icon);
icon = block.getFlowerIcon(world, x, y, z, meta, 3);
if (icon != null)
renderer.renderFaceZPos(block, x, y, z + offset, icon);
icon = block.getFlowerIcon(world, x, y, z, meta, 4);
if (icon != null)
renderer.renderFaceXNeg(block, x - offset, y, z, icon);
icon = block.getFlowerIcon(world, x, y, z, meta, 5);
if (icon != null)
renderer.renderFaceXPos(block, x + offset, y, z, icon);
return true;
}
@Override
public boolean shouldRender3DInInventory (int modelId) {
return true;
}
@Override
public int getRenderId () { | // Path: ModularPots/src/com/jaquadro/minecraft/modularpots/block/BlockFlowerLeaves.java
// public class BlockFlowerLeaves extends BlockOldLeaf
// {
// private IIcon[] flowersTop;
// private IIcon[] flowersTopSide;
// private IIcon[] flowersSide;
//
// public BlockFlowerLeaves (String blockName) {
// setBlockName(blockName);
// setBlockTextureName("leaves");
// }
//
// /*@Override
// public IIcon getIcon (int var1, int var2) {
// return null;
// }*/
//
// @Override
// public boolean renderAsNormalBlock () {
// return false;
// }
//
// @Override
// public boolean isOpaqueCube () {
// return false;
// }
//
// @Override
// public boolean canPlaceBlockOnSide (World p_149707_1_, int p_149707_2_, int p_149707_3_, int p_149707_4_, int p_149707_5_) {
// return true;
// }
//
// @Override
// public boolean shouldSideBeRendered (IBlockAccess p_149646_1_, int p_149646_2_, int p_149646_3_, int p_149646_4_, int p_149646_5_) {
// return true;
// }
//
// @Override
// public int getRenderType () {
// return ClientProxy.flowerLeafRenderID;
// }
//
// @SideOnly(Side.CLIENT)
// public IIcon getFlowerIcon (IBlockAccess world, int x, int y, int z, int meta, int side) {
// boolean clear1 = world.getBlock(x, y + 1, z) != this;
// boolean clear2 = world.getBlock(x, y, z - 1) != this;
// boolean clear3 = world.getBlock(x, y, z + 1) != this;
// boolean clear4 = world.getBlock(x - 1, y, z) != this;
// boolean clear5 = world.getBlock(x + 1, y, z) != this;
//
// if (side == 1 && clear1)
// return flowersTop[meta & 3];
// else if ((side == 2 && clear2) || (side == 3 && clear3) || (side == 4 && clear4) || (side == 5 && clear5))
// return clear1 ? flowersTopSide[meta & 3] : flowersSide[meta & 3];
//
// return null;
// }
//
// /*@Override
// public String[] func_150125_e () {
// return new String[0];
// }*/
//
// @SideOnly(Side.CLIENT)
// @Override
// public void registerBlockIcons (IIconRegister register) {
// super.registerBlockIcons(register);
//
// flowersTop = new IIcon[4];
// flowersTopSide = new IIcon[4];
// flowersSide = new IIcon[4];
//
// for (int i = 0; i < 4; i++) {
// flowersTop[i] = register.registerIcon(ModularPots.MOD_ID + ":leaves_flowers_white");
// flowersTopSide[i] = register.registerIcon(ModularPots.MOD_ID + ":leaves_flowers_white_half");
// flowersSide[i] = register.registerIcon(ModularPots.MOD_ID + ":leaves_flowers_white_sparse");
// }
// }
// }
//
// Path: ModularPots/src/com/jaquadro/minecraft/modularpots/client/ClientProxy.java
// public class ClientProxy extends CommonProxy
// {
// public static int renderPass = 0;
// public static int largePotRenderID;
// public static int transformPlantRenderID;
// public static int thinLogRenderID;
// public static int flowerLeafRenderID;
// public static int thinLogFenceRenderID;
//
// @Override
// public void registerRenderers ()
// {
// largePotRenderID = RenderingRegistry.getNextAvailableRenderId();
// transformPlantRenderID = RenderingRegistry.getNextAvailableRenderId();
// thinLogRenderID = RenderingRegistry.getNextAvailableRenderId();
// flowerLeafRenderID = RenderingRegistry.getNextAvailableRenderId();
// thinLogFenceRenderID = RenderingRegistry.getNextAvailableRenderId();
//
// RenderingRegistry.registerBlockHandler(largePotRenderID, new LargePotRenderer());
// RenderingRegistry.registerBlockHandler(transformPlantRenderID, new TransformPlantRenderer());
// RenderingRegistry.registerBlockHandler(thinLogRenderID, new ThinLogRenderer());
// RenderingRegistry.registerBlockHandler(flowerLeafRenderID, new FlowerLeafRenderer());
// RenderingRegistry.registerBlockHandler(thinLogFenceRenderID, new ThinLogFenceRenderer());
// }
// }
// Path: ModularPots/src/com/jaquadro/minecraft/modularpots/client/renderer/FlowerLeafRenderer.java
import com.jaquadro.minecraft.modularpots.block.BlockFlowerLeaves;
import com.jaquadro.minecraft.modularpots.client.ClientProxy;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
IIcon icon = block.getFlowerIcon(world, x, y, z, meta, 1);
if (icon != null)
renderer.renderFaceYPos(block, x, y + offset, z, icon);
icon = block.getFlowerIcon(world, x, y, z, meta, 2);
if (icon != null)
renderer.renderFaceZNeg(block, x, y, z - offset, icon);
icon = block.getFlowerIcon(world, x, y, z, meta, 3);
if (icon != null)
renderer.renderFaceZPos(block, x, y, z + offset, icon);
icon = block.getFlowerIcon(world, x, y, z, meta, 4);
if (icon != null)
renderer.renderFaceXNeg(block, x - offset, y, z, icon);
icon = block.getFlowerIcon(world, x, y, z, meta, 5);
if (icon != null)
renderer.renderFaceXPos(block, x + offset, y, z, icon);
return true;
}
@Override
public boolean shouldRender3DInInventory (int modelId) {
return true;
}
@Override
public int getRenderId () { | return ClientProxy.flowerLeafRenderID; |
jaquadro/ForgeMods | HungerStrike/src/com/jaquadro/minecraft/hungerstrike/ExtendedPlayer.java | // Path: HungerStrike/src/com/jaquadro/minecraft/hungerstrike/network/SyncExtendedPlayerPacket.java
// public class SyncExtendedPlayerPacket extends AbstractPacket
// {
// private NBTTagCompound data;
//
// public SyncExtendedPlayerPacket () { }
//
// public SyncExtendedPlayerPacket (EntityPlayer player) {
// data = new NBTTagCompound();
// ExtendedPlayer ep = ExtendedPlayer.get(player);
// if (ep != null)
// ep.saveNBTDataSync(data);
// }
//
// @Override
// public void encodeInto (ChannelHandlerContext ctx, ByteBuf buffer) {
// ByteBufUtils.writeTag(buffer, data);
// }
//
// @Override
// public void decodeInto (ChannelHandlerContext ctx, ByteBuf buffer) {
// data = ByteBufUtils.readTag(buffer);
// }
//
// @Override
// public void handleClientSide (EntityPlayer player) {
// ExtendedPlayer ep = ExtendedPlayer.get(player);
// if (ep != null)
// ep.loadNBTData(data);
// }
//
// @Override
// public void handleServerSide (EntityPlayer player) { }
// }
| import com.jaquadro.minecraft.hungerstrike.network.SyncExtendedPlayerPacket;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.server.FMLServerHandler;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.util.FoodStats;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties; |
@Override
public void init(Entity entity, World world) { }
@Override
public void saveNBTData(NBTTagCompound compound) {
NBTTagCompound properties = new NBTTagCompound();
properties.setBoolean("Enabled", hungerStrikeEnabled);
compound.setTag(TAG, properties);
}
@Override
public void loadNBTData(NBTTagCompound compound) {
NBTTagCompound properties = (NBTTagCompound) compound.getTag(TAG);
hungerStrikeEnabled = properties.getBoolean("Enabled");
}
public void saveNBTDataSync (NBTTagCompound compound) {
NBTTagCompound properties = new NBTTagCompound();
properties.setBoolean("Enabled", hungerStrikeEnabled);
compound.setTag(TAG, properties);
}
public void enableHungerStrike (boolean enable) {
if (hungerStrikeEnabled != enable) {
hungerStrikeEnabled = enable;
if (player instanceof EntityPlayerMP) | // Path: HungerStrike/src/com/jaquadro/minecraft/hungerstrike/network/SyncExtendedPlayerPacket.java
// public class SyncExtendedPlayerPacket extends AbstractPacket
// {
// private NBTTagCompound data;
//
// public SyncExtendedPlayerPacket () { }
//
// public SyncExtendedPlayerPacket (EntityPlayer player) {
// data = new NBTTagCompound();
// ExtendedPlayer ep = ExtendedPlayer.get(player);
// if (ep != null)
// ep.saveNBTDataSync(data);
// }
//
// @Override
// public void encodeInto (ChannelHandlerContext ctx, ByteBuf buffer) {
// ByteBufUtils.writeTag(buffer, data);
// }
//
// @Override
// public void decodeInto (ChannelHandlerContext ctx, ByteBuf buffer) {
// data = ByteBufUtils.readTag(buffer);
// }
//
// @Override
// public void handleClientSide (EntityPlayer player) {
// ExtendedPlayer ep = ExtendedPlayer.get(player);
// if (ep != null)
// ep.loadNBTData(data);
// }
//
// @Override
// public void handleServerSide (EntityPlayer player) { }
// }
// Path: HungerStrike/src/com/jaquadro/minecraft/hungerstrike/ExtendedPlayer.java
import com.jaquadro.minecraft.hungerstrike.network.SyncExtendedPlayerPacket;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.server.FMLServerHandler;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.util.FoodStats;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;
@Override
public void init(Entity entity, World world) { }
@Override
public void saveNBTData(NBTTagCompound compound) {
NBTTagCompound properties = new NBTTagCompound();
properties.setBoolean("Enabled", hungerStrikeEnabled);
compound.setTag(TAG, properties);
}
@Override
public void loadNBTData(NBTTagCompound compound) {
NBTTagCompound properties = (NBTTagCompound) compound.getTag(TAG);
hungerStrikeEnabled = properties.getBoolean("Enabled");
}
public void saveNBTDataSync (NBTTagCompound compound) {
NBTTagCompound properties = new NBTTagCompound();
properties.setBoolean("Enabled", hungerStrikeEnabled);
compound.setTag(TAG, properties);
}
public void enableHungerStrike (boolean enable) {
if (hungerStrikeEnabled != enable) {
hungerStrikeEnabled = enable;
if (player instanceof EntityPlayerMP) | HungerStrike.packetPipeline.sendTo(new SyncExtendedPlayerPacket(player), (EntityPlayerMP)player); |
jaquadro/ForgeMods | ModularPots/src/com/jaquadro/minecraft/modularpots/creativetab/ModularPotsCreativeTab.java | // Path: ModularPots/src/com/jaquadro/minecraft/modularpots/core/ModBlocks.java
// public class ModBlocks
// {
// public static BlockLargePot largePot;
// public static BlockLargePot largePotColored;
// public static BlockLargePotPlantProxy largePotPlantProxy;
// public static BlockPotteryTable potteryTable;
// public static BlockThinLog thinLog;
// public static BlockThinLogFence thinLogFence;
// public static BlockFlowerLeaves flowerLeaves;
//
// public void init () {
// largePot = new BlockLargePot("largePot", false);
// largePotColored = new BlockLargePot("largePotColored", true);
// largePotPlantProxy = new BlockLargePotPlantProxy("largePotPlantProxy");
// potteryTable = new BlockPotteryTable("potteryTable");
// thinLog = new BlockThinLog("thinLog");
// thinLogFence = new BlockThinLogFence("thinLogFence");
// flowerLeaves = new BlockFlowerLeaves("flowerLeaves");
//
// String MOD_ID = ModularPots.MOD_ID;
//
// GameRegistry.registerBlock(largePot, ItemLargePot.class, "large_pot");
// GameRegistry.registerBlock(largePotColored, ItemLargePotColored.class, "large_pot_colored");
// GameRegistry.registerBlock(largePotPlantProxy, "large_pot_plant_proxy");
// GameRegistry.registerBlock(thinLog, ItemThinLog.class, "thin_log");
// GameRegistry.registerBlock(thinLogFence, ItemThinLogFence.class, "thin_log_fence");
// GameRegistry.registerBlock(potteryTable, "pottery_table");
// //GameRegistry.registerBlock(flowerLeaves, "flower_leaves");
//
// GameRegistry.registerTileEntity(TileEntityLargePot.class, ModBlocks.getQualifiedName(largePot));
// GameRegistry.registerTileEntity(TileEntityPotteryTable.class, ModBlocks.getQualifiedName(potteryTable));
// GameRegistry.registerTileEntity(TileEntityWoodProxy.class, ModBlocks.getQualifiedName(thinLog));
// }
//
// public static Block get (String name) {
// return GameRegistry.findBlock(ModularPots.MOD_ID, name);
// }
//
// public static String getQualifiedName (Block block) {
// return GameData.blockRegistry.getNameForObject(block);
// }
//
// public static UniqueMetaIdentifier getUniqueMetaID (Block block, int meta) {
// String name = GameData.blockRegistry.getNameForObject(block);
// if (name == null) {
// FMLLog.log(ModularPots.MOD_ID, Level.WARN, "Tried to make a UniqueMetaIdentifier from an invalid block");
// return null;
// }
//
// return new UniqueMetaIdentifier(name, meta);
// }
// }
| import com.jaquadro.minecraft.modularpots.core.ModBlocks;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item; | package com.jaquadro.minecraft.modularpots.creativetab;
public class ModularPotsCreativeTab extends CreativeTabs
{
public ModularPotsCreativeTab (String label) {
super(label);
}
@SideOnly(Side.CLIENT)
@Override
public Item getTabIconItem () { | // Path: ModularPots/src/com/jaquadro/minecraft/modularpots/core/ModBlocks.java
// public class ModBlocks
// {
// public static BlockLargePot largePot;
// public static BlockLargePot largePotColored;
// public static BlockLargePotPlantProxy largePotPlantProxy;
// public static BlockPotteryTable potteryTable;
// public static BlockThinLog thinLog;
// public static BlockThinLogFence thinLogFence;
// public static BlockFlowerLeaves flowerLeaves;
//
// public void init () {
// largePot = new BlockLargePot("largePot", false);
// largePotColored = new BlockLargePot("largePotColored", true);
// largePotPlantProxy = new BlockLargePotPlantProxy("largePotPlantProxy");
// potteryTable = new BlockPotteryTable("potteryTable");
// thinLog = new BlockThinLog("thinLog");
// thinLogFence = new BlockThinLogFence("thinLogFence");
// flowerLeaves = new BlockFlowerLeaves("flowerLeaves");
//
// String MOD_ID = ModularPots.MOD_ID;
//
// GameRegistry.registerBlock(largePot, ItemLargePot.class, "large_pot");
// GameRegistry.registerBlock(largePotColored, ItemLargePotColored.class, "large_pot_colored");
// GameRegistry.registerBlock(largePotPlantProxy, "large_pot_plant_proxy");
// GameRegistry.registerBlock(thinLog, ItemThinLog.class, "thin_log");
// GameRegistry.registerBlock(thinLogFence, ItemThinLogFence.class, "thin_log_fence");
// GameRegistry.registerBlock(potteryTable, "pottery_table");
// //GameRegistry.registerBlock(flowerLeaves, "flower_leaves");
//
// GameRegistry.registerTileEntity(TileEntityLargePot.class, ModBlocks.getQualifiedName(largePot));
// GameRegistry.registerTileEntity(TileEntityPotteryTable.class, ModBlocks.getQualifiedName(potteryTable));
// GameRegistry.registerTileEntity(TileEntityWoodProxy.class, ModBlocks.getQualifiedName(thinLog));
// }
//
// public static Block get (String name) {
// return GameRegistry.findBlock(ModularPots.MOD_ID, name);
// }
//
// public static String getQualifiedName (Block block) {
// return GameData.blockRegistry.getNameForObject(block);
// }
//
// public static UniqueMetaIdentifier getUniqueMetaID (Block block, int meta) {
// String name = GameData.blockRegistry.getNameForObject(block);
// if (name == null) {
// FMLLog.log(ModularPots.MOD_ID, Level.WARN, "Tried to make a UniqueMetaIdentifier from an invalid block");
// return null;
// }
//
// return new UniqueMetaIdentifier(name, meta);
// }
// }
// Path: ModularPots/src/com/jaquadro/minecraft/modularpots/creativetab/ModularPotsCreativeTab.java
import com.jaquadro.minecraft.modularpots.core.ModBlocks;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
package com.jaquadro.minecraft.modularpots.creativetab;
public class ModularPotsCreativeTab extends CreativeTabs
{
public ModularPotsCreativeTab (String label) {
super(label);
}
@SideOnly(Side.CLIENT)
@Override
public Item getTabIconItem () { | return Item.getItemFromBlock(ModBlocks.largePot); |
jaquadro/ForgeMods | ModularPots/src/com/jaquadro/minecraft/modularpots/integration/BiomesOPlentyIntegration.java | // Path: ModularPots/src/com/jaquadro/minecraft/modularpots/block/support/SaplingRegistry.java
// public class SaplingRegistry
// {
// public static class SaplingRecord
// {
// public UniqueMetaIdentifier saplingType;
// public UniqueMetaIdentifier woodType;
// public UniqueMetaIdentifier leafType;
// public WorldGenOrnamentalTree generator;
// }
//
// private static final Map<UniqueMetaIdentifier, SaplingRecord> registry = new HashMap<UniqueMetaIdentifier, SaplingRecord>();
//
// public static boolean registerSapling (UniqueMetaIdentifier sapling, UniqueMetaIdentifier wood, UniqueMetaIdentifier leaf, String generatorName) {
// OrnamentalTreeFactory tree = OrnamentalTreeRegistry.getTree(generatorName);
// if (tree == null)
// return false;
//
// WorldGenOrnamentalTree generator = tree.create(wood.getBlock(), wood.meta, leaf.getBlock(), leaf.meta);
//
// SaplingRecord record = new SaplingRecord();
// record.saplingType = sapling;
// record.woodType = wood;
// record.leafType = leaf;
// record.generator = generator;
//
// registry.put(sapling, record);
//
// return true;
// }
//
// public static boolean registerSapling (Item sapling, int saplingMeta, Block wood, int woodMeta, Block leaf, int leafMeta, String generatorName) {
// return registerSapling(ModItems.getUniqueMetaID(sapling, saplingMeta), ModBlocks.getUniqueMetaID(wood, woodMeta), ModBlocks.getUniqueMetaID(leaf, leafMeta), generatorName);
// }
//
// public static WorldGenOrnamentalTree getGenerator (Block block, int meta) {
// UniqueMetaIdentifier id = ModBlocks.getUniqueMetaID(block, meta);
// if (!registry.containsKey(id))
// return null;
//
// SaplingRecord record = registry.get(id);
// return record.generator;
// }
//
// static {
// Item sapling = Item.getItemFromBlock(Blocks.sapling);
//
// registerSapling(sapling, 0, Blocks.log, 0, Blocks.leaves, 0, "small_oak");
// registerSapling(sapling, 1, Blocks.log, 1, Blocks.leaves, 1, "small_spruce");
// registerSapling(sapling, 2, Blocks.log, 2, Blocks.leaves, 2, "small_oak");
// registerSapling(sapling, 3, Blocks.log, 3, Blocks.leaves, 3, "small_jungle");
// registerSapling(sapling, 4, Blocks.log2, 0, Blocks.leaves2, 0, "small_acacia");
// registerSapling(sapling, 5, Blocks.log2, 1, Blocks.leaves2, 1, "small_oak");
// }
// }
//
// Path: ModularPots/src/com/jaquadro/minecraft/modularpots/block/support/WoodRegistry.java
// public class WoodRegistry
// {
// private static final Map<UniqueMetaIdentifier, Block> registry = new HashMap<UniqueMetaIdentifier, Block>();
//
// public static void registerWoodType (Block block, int meta) {
// if (block == null)
// return;
//
// UniqueMetaIdentifier id = new UniqueMetaIdentifier(ModBlocks.getQualifiedName(block), meta);
// if (!registry.containsKey(id))
// registry.put(id, block);
// }
//
// public static Set<Entry<UniqueMetaIdentifier, Block>> registeredTypes () {
// return registry.entrySet();
// }
//
// public static boolean contains (Block block, int meta) {
// UniqueMetaIdentifier id = ModBlocks.getUniqueMetaID(block, meta);
// return registry.containsKey(id);
// }
// }
| import com.jaquadro.minecraft.modularpots.block.support.SaplingRegistry;
import com.jaquadro.minecraft.modularpots.block.support.WoodRegistry;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item; | package com.jaquadro.minecraft.modularpots.integration;
public class BiomesOPlentyIntegration
{
public static final String MOD_ID = "BiomesOPlenty";
public static void init () {
if (!Loader.isModLoaded(MOD_ID))
return;
Block log1 = GameRegistry.findBlock(MOD_ID, "logs1");
Block log2 = GameRegistry.findBlock(MOD_ID, "logs2");
Block log3 = GameRegistry.findBlock(MOD_ID, "logs3");
Block log4 = GameRegistry.findBlock(MOD_ID, "logs4");
Block bamboo = GameRegistry.findBlock(MOD_ID, "bamboo");
Block leaf1 = GameRegistry.findBlock(MOD_ID, "leaves1");
Block leaf2 = GameRegistry.findBlock(MOD_ID, "leaves2");
Block leaf3 = GameRegistry.findBlock(MOD_ID, "leaves3");
Block leaf4 = GameRegistry.findBlock(MOD_ID, "leaves4");
Block leafc1 = GameRegistry.findBlock(MOD_ID, "colorizedLeaves1");
Block leafc2 = GameRegistry.findBlock(MOD_ID, "colorizedLeaves2");
Block leafApple = GameRegistry.findBlock(MOD_ID, "appleLeaves");
Block leafPersimmon = GameRegistry.findBlock(MOD_ID, "persimmonLeaves");
Item sapling = GameRegistry.findItem(MOD_ID, "saplings");
Item sapling2 = GameRegistry.findItem(MOD_ID, "colorizedSaplings");
// Register Wood
| // Path: ModularPots/src/com/jaquadro/minecraft/modularpots/block/support/SaplingRegistry.java
// public class SaplingRegistry
// {
// public static class SaplingRecord
// {
// public UniqueMetaIdentifier saplingType;
// public UniqueMetaIdentifier woodType;
// public UniqueMetaIdentifier leafType;
// public WorldGenOrnamentalTree generator;
// }
//
// private static final Map<UniqueMetaIdentifier, SaplingRecord> registry = new HashMap<UniqueMetaIdentifier, SaplingRecord>();
//
// public static boolean registerSapling (UniqueMetaIdentifier sapling, UniqueMetaIdentifier wood, UniqueMetaIdentifier leaf, String generatorName) {
// OrnamentalTreeFactory tree = OrnamentalTreeRegistry.getTree(generatorName);
// if (tree == null)
// return false;
//
// WorldGenOrnamentalTree generator = tree.create(wood.getBlock(), wood.meta, leaf.getBlock(), leaf.meta);
//
// SaplingRecord record = new SaplingRecord();
// record.saplingType = sapling;
// record.woodType = wood;
// record.leafType = leaf;
// record.generator = generator;
//
// registry.put(sapling, record);
//
// return true;
// }
//
// public static boolean registerSapling (Item sapling, int saplingMeta, Block wood, int woodMeta, Block leaf, int leafMeta, String generatorName) {
// return registerSapling(ModItems.getUniqueMetaID(sapling, saplingMeta), ModBlocks.getUniqueMetaID(wood, woodMeta), ModBlocks.getUniqueMetaID(leaf, leafMeta), generatorName);
// }
//
// public static WorldGenOrnamentalTree getGenerator (Block block, int meta) {
// UniqueMetaIdentifier id = ModBlocks.getUniqueMetaID(block, meta);
// if (!registry.containsKey(id))
// return null;
//
// SaplingRecord record = registry.get(id);
// return record.generator;
// }
//
// static {
// Item sapling = Item.getItemFromBlock(Blocks.sapling);
//
// registerSapling(sapling, 0, Blocks.log, 0, Blocks.leaves, 0, "small_oak");
// registerSapling(sapling, 1, Blocks.log, 1, Blocks.leaves, 1, "small_spruce");
// registerSapling(sapling, 2, Blocks.log, 2, Blocks.leaves, 2, "small_oak");
// registerSapling(sapling, 3, Blocks.log, 3, Blocks.leaves, 3, "small_jungle");
// registerSapling(sapling, 4, Blocks.log2, 0, Blocks.leaves2, 0, "small_acacia");
// registerSapling(sapling, 5, Blocks.log2, 1, Blocks.leaves2, 1, "small_oak");
// }
// }
//
// Path: ModularPots/src/com/jaquadro/minecraft/modularpots/block/support/WoodRegistry.java
// public class WoodRegistry
// {
// private static final Map<UniqueMetaIdentifier, Block> registry = new HashMap<UniqueMetaIdentifier, Block>();
//
// public static void registerWoodType (Block block, int meta) {
// if (block == null)
// return;
//
// UniqueMetaIdentifier id = new UniqueMetaIdentifier(ModBlocks.getQualifiedName(block), meta);
// if (!registry.containsKey(id))
// registry.put(id, block);
// }
//
// public static Set<Entry<UniqueMetaIdentifier, Block>> registeredTypes () {
// return registry.entrySet();
// }
//
// public static boolean contains (Block block, int meta) {
// UniqueMetaIdentifier id = ModBlocks.getUniqueMetaID(block, meta);
// return registry.containsKey(id);
// }
// }
// Path: ModularPots/src/com/jaquadro/minecraft/modularpots/integration/BiomesOPlentyIntegration.java
import com.jaquadro.minecraft.modularpots.block.support.SaplingRegistry;
import com.jaquadro.minecraft.modularpots.block.support.WoodRegistry;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
package com.jaquadro.minecraft.modularpots.integration;
public class BiomesOPlentyIntegration
{
public static final String MOD_ID = "BiomesOPlenty";
public static void init () {
if (!Loader.isModLoaded(MOD_ID))
return;
Block log1 = GameRegistry.findBlock(MOD_ID, "logs1");
Block log2 = GameRegistry.findBlock(MOD_ID, "logs2");
Block log3 = GameRegistry.findBlock(MOD_ID, "logs3");
Block log4 = GameRegistry.findBlock(MOD_ID, "logs4");
Block bamboo = GameRegistry.findBlock(MOD_ID, "bamboo");
Block leaf1 = GameRegistry.findBlock(MOD_ID, "leaves1");
Block leaf2 = GameRegistry.findBlock(MOD_ID, "leaves2");
Block leaf3 = GameRegistry.findBlock(MOD_ID, "leaves3");
Block leaf4 = GameRegistry.findBlock(MOD_ID, "leaves4");
Block leafc1 = GameRegistry.findBlock(MOD_ID, "colorizedLeaves1");
Block leafc2 = GameRegistry.findBlock(MOD_ID, "colorizedLeaves2");
Block leafApple = GameRegistry.findBlock(MOD_ID, "appleLeaves");
Block leafPersimmon = GameRegistry.findBlock(MOD_ID, "persimmonLeaves");
Item sapling = GameRegistry.findItem(MOD_ID, "saplings");
Item sapling2 = GameRegistry.findItem(MOD_ID, "colorizedSaplings");
// Register Wood
| WoodRegistry.registerWoodType(log1, 0); |
jaquadro/ForgeMods | ModularPots/src/com/jaquadro/minecraft/modularpots/integration/BiomesOPlentyIntegration.java | // Path: ModularPots/src/com/jaquadro/minecraft/modularpots/block/support/SaplingRegistry.java
// public class SaplingRegistry
// {
// public static class SaplingRecord
// {
// public UniqueMetaIdentifier saplingType;
// public UniqueMetaIdentifier woodType;
// public UniqueMetaIdentifier leafType;
// public WorldGenOrnamentalTree generator;
// }
//
// private static final Map<UniqueMetaIdentifier, SaplingRecord> registry = new HashMap<UniqueMetaIdentifier, SaplingRecord>();
//
// public static boolean registerSapling (UniqueMetaIdentifier sapling, UniqueMetaIdentifier wood, UniqueMetaIdentifier leaf, String generatorName) {
// OrnamentalTreeFactory tree = OrnamentalTreeRegistry.getTree(generatorName);
// if (tree == null)
// return false;
//
// WorldGenOrnamentalTree generator = tree.create(wood.getBlock(), wood.meta, leaf.getBlock(), leaf.meta);
//
// SaplingRecord record = new SaplingRecord();
// record.saplingType = sapling;
// record.woodType = wood;
// record.leafType = leaf;
// record.generator = generator;
//
// registry.put(sapling, record);
//
// return true;
// }
//
// public static boolean registerSapling (Item sapling, int saplingMeta, Block wood, int woodMeta, Block leaf, int leafMeta, String generatorName) {
// return registerSapling(ModItems.getUniqueMetaID(sapling, saplingMeta), ModBlocks.getUniqueMetaID(wood, woodMeta), ModBlocks.getUniqueMetaID(leaf, leafMeta), generatorName);
// }
//
// public static WorldGenOrnamentalTree getGenerator (Block block, int meta) {
// UniqueMetaIdentifier id = ModBlocks.getUniqueMetaID(block, meta);
// if (!registry.containsKey(id))
// return null;
//
// SaplingRecord record = registry.get(id);
// return record.generator;
// }
//
// static {
// Item sapling = Item.getItemFromBlock(Blocks.sapling);
//
// registerSapling(sapling, 0, Blocks.log, 0, Blocks.leaves, 0, "small_oak");
// registerSapling(sapling, 1, Blocks.log, 1, Blocks.leaves, 1, "small_spruce");
// registerSapling(sapling, 2, Blocks.log, 2, Blocks.leaves, 2, "small_oak");
// registerSapling(sapling, 3, Blocks.log, 3, Blocks.leaves, 3, "small_jungle");
// registerSapling(sapling, 4, Blocks.log2, 0, Blocks.leaves2, 0, "small_acacia");
// registerSapling(sapling, 5, Blocks.log2, 1, Blocks.leaves2, 1, "small_oak");
// }
// }
//
// Path: ModularPots/src/com/jaquadro/minecraft/modularpots/block/support/WoodRegistry.java
// public class WoodRegistry
// {
// private static final Map<UniqueMetaIdentifier, Block> registry = new HashMap<UniqueMetaIdentifier, Block>();
//
// public static void registerWoodType (Block block, int meta) {
// if (block == null)
// return;
//
// UniqueMetaIdentifier id = new UniqueMetaIdentifier(ModBlocks.getQualifiedName(block), meta);
// if (!registry.containsKey(id))
// registry.put(id, block);
// }
//
// public static Set<Entry<UniqueMetaIdentifier, Block>> registeredTypes () {
// return registry.entrySet();
// }
//
// public static boolean contains (Block block, int meta) {
// UniqueMetaIdentifier id = ModBlocks.getUniqueMetaID(block, meta);
// return registry.containsKey(id);
// }
// }
| import com.jaquadro.minecraft.modularpots.block.support.SaplingRegistry;
import com.jaquadro.minecraft.modularpots.block.support.WoodRegistry;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item; | Block leafApple = GameRegistry.findBlock(MOD_ID, "appleLeaves");
Block leafPersimmon = GameRegistry.findBlock(MOD_ID, "persimmonLeaves");
Item sapling = GameRegistry.findItem(MOD_ID, "saplings");
Item sapling2 = GameRegistry.findItem(MOD_ID, "colorizedSaplings");
// Register Wood
WoodRegistry.registerWoodType(log1, 0);
WoodRegistry.registerWoodType(log1, 1);
WoodRegistry.registerWoodType(log1, 2);
WoodRegistry.registerWoodType(log1, 3);
WoodRegistry.registerWoodType(log2, 0);
WoodRegistry.registerWoodType(log2, 1);
WoodRegistry.registerWoodType(log2, 2);
WoodRegistry.registerWoodType(log2, 3);
WoodRegistry.registerWoodType(log3, 0);
WoodRegistry.registerWoodType(log3, 1);
WoodRegistry.registerWoodType(log3, 2);
WoodRegistry.registerWoodType(log3, 3);
WoodRegistry.registerWoodType(log4, 0);
WoodRegistry.registerWoodType(log4, 1);
WoodRegistry.registerWoodType(log4, 2);
WoodRegistry.registerWoodType(log4, 3);
// Register Saplings
| // Path: ModularPots/src/com/jaquadro/minecraft/modularpots/block/support/SaplingRegistry.java
// public class SaplingRegistry
// {
// public static class SaplingRecord
// {
// public UniqueMetaIdentifier saplingType;
// public UniqueMetaIdentifier woodType;
// public UniqueMetaIdentifier leafType;
// public WorldGenOrnamentalTree generator;
// }
//
// private static final Map<UniqueMetaIdentifier, SaplingRecord> registry = new HashMap<UniqueMetaIdentifier, SaplingRecord>();
//
// public static boolean registerSapling (UniqueMetaIdentifier sapling, UniqueMetaIdentifier wood, UniqueMetaIdentifier leaf, String generatorName) {
// OrnamentalTreeFactory tree = OrnamentalTreeRegistry.getTree(generatorName);
// if (tree == null)
// return false;
//
// WorldGenOrnamentalTree generator = tree.create(wood.getBlock(), wood.meta, leaf.getBlock(), leaf.meta);
//
// SaplingRecord record = new SaplingRecord();
// record.saplingType = sapling;
// record.woodType = wood;
// record.leafType = leaf;
// record.generator = generator;
//
// registry.put(sapling, record);
//
// return true;
// }
//
// public static boolean registerSapling (Item sapling, int saplingMeta, Block wood, int woodMeta, Block leaf, int leafMeta, String generatorName) {
// return registerSapling(ModItems.getUniqueMetaID(sapling, saplingMeta), ModBlocks.getUniqueMetaID(wood, woodMeta), ModBlocks.getUniqueMetaID(leaf, leafMeta), generatorName);
// }
//
// public static WorldGenOrnamentalTree getGenerator (Block block, int meta) {
// UniqueMetaIdentifier id = ModBlocks.getUniqueMetaID(block, meta);
// if (!registry.containsKey(id))
// return null;
//
// SaplingRecord record = registry.get(id);
// return record.generator;
// }
//
// static {
// Item sapling = Item.getItemFromBlock(Blocks.sapling);
//
// registerSapling(sapling, 0, Blocks.log, 0, Blocks.leaves, 0, "small_oak");
// registerSapling(sapling, 1, Blocks.log, 1, Blocks.leaves, 1, "small_spruce");
// registerSapling(sapling, 2, Blocks.log, 2, Blocks.leaves, 2, "small_oak");
// registerSapling(sapling, 3, Blocks.log, 3, Blocks.leaves, 3, "small_jungle");
// registerSapling(sapling, 4, Blocks.log2, 0, Blocks.leaves2, 0, "small_acacia");
// registerSapling(sapling, 5, Blocks.log2, 1, Blocks.leaves2, 1, "small_oak");
// }
// }
//
// Path: ModularPots/src/com/jaquadro/minecraft/modularpots/block/support/WoodRegistry.java
// public class WoodRegistry
// {
// private static final Map<UniqueMetaIdentifier, Block> registry = new HashMap<UniqueMetaIdentifier, Block>();
//
// public static void registerWoodType (Block block, int meta) {
// if (block == null)
// return;
//
// UniqueMetaIdentifier id = new UniqueMetaIdentifier(ModBlocks.getQualifiedName(block), meta);
// if (!registry.containsKey(id))
// registry.put(id, block);
// }
//
// public static Set<Entry<UniqueMetaIdentifier, Block>> registeredTypes () {
// return registry.entrySet();
// }
//
// public static boolean contains (Block block, int meta) {
// UniqueMetaIdentifier id = ModBlocks.getUniqueMetaID(block, meta);
// return registry.containsKey(id);
// }
// }
// Path: ModularPots/src/com/jaquadro/minecraft/modularpots/integration/BiomesOPlentyIntegration.java
import com.jaquadro.minecraft.modularpots.block.support.SaplingRegistry;
import com.jaquadro.minecraft.modularpots.block.support.WoodRegistry;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
Block leafApple = GameRegistry.findBlock(MOD_ID, "appleLeaves");
Block leafPersimmon = GameRegistry.findBlock(MOD_ID, "persimmonLeaves");
Item sapling = GameRegistry.findItem(MOD_ID, "saplings");
Item sapling2 = GameRegistry.findItem(MOD_ID, "colorizedSaplings");
// Register Wood
WoodRegistry.registerWoodType(log1, 0);
WoodRegistry.registerWoodType(log1, 1);
WoodRegistry.registerWoodType(log1, 2);
WoodRegistry.registerWoodType(log1, 3);
WoodRegistry.registerWoodType(log2, 0);
WoodRegistry.registerWoodType(log2, 1);
WoodRegistry.registerWoodType(log2, 2);
WoodRegistry.registerWoodType(log2, 3);
WoodRegistry.registerWoodType(log3, 0);
WoodRegistry.registerWoodType(log3, 1);
WoodRegistry.registerWoodType(log3, 2);
WoodRegistry.registerWoodType(log3, 3);
WoodRegistry.registerWoodType(log4, 0);
WoodRegistry.registerWoodType(log4, 1);
WoodRegistry.registerWoodType(log4, 2);
WoodRegistry.registerWoodType(log4, 3);
// Register Saplings
| SaplingRegistry.registerSapling(sapling, 0, Blocks.log, 0, leafApple, 0, "small_oak"); // Apple Tree |
jaquadro/ForgeMods | ModularPots/src/com/jaquadro/minecraft/modularpots/item/ItemUsedSoilKit.java | // Path: ModularPots/src/com/jaquadro/minecraft/modularpots/ModularPots.java
// @Mod(modid = ModularPots.MOD_ID, name = ModularPots.MOD_NAME, version = ModularPots.MOD_VERSION)
// public class ModularPots
// {
// public static final String MOD_ID = "modularpots";
// static final String MOD_NAME = "Modular Flower Pots";
// static final String MOD_VERSION = "1.7.10.14";
// static final String SOURCE_PATH = "com.jaquadro.minecraft.modularpots.";
//
// public static CreativeTabs tabModularPots = new ModularPotsCreativeTab("modularPots");
//
// public static final ModBlocks blocks = new ModBlocks();
// public static final ModItems items = new ModItems();
// public static final ModRecipes recipes = new ModRecipes();
// public static final ModIntegration integration = new ModIntegration();
//
// public static int potteryTableGuiID = 0;
//
// public static ConfigManager config;
//
// @Mod.Instance(MOD_ID)
// public static ModularPots instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "client.ClientProxy", serverSide = SOURCE_PATH + "CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// config = new ConfigManager(new File(event.getModConfigurationDirectory(), MOD_ID + ".patterns.cfg"));
//
// blocks.init();
// items.init();
// }
//
// @Mod.EventHandler
// public void load (FMLInitializationEvent event) {
// proxy.registerRenderers();
// MinecraftForge.EVENT_BUS.register(this);
// FMLCommonHandler.instance().bus().register(this);
// NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler());
//
// for (int i = 1; i < 256; i++) {
// if (!config.hasPattern(i))
// continue;
//
// PatternConfig pattern = config.getPattern(i);
// for (int j = 0; j < pattern.getLocationCount(); j++)
// ChestGenHooks.addItem(pattern.getGenLocation(j), new WeightedRandomChestContent(items.potteryPattern, i, 1, 1, pattern.getGenRarity(j)));
// }
//
// VillagerTradeHandler.instance().load();
// integration.init();
// }
//
// @Mod.EventHandler
// public void postInit (FMLPostInitializationEvent event) {
// PlantHandlerRegistry.init();
// integration.postInit();
//
// recipes.init();
// }
//
// @Mod.EventHandler
// public void interModComs (FMLInterModComms.IMCEvent event) {
// for (FMLInterModComms.IMCMessage message : event.getMessages()) {
// if (message.key.equals("plantBlacklist")) {
// if (message.isItemStackMessage())
// PlantRegistry.instance().addToBlacklist(message.getItemStackValue());
// else if (message.isNBTMessage())
// PlantRegistry.instance().addToBlacklist(message.getNBTValue());
// }
// else if (message.key.equals("bonemealBlacklist")) {
// if (message.isItemStackMessage())
// PlantRegistry.instance().addToBlacklist(message.getItemStackValue(), RegistryGroup.Bonemeal);
// else if (message.isNBTMessage())
// PlantRegistry.instance().addToBlacklist(message.getNBTValue(), RegistryGroup.Bonemeal);
// }
// }
// }
//
// @SubscribeEvent
// public void applyBonemeal (BonemealEvent event) {
// if (event.block == blocks.largePotPlantProxy) {
// BlockLargePotPlantProxy proxyBlock = blocks.largePotPlantProxy;
// if (proxyBlock.applyBonemeal(event.world, event.x, event.y, event.z))
// event.setResult(Result.ALLOW); // Stop further processing and consume bonemeal
// }
// }
//
// @SubscribeEvent
// public void handleCrafting (PlayerEvent.ItemCraftedEvent event) {
// if (event.crafting.getItem() instanceof ItemThinLog) {
// for (int i = 0; i < event.craftMatrix.getSizeInventory(); i++) {
// ItemStack item = event.craftMatrix.getStackInSlot(i);
// if (item != null && isValidAxe(item) && item.getItemDamage() < item.getMaxDamage()) {
// event.craftMatrix.setInventorySlotContents(i, new ItemStack(item.getItem(), item.stackSize + 1, item.getItemDamage() + 1));
// }
// }
// }
// }
//
// private boolean isValidAxe (ItemStack itemStack) {
// Item item = itemStack.getItem();
// return item == Items.wooden_axe
// || item == Items.stone_axe
// || item == Items.iron_axe
// || item == Items.golden_axe
// || item == Items.diamond_axe;
// }
// }
| import com.jaquadro.minecraft.modularpots.ModularPots;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.BlockGlass;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IIcon;
import net.minecraft.util.StatCollector;
import net.minecraft.world.ColorizerGrass;
import net.minecraft.world.World;
import java.text.DecimalFormat;
import java.util.List; | package com.jaquadro.minecraft.modularpots.item;
public class ItemUsedSoilKit extends Item
{
@SideOnly(Side.CLIENT)
private IIcon icon;
@SideOnly(Side.CLIENT)
private IIcon iconOverlay;
public ItemUsedSoilKit (String unlocalizedName) {
setUnlocalizedName(unlocalizedName);
setMaxStackSize(1);
setHasSubtypes(true);
setTextureName("soil_test_kit"); | // Path: ModularPots/src/com/jaquadro/minecraft/modularpots/ModularPots.java
// @Mod(modid = ModularPots.MOD_ID, name = ModularPots.MOD_NAME, version = ModularPots.MOD_VERSION)
// public class ModularPots
// {
// public static final String MOD_ID = "modularpots";
// static final String MOD_NAME = "Modular Flower Pots";
// static final String MOD_VERSION = "1.7.10.14";
// static final String SOURCE_PATH = "com.jaquadro.minecraft.modularpots.";
//
// public static CreativeTabs tabModularPots = new ModularPotsCreativeTab("modularPots");
//
// public static final ModBlocks blocks = new ModBlocks();
// public static final ModItems items = new ModItems();
// public static final ModRecipes recipes = new ModRecipes();
// public static final ModIntegration integration = new ModIntegration();
//
// public static int potteryTableGuiID = 0;
//
// public static ConfigManager config;
//
// @Mod.Instance(MOD_ID)
// public static ModularPots instance;
//
// @SidedProxy(clientSide = SOURCE_PATH + "client.ClientProxy", serverSide = SOURCE_PATH + "CommonProxy")
// public static CommonProxy proxy;
//
// @Mod.EventHandler
// public void preInit (FMLPreInitializationEvent event) {
// config = new ConfigManager(new File(event.getModConfigurationDirectory(), MOD_ID + ".patterns.cfg"));
//
// blocks.init();
// items.init();
// }
//
// @Mod.EventHandler
// public void load (FMLInitializationEvent event) {
// proxy.registerRenderers();
// MinecraftForge.EVENT_BUS.register(this);
// FMLCommonHandler.instance().bus().register(this);
// NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler());
//
// for (int i = 1; i < 256; i++) {
// if (!config.hasPattern(i))
// continue;
//
// PatternConfig pattern = config.getPattern(i);
// for (int j = 0; j < pattern.getLocationCount(); j++)
// ChestGenHooks.addItem(pattern.getGenLocation(j), new WeightedRandomChestContent(items.potteryPattern, i, 1, 1, pattern.getGenRarity(j)));
// }
//
// VillagerTradeHandler.instance().load();
// integration.init();
// }
//
// @Mod.EventHandler
// public void postInit (FMLPostInitializationEvent event) {
// PlantHandlerRegistry.init();
// integration.postInit();
//
// recipes.init();
// }
//
// @Mod.EventHandler
// public void interModComs (FMLInterModComms.IMCEvent event) {
// for (FMLInterModComms.IMCMessage message : event.getMessages()) {
// if (message.key.equals("plantBlacklist")) {
// if (message.isItemStackMessage())
// PlantRegistry.instance().addToBlacklist(message.getItemStackValue());
// else if (message.isNBTMessage())
// PlantRegistry.instance().addToBlacklist(message.getNBTValue());
// }
// else if (message.key.equals("bonemealBlacklist")) {
// if (message.isItemStackMessage())
// PlantRegistry.instance().addToBlacklist(message.getItemStackValue(), RegistryGroup.Bonemeal);
// else if (message.isNBTMessage())
// PlantRegistry.instance().addToBlacklist(message.getNBTValue(), RegistryGroup.Bonemeal);
// }
// }
// }
//
// @SubscribeEvent
// public void applyBonemeal (BonemealEvent event) {
// if (event.block == blocks.largePotPlantProxy) {
// BlockLargePotPlantProxy proxyBlock = blocks.largePotPlantProxy;
// if (proxyBlock.applyBonemeal(event.world, event.x, event.y, event.z))
// event.setResult(Result.ALLOW); // Stop further processing and consume bonemeal
// }
// }
//
// @SubscribeEvent
// public void handleCrafting (PlayerEvent.ItemCraftedEvent event) {
// if (event.crafting.getItem() instanceof ItemThinLog) {
// for (int i = 0; i < event.craftMatrix.getSizeInventory(); i++) {
// ItemStack item = event.craftMatrix.getStackInSlot(i);
// if (item != null && isValidAxe(item) && item.getItemDamage() < item.getMaxDamage()) {
// event.craftMatrix.setInventorySlotContents(i, new ItemStack(item.getItem(), item.stackSize + 1, item.getItemDamage() + 1));
// }
// }
// }
// }
//
// private boolean isValidAxe (ItemStack itemStack) {
// Item item = itemStack.getItem();
// return item == Items.wooden_axe
// || item == Items.stone_axe
// || item == Items.iron_axe
// || item == Items.golden_axe
// || item == Items.diamond_axe;
// }
// }
// Path: ModularPots/src/com/jaquadro/minecraft/modularpots/item/ItemUsedSoilKit.java
import com.jaquadro.minecraft.modularpots.ModularPots;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.BlockGlass;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IIcon;
import net.minecraft.util.StatCollector;
import net.minecraft.world.ColorizerGrass;
import net.minecraft.world.World;
import java.text.DecimalFormat;
import java.util.List;
package com.jaquadro.minecraft.modularpots.item;
public class ItemUsedSoilKit extends Item
{
@SideOnly(Side.CLIENT)
private IIcon icon;
@SideOnly(Side.CLIENT)
private IIcon iconOverlay;
public ItemUsedSoilKit (String unlocalizedName) {
setUnlocalizedName(unlocalizedName);
setMaxStackSize(1);
setHasSubtypes(true);
setTextureName("soil_test_kit"); | setCreativeTab(ModularPots.tabModularPots); |
jaquadro/ForgeMods | HungerStrike/src/com/jaquadro/minecraft/hungerstrike/network/SyncExtendedPlayerPacket.java | // Path: HungerStrike/src/com/jaquadro/minecraft/hungerstrike/ExtendedPlayer.java
// public class ExtendedPlayer implements IExtendedEntityProperties
// {
// public final static String TAG = "HungerStrike";
//
// private final EntityPlayer player;
//
// private boolean hungerStrikeEnabled;
// private int startHunger;
//
// public ExtendedPlayer(EntityPlayer player) {
// this.player = player;
// this.hungerStrikeEnabled = false;
// }
//
// public static final void register (EntityPlayer player) {
// player.registerExtendedProperties(TAG, new ExtendedPlayer(player));
// }
//
// public static final ExtendedPlayer get (EntityPlayer player) {
// return (ExtendedPlayer) player.getExtendedProperties(TAG);
// }
//
// @Override
// public void init(Entity entity, World world) { }
//
// @Override
// public void saveNBTData(NBTTagCompound compound) {
// NBTTagCompound properties = new NBTTagCompound();
// properties.setBoolean("Enabled", hungerStrikeEnabled);
//
// compound.setTag(TAG, properties);
// }
//
// @Override
// public void loadNBTData(NBTTagCompound compound) {
// NBTTagCompound properties = (NBTTagCompound) compound.getTag(TAG);
//
// hungerStrikeEnabled = properties.getBoolean("Enabled");
// }
//
// public void saveNBTDataSync (NBTTagCompound compound) {
// NBTTagCompound properties = new NBTTagCompound();
// properties.setBoolean("Enabled", hungerStrikeEnabled);
//
// compound.setTag(TAG, properties);
// }
//
// public void enableHungerStrike (boolean enable) {
// if (hungerStrikeEnabled != enable) {
// hungerStrikeEnabled = enable;
// if (player instanceof EntityPlayerMP)
// HungerStrike.packetPipeline.sendTo(new SyncExtendedPlayerPacket(player), (EntityPlayerMP)player);
// }
// }
//
// public boolean isOnHungerStrike () {
// return hungerStrikeEnabled;
// }
//
// /*public boolean getEffectiveHungerStrike () {
// if (!player.worldObj.isRemote)
// return hungerStrikeEnabled;
//
// switch (HungerStrike.config.getMode()) {
// case NONE:
// return false;
// case ALL:
// return true;
// case LIST:
// default:
// return hungerStrikeEnabled;
// }
// }*/
//
// private boolean shouldTick () {
// ConfigManager.Mode mode = HungerStrike.instance.config.getMode();
// if (mode == ConfigManager.Mode.LIST)
// return hungerStrikeEnabled;
// else
// return mode == ConfigManager.Mode.ALL;
// }
//
// public void tick (TickEvent.Phase phase, Side side) {
// if (!shouldTick())
// return;
//
// if (phase == TickEvent.Phase.START)
// tickStart();
// else if (phase == TickEvent.Phase.END)
// tickEnd(side);
// }
//
// private void tickStart () {
// setFoodData(player.getFoodStats(), calcBaselineHunger(), 1);
// startHunger = player.getFoodStats().getFoodLevel();
// }
//
// private void tickEnd (Side side) {
// if (side == Side.SERVER) {
// int foodDiff = player.getFoodStats().getFoodLevel() - startHunger;
// if (foodDiff > 0)
// player.heal(foodDiff * (float)HungerStrike.instance.config.getFoodHealFactor());
// }
//
// setFoodData(player.getFoodStats(), calcBaselineHunger(), 1);
// }
//
// private void setFoodData (FoodStats foodStats, int foodLevel, float saturationLevel) {
// foodStats.addStats(1, (saturationLevel - foodStats.getSaturationLevel()) / 2);
// foodStats.addStats(foodLevel - foodStats.getFoodLevel(), 0);
// }
//
// private int calcBaselineHunger () {
// if (player.isPotionActive(Potion.hunger))
// return 5;
// else if (player.isPotionActive(Potion.regeneration))
// return 20;
// else
// return 10;
// }
// }
| import com.jaquadro.minecraft.hungerstrike.ExtendedPlayer;
import cpw.mods.fml.common.network.ByteBufUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound; | package com.jaquadro.minecraft.hungerstrike.network;
public class SyncExtendedPlayerPacket extends AbstractPacket
{
private NBTTagCompound data;
public SyncExtendedPlayerPacket () { }
public SyncExtendedPlayerPacket (EntityPlayer player) {
data = new NBTTagCompound(); | // Path: HungerStrike/src/com/jaquadro/minecraft/hungerstrike/ExtendedPlayer.java
// public class ExtendedPlayer implements IExtendedEntityProperties
// {
// public final static String TAG = "HungerStrike";
//
// private final EntityPlayer player;
//
// private boolean hungerStrikeEnabled;
// private int startHunger;
//
// public ExtendedPlayer(EntityPlayer player) {
// this.player = player;
// this.hungerStrikeEnabled = false;
// }
//
// public static final void register (EntityPlayer player) {
// player.registerExtendedProperties(TAG, new ExtendedPlayer(player));
// }
//
// public static final ExtendedPlayer get (EntityPlayer player) {
// return (ExtendedPlayer) player.getExtendedProperties(TAG);
// }
//
// @Override
// public void init(Entity entity, World world) { }
//
// @Override
// public void saveNBTData(NBTTagCompound compound) {
// NBTTagCompound properties = new NBTTagCompound();
// properties.setBoolean("Enabled", hungerStrikeEnabled);
//
// compound.setTag(TAG, properties);
// }
//
// @Override
// public void loadNBTData(NBTTagCompound compound) {
// NBTTagCompound properties = (NBTTagCompound) compound.getTag(TAG);
//
// hungerStrikeEnabled = properties.getBoolean("Enabled");
// }
//
// public void saveNBTDataSync (NBTTagCompound compound) {
// NBTTagCompound properties = new NBTTagCompound();
// properties.setBoolean("Enabled", hungerStrikeEnabled);
//
// compound.setTag(TAG, properties);
// }
//
// public void enableHungerStrike (boolean enable) {
// if (hungerStrikeEnabled != enable) {
// hungerStrikeEnabled = enable;
// if (player instanceof EntityPlayerMP)
// HungerStrike.packetPipeline.sendTo(new SyncExtendedPlayerPacket(player), (EntityPlayerMP)player);
// }
// }
//
// public boolean isOnHungerStrike () {
// return hungerStrikeEnabled;
// }
//
// /*public boolean getEffectiveHungerStrike () {
// if (!player.worldObj.isRemote)
// return hungerStrikeEnabled;
//
// switch (HungerStrike.config.getMode()) {
// case NONE:
// return false;
// case ALL:
// return true;
// case LIST:
// default:
// return hungerStrikeEnabled;
// }
// }*/
//
// private boolean shouldTick () {
// ConfigManager.Mode mode = HungerStrike.instance.config.getMode();
// if (mode == ConfigManager.Mode.LIST)
// return hungerStrikeEnabled;
// else
// return mode == ConfigManager.Mode.ALL;
// }
//
// public void tick (TickEvent.Phase phase, Side side) {
// if (!shouldTick())
// return;
//
// if (phase == TickEvent.Phase.START)
// tickStart();
// else if (phase == TickEvent.Phase.END)
// tickEnd(side);
// }
//
// private void tickStart () {
// setFoodData(player.getFoodStats(), calcBaselineHunger(), 1);
// startHunger = player.getFoodStats().getFoodLevel();
// }
//
// private void tickEnd (Side side) {
// if (side == Side.SERVER) {
// int foodDiff = player.getFoodStats().getFoodLevel() - startHunger;
// if (foodDiff > 0)
// player.heal(foodDiff * (float)HungerStrike.instance.config.getFoodHealFactor());
// }
//
// setFoodData(player.getFoodStats(), calcBaselineHunger(), 1);
// }
//
// private void setFoodData (FoodStats foodStats, int foodLevel, float saturationLevel) {
// foodStats.addStats(1, (saturationLevel - foodStats.getSaturationLevel()) / 2);
// foodStats.addStats(foodLevel - foodStats.getFoodLevel(), 0);
// }
//
// private int calcBaselineHunger () {
// if (player.isPotionActive(Potion.hunger))
// return 5;
// else if (player.isPotionActive(Potion.regeneration))
// return 20;
// else
// return 10;
// }
// }
// Path: HungerStrike/src/com/jaquadro/minecraft/hungerstrike/network/SyncExtendedPlayerPacket.java
import com.jaquadro.minecraft.hungerstrike.ExtendedPlayer;
import cpw.mods.fml.common.network.ByteBufUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
package com.jaquadro.minecraft.hungerstrike.network;
public class SyncExtendedPlayerPacket extends AbstractPacket
{
private NBTTagCompound data;
public SyncExtendedPlayerPacket () { }
public SyncExtendedPlayerPacket (EntityPlayer player) {
data = new NBTTagCompound(); | ExtendedPlayer ep = ExtendedPlayer.get(player); |
htwg/UCE | mediator/src/main/java/de/fhkn/in/uce/mediator/peerregistry/Endpoint.java | // Path: stun/src/main/java/de/fhkn/in/uce/stun/attribute/EndpointClass.java
// public static enum EndpointCategory {
// /**
// * Type of endpoint is undefined.
// */
// UNDEFINED(0x0),
// /**
// * Endpoint is a private endpoint (behind NAT).
// */
// PRIVATE(0x1),
// /**
// * Endpoint is a public endpoint (visible from outside).
// */
// PUBLIC(0x2),
// /**
// * Endpoint is an endpoint on a server for relaying data between client
// * and peer.
// */
// RELAY(0x3),
// /**
// * Endpoint is an endpoint for connection reversal.
// */
// CONNECTION_REVERSAL(0x4);
//
// private static final Map<Integer, EndpointCategory> intToEnum = new HashMap<Integer, EndpointCategory>();
//
// static {
// for (final EndpointCategory l : values()) {
// intToEnum.put(l.encoded, l);
// }
// }
//
// private final int encoded;
//
// /**
// * Creates a new {@link EndpointClass}.
// *
// * @param encoded
// * the encoded representation of the endpoint.
// */
// private EndpointCategory(final int encoded) {
// this.encoded = encoded;
// }
//
// /**
// * Returns the byte encoded {@link EndpointClass}.
// *
// * @return
// */
// int encode() {
// return this.encoded;
// }
//
// /**
// * Decodes the {@link EndpointClass}.
// *
// * @param encoded
// * the byte encoded {@link EndpointClass}
// * @return the decoded {@link EndpointClass}
// */
// private static EndpointCategory fromEncoded(final int encoded) {
// return intToEnum.get(encoded);
// }
// }
| import java.net.InetSocketAddress;
import net.jcip.annotations.Immutable;
import de.fhkn.in.uce.stun.attribute.EndpointClass.EndpointCategory;
| /*
* Copyright (c) 2012 Alexander Diener,
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.fhkn.in.uce.mediator.peerregistry;
/**
* The class represents an endpoint which consists of an endpoint address and an
* endpoint category.
*
* @author Alexander Diener (aldiener@htwg-konstanz.de)
*
*/
@Immutable
public final class Endpoint {
private final InetSocketAddress endpointAddress;
| // Path: stun/src/main/java/de/fhkn/in/uce/stun/attribute/EndpointClass.java
// public static enum EndpointCategory {
// /**
// * Type of endpoint is undefined.
// */
// UNDEFINED(0x0),
// /**
// * Endpoint is a private endpoint (behind NAT).
// */
// PRIVATE(0x1),
// /**
// * Endpoint is a public endpoint (visible from outside).
// */
// PUBLIC(0x2),
// /**
// * Endpoint is an endpoint on a server for relaying data between client
// * and peer.
// */
// RELAY(0x3),
// /**
// * Endpoint is an endpoint for connection reversal.
// */
// CONNECTION_REVERSAL(0x4);
//
// private static final Map<Integer, EndpointCategory> intToEnum = new HashMap<Integer, EndpointCategory>();
//
// static {
// for (final EndpointCategory l : values()) {
// intToEnum.put(l.encoded, l);
// }
// }
//
// private final int encoded;
//
// /**
// * Creates a new {@link EndpointClass}.
// *
// * @param encoded
// * the encoded representation of the endpoint.
// */
// private EndpointCategory(final int encoded) {
// this.encoded = encoded;
// }
//
// /**
// * Returns the byte encoded {@link EndpointClass}.
// *
// * @return
// */
// int encode() {
// return this.encoded;
// }
//
// /**
// * Decodes the {@link EndpointClass}.
// *
// * @param encoded
// * the byte encoded {@link EndpointClass}
// * @return the decoded {@link EndpointClass}
// */
// private static EndpointCategory fromEncoded(final int encoded) {
// return intToEnum.get(encoded);
// }
// }
// Path: mediator/src/main/java/de/fhkn/in/uce/mediator/peerregistry/Endpoint.java
import java.net.InetSocketAddress;
import net.jcip.annotations.Immutable;
import de.fhkn.in.uce.stun.attribute.EndpointClass.EndpointCategory;
/*
* Copyright (c) 2012 Alexander Diener,
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.fhkn.in.uce.mediator.peerregistry;
/**
* The class represents an endpoint which consists of an endpoint address and an
* endpoint category.
*
* @author Alexander Diener (aldiener@htwg-konstanz.de)
*
*/
@Immutable
public final class Endpoint {
private final InetSocketAddress endpointAddress;
| private final EndpointCategory category;
|
htwg/UCE | connectivitymanager/src/main/java/de/fhkn/in/uce/connectivitymanager/selector/decisiontree/NATTraversalRule.java | // Path: plugininterface/src/main/java/de/fhkn/in/uce/plugininterface/NATSituation.java
// @Immutable
// public final class NATSituation {
// private final NATBehavior clientNat;
// private final NATBehavior serviceNat;
//
// /**
// * Creates a unknown {@link NATSituation}.
// */
// public NATSituation() {
// this.clientNat = new NATBehavior();
// this.serviceNat = new NATBehavior();
// }
//
// /**
// * Creates a {@link NATSituation} with the given client and server
// * {@link NATBehavior}.
// *
// * @param clientNat
// * the {@link NATBehavior} of the client
// * @param serviceNat
// * the {@link NATBehavior} of the server
// */
// public NATSituation(final NATBehavior clientNat, final NATBehavior serviceNat) {
// this.clientNat = clientNat;
// this.serviceNat = serviceNat;
// }
//
// /**
// * Creates a {@link NATSituation} with the given client and server
// * {@link NATFeatureRealization}s.
// *
// * @param clientMapping
// * the {@link NATFeatureRealization} for the client NAT mapping
// *
// * @param clientFiltering
// * the {@link NATFeatureRealization} for the client NAT filtering
// * @param serviceMapping
// * the {@link NATFeatureRealization} for the server NAT mapping
// * @param serviceFiltering
// * the {@link NATFeatureRealization} for the server NAT filtering
// */
// public NATSituation(final NATFeatureRealization clientMapping, final NATFeatureRealization clientFiltering,
// final NATFeatureRealization serviceMapping, final NATFeatureRealization serviceFiltering) {
// this(new NATBehavior(clientMapping, clientFiltering), new NATBehavior(serviceMapping, serviceFiltering));
// }
//
// /**
// * Returns the {@link NATBehavior} of the client NAT.
// *
// * @return the {@link NATBehavior} of the client NAT
// */
// public NATBehavior getClientNATBehavior() {
// return this.clientNat;
// }
//
// /**
// * Returns the {@link NATBehavior} of the server NAT.
// *
// * @return the {@link NATBehavior} of the server NAT
// */
// public NATBehavior getServiceNATBehavior() {
// return this.serviceNat;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = (prime * result) + ((this.clientNat == null) ? 0 : this.clientNat.hashCode());
// result = (prime * result) + ((this.serviceNat == null) ? 0 : this.serviceNat.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(final Object obj) {
// if (null == obj) {
// return false;
// }
// if (!(obj instanceof NATSituation)) {
// return false;
// }
// final NATSituation other = (NATSituation) obj;
//
// final NATFeatureRealization thisClientMapping = this.clientNat.getFeatureRealization(NATFeature.MAPPING);
// final NATFeatureRealization thisClientFiltering = this.clientNat.getFeatureRealization(NATFeature.FILTERING);
// final NATFeatureRealization thisServiceMapping = this.serviceNat.getFeatureRealization(NATFeature.MAPPING);
// final NATFeatureRealization thisServiceFiltering = this.serviceNat.getFeatureRealization(NATFeature.FILTERING);
//
// final NATFeatureRealization otherClientMapping = other.getClientNATBehavior().getFeatureRealization(
// NATFeature.MAPPING);
// final NATFeatureRealization otherClientFiltering = other.getClientNATBehavior().getFeatureRealization(
// NATFeature.FILTERING);
// final NATFeatureRealization otherServiceMapping = other.getServiceNATBehavior().getFeatureRealization(
// NATFeature.MAPPING);
// final NATFeatureRealization otherServiceFiltering = other.getServiceNATBehavior().getFeatureRealization(
// NATFeature.FILTERING);
//
// if (thisClientMapping.equals(otherClientMapping) && thisClientFiltering.equals(otherClientFiltering)
// && thisServiceMapping.equals(otherServiceMapping) && thisServiceFiltering.equals(otherServiceFiltering)) {
// return true;
// }
// return false;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("NATSituation=");
// sb.append("client");
// sb.append(this.clientNat.toString());
// sb.append("service");
// sb.append(this.serviceNat.toString());
// return sb.toString();
// }
// }
| import java.util.Collections;
import java.util.List;
import net.jcip.annotations.Immutable;
import de.fhkn.in.uce.plugininterface.NATSituation;
import de.fhkn.in.uce.plugininterface.NATTraversalTechnique;
| /*
Copyright (c) 2012 Alexander Diener,
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.fhkn.in.uce.connectivitymanager.selector.decisiontree;
/**
* A {@code NATTraversalRule} represents a NAT situation and the appropriate NAT
* traversal techniques which can be used to traverse the described NAT device.
* The scope of this class is to provide a rule for learning decision trees to
* generate a tree out of {@code NATTraversalRule}s.
*
* @author Alexander Diener (aldiener@htwg-konstanz.de)
*
*/
@Immutable
public final class NATTraversalRule {
| // Path: plugininterface/src/main/java/de/fhkn/in/uce/plugininterface/NATSituation.java
// @Immutable
// public final class NATSituation {
// private final NATBehavior clientNat;
// private final NATBehavior serviceNat;
//
// /**
// * Creates a unknown {@link NATSituation}.
// */
// public NATSituation() {
// this.clientNat = new NATBehavior();
// this.serviceNat = new NATBehavior();
// }
//
// /**
// * Creates a {@link NATSituation} with the given client and server
// * {@link NATBehavior}.
// *
// * @param clientNat
// * the {@link NATBehavior} of the client
// * @param serviceNat
// * the {@link NATBehavior} of the server
// */
// public NATSituation(final NATBehavior clientNat, final NATBehavior serviceNat) {
// this.clientNat = clientNat;
// this.serviceNat = serviceNat;
// }
//
// /**
// * Creates a {@link NATSituation} with the given client and server
// * {@link NATFeatureRealization}s.
// *
// * @param clientMapping
// * the {@link NATFeatureRealization} for the client NAT mapping
// *
// * @param clientFiltering
// * the {@link NATFeatureRealization} for the client NAT filtering
// * @param serviceMapping
// * the {@link NATFeatureRealization} for the server NAT mapping
// * @param serviceFiltering
// * the {@link NATFeatureRealization} for the server NAT filtering
// */
// public NATSituation(final NATFeatureRealization clientMapping, final NATFeatureRealization clientFiltering,
// final NATFeatureRealization serviceMapping, final NATFeatureRealization serviceFiltering) {
// this(new NATBehavior(clientMapping, clientFiltering), new NATBehavior(serviceMapping, serviceFiltering));
// }
//
// /**
// * Returns the {@link NATBehavior} of the client NAT.
// *
// * @return the {@link NATBehavior} of the client NAT
// */
// public NATBehavior getClientNATBehavior() {
// return this.clientNat;
// }
//
// /**
// * Returns the {@link NATBehavior} of the server NAT.
// *
// * @return the {@link NATBehavior} of the server NAT
// */
// public NATBehavior getServiceNATBehavior() {
// return this.serviceNat;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = (prime * result) + ((this.clientNat == null) ? 0 : this.clientNat.hashCode());
// result = (prime * result) + ((this.serviceNat == null) ? 0 : this.serviceNat.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(final Object obj) {
// if (null == obj) {
// return false;
// }
// if (!(obj instanceof NATSituation)) {
// return false;
// }
// final NATSituation other = (NATSituation) obj;
//
// final NATFeatureRealization thisClientMapping = this.clientNat.getFeatureRealization(NATFeature.MAPPING);
// final NATFeatureRealization thisClientFiltering = this.clientNat.getFeatureRealization(NATFeature.FILTERING);
// final NATFeatureRealization thisServiceMapping = this.serviceNat.getFeatureRealization(NATFeature.MAPPING);
// final NATFeatureRealization thisServiceFiltering = this.serviceNat.getFeatureRealization(NATFeature.FILTERING);
//
// final NATFeatureRealization otherClientMapping = other.getClientNATBehavior().getFeatureRealization(
// NATFeature.MAPPING);
// final NATFeatureRealization otherClientFiltering = other.getClientNATBehavior().getFeatureRealization(
// NATFeature.FILTERING);
// final NATFeatureRealization otherServiceMapping = other.getServiceNATBehavior().getFeatureRealization(
// NATFeature.MAPPING);
// final NATFeatureRealization otherServiceFiltering = other.getServiceNATBehavior().getFeatureRealization(
// NATFeature.FILTERING);
//
// if (thisClientMapping.equals(otherClientMapping) && thisClientFiltering.equals(otherClientFiltering)
// && thisServiceMapping.equals(otherServiceMapping) && thisServiceFiltering.equals(otherServiceFiltering)) {
// return true;
// }
// return false;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("NATSituation=");
// sb.append("client");
// sb.append(this.clientNat.toString());
// sb.append("service");
// sb.append(this.serviceNat.toString());
// return sb.toString();
// }
// }
// Path: connectivitymanager/src/main/java/de/fhkn/in/uce/connectivitymanager/selector/decisiontree/NATTraversalRule.java
import java.util.Collections;
import java.util.List;
import net.jcip.annotations.Immutable;
import de.fhkn.in.uce.plugininterface.NATSituation;
import de.fhkn.in.uce.plugininterface.NATTraversalTechnique;
/*
Copyright (c) 2012 Alexander Diener,
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.fhkn.in.uce.connectivitymanager.selector.decisiontree;
/**
* A {@code NATTraversalRule} represents a NAT situation and the appropriate NAT
* traversal techniques which can be used to traverse the described NAT device.
* The scope of this class is to provide a rule for learning decision trees to
* generate a tree out of {@code NATTraversalRule}s.
*
* @author Alexander Diener (aldiener@htwg-konstanz.de)
*
*/
@Immutable
public final class NATTraversalRule {
| private final NATSituation natSituation;
|
htwg/UCE | master.server/src/test/java/de/fhkn/in/uce/master/server/MasterServerTest.java | // Path: master.server/src/main/java/de/fhkn/in/uce/master/server/MasterServer.java
// public class MasterServer {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(MasterServer.class);
//
// private final int executorThreads = 3;
// private final int terminationTime = 100;
//
// private final ExecutorService executorService;
// private ArgumentHandler argHandler;
//
// /**
// * Creates a master server.
// */
// public MasterServer() {
// executorService = Executors.newFixedThreadPool(executorThreads);
// argHandler = new ArgumentHandler(LOGGER);
// }
//
// /**
// * Main method to create and start the master server.
// *
// * @param args
// * command line arguments.
// */
// public static void main(final String[] args) {
// MasterServer masterServer = new MasterServer();
// try {
// masterServer.run(args);
// } catch (Exception e) {
// LOGGER.error("An error occured during startup of the master server.");
// LOGGER.error("Execption: ", e);
// e.printStackTrace();
// }
// }
//
// /**
// * Starts the master server and its children stun, relay and mediator.
// *
// * @param args
// * command line arguments.
// */
// public void run(final String[] args) {
// try {
// argHandler.parseArguments(args);
// } catch (IllegalArgumentException e) {
// return;
// }
//
// stunServerTask();
// relayServerTask();
// mediatorServerTask();
//
// //sleep one second before shuting down the executors
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// //do nothing
// }
// shutdownExecutor();
// }
//
// private void shutdownExecutor() {
// logInfo("Shutting down executor threads.");
// try {
// executorService.shutdown();
// logInfo("Trying to force shutting down worker threads in " + terminationTime + "ms.");
// if (!executorService.awaitTermination(terminationTime, TimeUnit.MILLISECONDS)) {
// logInfo("Force now to shutdown worker threads.");
// executorService.shutdownNow();
// }
// } catch (Exception e) {
// executorService.shutdown();
// Thread.currentThread().interrupt();
// }
// }
//
// private void logInfo(final String msg) {
// System.out.println(msg);
// LOGGER.info(msg);
// }
//
// private void relayServerTask() {
// logInfo("Starting Relay Server");
// executorService.submit(new Runnable() {
// @Override
// public void run() {
// try {
// List<String> relayArgs = argHandler.getRelayArgs();
// RelayServer.main(relayArgs.toArray(new String[relayArgs.size()]));
// logInfo("Successfully started Relay Server");
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// });
// }
//
// private void stunServerTask() {
// logInfo("Starting Stun Server");
// executorService.submit(new Runnable() {
// @Override
// public void run() {
// List<String> stunArgs = argHandler.getStunArgs();
// StunServer.main(stunArgs.toArray(new String[stunArgs.size()]));
// logInfo("Successfully started Stun Server");
// }
// });
// }
//
// private void mediatorServerTask() {
// logInfo("Starting Mediator Server");
// executorService.submit(new Runnable() {
// @Override
// public void run() {
// try {
// List<String> mediatorArgs = argHandler.getMediatorArgs();
// Mediator.main(mediatorArgs.toArray(new String[mediatorArgs.size()]));
// logInfo("Successfully started Mediator Server");
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// });
// }
// }
| import org.junit.Test;
import de.fhkn.in.uce.master.server.MasterServer; | package de.fhkn.in.uce.master.server;
public class MasterServerTest {
/**
* Test method for
* {@link MasterServer#run(String[])} with no arguments in file, system and command line.
*/
@Test
public final void testRun() {
String[] args = {""}; | // Path: master.server/src/main/java/de/fhkn/in/uce/master/server/MasterServer.java
// public class MasterServer {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(MasterServer.class);
//
// private final int executorThreads = 3;
// private final int terminationTime = 100;
//
// private final ExecutorService executorService;
// private ArgumentHandler argHandler;
//
// /**
// * Creates a master server.
// */
// public MasterServer() {
// executorService = Executors.newFixedThreadPool(executorThreads);
// argHandler = new ArgumentHandler(LOGGER);
// }
//
// /**
// * Main method to create and start the master server.
// *
// * @param args
// * command line arguments.
// */
// public static void main(final String[] args) {
// MasterServer masterServer = new MasterServer();
// try {
// masterServer.run(args);
// } catch (Exception e) {
// LOGGER.error("An error occured during startup of the master server.");
// LOGGER.error("Execption: ", e);
// e.printStackTrace();
// }
// }
//
// /**
// * Starts the master server and its children stun, relay and mediator.
// *
// * @param args
// * command line arguments.
// */
// public void run(final String[] args) {
// try {
// argHandler.parseArguments(args);
// } catch (IllegalArgumentException e) {
// return;
// }
//
// stunServerTask();
// relayServerTask();
// mediatorServerTask();
//
// //sleep one second before shuting down the executors
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// //do nothing
// }
// shutdownExecutor();
// }
//
// private void shutdownExecutor() {
// logInfo("Shutting down executor threads.");
// try {
// executorService.shutdown();
// logInfo("Trying to force shutting down worker threads in " + terminationTime + "ms.");
// if (!executorService.awaitTermination(terminationTime, TimeUnit.MILLISECONDS)) {
// logInfo("Force now to shutdown worker threads.");
// executorService.shutdownNow();
// }
// } catch (Exception e) {
// executorService.shutdown();
// Thread.currentThread().interrupt();
// }
// }
//
// private void logInfo(final String msg) {
// System.out.println(msg);
// LOGGER.info(msg);
// }
//
// private void relayServerTask() {
// logInfo("Starting Relay Server");
// executorService.submit(new Runnable() {
// @Override
// public void run() {
// try {
// List<String> relayArgs = argHandler.getRelayArgs();
// RelayServer.main(relayArgs.toArray(new String[relayArgs.size()]));
// logInfo("Successfully started Relay Server");
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// });
// }
//
// private void stunServerTask() {
// logInfo("Starting Stun Server");
// executorService.submit(new Runnable() {
// @Override
// public void run() {
// List<String> stunArgs = argHandler.getStunArgs();
// StunServer.main(stunArgs.toArray(new String[stunArgs.size()]));
// logInfo("Successfully started Stun Server");
// }
// });
// }
//
// private void mediatorServerTask() {
// logInfo("Starting Mediator Server");
// executorService.submit(new Runnable() {
// @Override
// public void run() {
// try {
// List<String> mediatorArgs = argHandler.getMediatorArgs();
// Mediator.main(mediatorArgs.toArray(new String[mediatorArgs.size()]));
// logInfo("Successfully started Mediator Server");
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// });
// }
// }
// Path: master.server/src/test/java/de/fhkn/in/uce/master/server/MasterServerTest.java
import org.junit.Test;
import de.fhkn.in.uce.master.server.MasterServer;
package de.fhkn.in.uce.master.server;
public class MasterServerTest {
/**
* Test method for
* {@link MasterServer#run(String[])} with no arguments in file, system and command line.
*/
@Test
public final void testRun() {
String[] args = {""}; | MasterServer server = new MasterServer(); |
delving/x3ml | src/main/java/eu/delving/x3ml/engine/Root.java | // Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
| import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.xml.namespace.NamespaceContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The root of the mapping is where the domain contexts are created. They then
* fabricate path contexts which in turn make range contexts.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class Root {
private final Element rootNode;
private final ModelOutput modelOutput;
private final XPathInput xpathInput;
private final Context context;
| // Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
// Path: src/main/java/eu/delving/x3ml/engine/Root.java
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.xml.namespace.NamespaceContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The root of the mapping is where the domain contexts are created. They then
* fabricate path contexts which in turn make range contexts.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class Root {
private final Element rootNode;
private final ModelOutput modelOutput;
private final XPathInput xpathInput;
private final Context context;
| private final Map<String, GeneratedValue> generated = new HashMap<String, GeneratedValue>();
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/GeneratorContext.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("if")
// public static class Condition extends Visible {
//
// public Narrower narrower;
// public Exists exists;
// public Equals equals;
// public AndCondition and;
// public OrCondition or;
// public NotCondition not;
//
// private static class Outcome {
//
// final GeneratorContext context;
// boolean failure;
//
// private Outcome(GeneratorContext context) {
// this.context = context;
// }
//
// Outcome evaluate(YesOrNo yesOrNo) {
// if (yesOrNo != null && !failure && !yesOrNo.yes(context)) {
// failure = true;
// }
// return this;
// }
// }
//
// public boolean failure(GeneratorContext context) {
// return new Outcome(context)
// .evaluate(narrower)
// .evaluate(exists)
// .evaluate(equals)
// .evaluate(and)
// .evaluate(or)
// .evaluate(not).failure;
// }
//
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
| import org.w3c.dom.Node;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.Condition;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.SourceType;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* This abstract class is above Domain, Path, and Range and carries most of
* their contextual information.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public abstract class GeneratorContext {
public final Root.Context context;
public final GeneratorContext parent;
public final Node node;
public final int index;
protected GeneratorContext(Root.Context context, GeneratorContext parent, Node node, int index) {
this.context = context;
this.parent = parent;
this.node = node;
this.index = index;
}
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("if")
// public static class Condition extends Visible {
//
// public Narrower narrower;
// public Exists exists;
// public Equals equals;
// public AndCondition and;
// public OrCondition or;
// public NotCondition not;
//
// private static class Outcome {
//
// final GeneratorContext context;
// boolean failure;
//
// private Outcome(GeneratorContext context) {
// this.context = context;
// }
//
// Outcome evaluate(YesOrNo yesOrNo) {
// if (yesOrNo != null && !failure && !yesOrNo.yes(context)) {
// failure = true;
// }
// return this;
// }
// }
//
// public boolean failure(GeneratorContext context) {
// return new Outcome(context)
// .evaluate(narrower)
// .evaluate(exists)
// .evaluate(equals)
// .evaluate(and)
// .evaluate(or)
// .evaluate(not).failure;
// }
//
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
// Path: src/main/java/eu/delving/x3ml/engine/GeneratorContext.java
import org.w3c.dom.Node;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.Condition;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.SourceType;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* This abstract class is above Domain, Path, and Range and carries most of
* their contextual information.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public abstract class GeneratorContext {
public final Root.Context context;
public final GeneratorContext parent;
public final Node node;
public final int index;
protected GeneratorContext(Root.Context context, GeneratorContext parent, Node node, int index) {
this.context = context;
this.parent = parent;
this.node = node;
this.index = index;
}
| public GeneratedValue get(String variable) {
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/GeneratorContext.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("if")
// public static class Condition extends Visible {
//
// public Narrower narrower;
// public Exists exists;
// public Equals equals;
// public AndCondition and;
// public OrCondition or;
// public NotCondition not;
//
// private static class Outcome {
//
// final GeneratorContext context;
// boolean failure;
//
// private Outcome(GeneratorContext context) {
// this.context = context;
// }
//
// Outcome evaluate(YesOrNo yesOrNo) {
// if (yesOrNo != null && !failure && !yesOrNo.yes(context)) {
// failure = true;
// }
// return this;
// }
// }
//
// public boolean failure(GeneratorContext context) {
// return new Outcome(context)
// .evaluate(narrower)
// .evaluate(exists)
// .evaluate(equals)
// .evaluate(and)
// .evaluate(or)
// .evaluate(not).failure;
// }
//
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
| import org.w3c.dom.Node;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.Condition;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.SourceType;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* This abstract class is above Domain, Path, and Range and carries most of
* their contextual information.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public abstract class GeneratorContext {
public final Root.Context context;
public final GeneratorContext parent;
public final Node node;
public final int index;
protected GeneratorContext(Root.Context context, GeneratorContext parent, Node node, int index) {
this.context = context;
this.parent = parent;
this.node = node;
this.index = index;
}
public GeneratedValue get(String variable) {
if (parent == null) {
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("if")
// public static class Condition extends Visible {
//
// public Narrower narrower;
// public Exists exists;
// public Equals equals;
// public AndCondition and;
// public OrCondition or;
// public NotCondition not;
//
// private static class Outcome {
//
// final GeneratorContext context;
// boolean failure;
//
// private Outcome(GeneratorContext context) {
// this.context = context;
// }
//
// Outcome evaluate(YesOrNo yesOrNo) {
// if (yesOrNo != null && !failure && !yesOrNo.yes(context)) {
// failure = true;
// }
// return this;
// }
// }
//
// public boolean failure(GeneratorContext context) {
// return new Outcome(context)
// .evaluate(narrower)
// .evaluate(exists)
// .evaluate(equals)
// .evaluate(and)
// .evaluate(or)
// .evaluate(not).failure;
// }
//
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
// Path: src/main/java/eu/delving/x3ml/engine/GeneratorContext.java
import org.w3c.dom.Node;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.Condition;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.SourceType;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* This abstract class is above Domain, Path, and Range and carries most of
* their contextual information.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public abstract class GeneratorContext {
public final Root.Context context;
public final GeneratorContext parent;
public final Node node;
public final int index;
protected GeneratorContext(Root.Context context, GeneratorContext parent, Node node, int index) {
this.context = context;
this.parent = parent;
this.node = node;
this.index = index;
}
public GeneratedValue get(String variable) {
if (parent == null) {
| throw exception("Parent context missing");
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/GeneratorContext.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("if")
// public static class Condition extends Visible {
//
// public Narrower narrower;
// public Exists exists;
// public Equals equals;
// public AndCondition and;
// public OrCondition or;
// public NotCondition not;
//
// private static class Outcome {
//
// final GeneratorContext context;
// boolean failure;
//
// private Outcome(GeneratorContext context) {
// this.context = context;
// }
//
// Outcome evaluate(YesOrNo yesOrNo) {
// if (yesOrNo != null && !failure && !yesOrNo.yes(context)) {
// failure = true;
// }
// return this;
// }
// }
//
// public boolean failure(GeneratorContext context) {
// return new Outcome(context)
// .evaluate(narrower)
// .evaluate(exists)
// .evaluate(equals)
// .evaluate(and)
// .evaluate(or)
// .evaluate(not).failure;
// }
//
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
| import org.w3c.dom.Node;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.Condition;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.SourceType;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* This abstract class is above Domain, Path, and Range and carries most of
* their contextual information.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public abstract class GeneratorContext {
public final Root.Context context;
public final GeneratorContext parent;
public final Node node;
public final int index;
protected GeneratorContext(Root.Context context, GeneratorContext parent, Node node, int index) {
this.context = context;
this.parent = parent;
this.node = node;
this.index = index;
}
public GeneratedValue get(String variable) {
if (parent == null) {
throw exception("Parent context missing");
}
return parent.get(variable);
}
public void put(String variable, GeneratedValue generatedValue) {
if (parent == null) {
throw exception("Parent context missing");
}
parent.put(variable, generatedValue);
}
public String evaluate(String expression) {
return context.input().valueAt(node, expression);
}
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("if")
// public static class Condition extends Visible {
//
// public Narrower narrower;
// public Exists exists;
// public Equals equals;
// public AndCondition and;
// public OrCondition or;
// public NotCondition not;
//
// private static class Outcome {
//
// final GeneratorContext context;
// boolean failure;
//
// private Outcome(GeneratorContext context) {
// this.context = context;
// }
//
// Outcome evaluate(YesOrNo yesOrNo) {
// if (yesOrNo != null && !failure && !yesOrNo.yes(context)) {
// failure = true;
// }
// return this;
// }
// }
//
// public boolean failure(GeneratorContext context) {
// return new Outcome(context)
// .evaluate(narrower)
// .evaluate(exists)
// .evaluate(equals)
// .evaluate(and)
// .evaluate(or)
// .evaluate(not).failure;
// }
//
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
// Path: src/main/java/eu/delving/x3ml/engine/GeneratorContext.java
import org.w3c.dom.Node;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.Condition;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.SourceType;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* This abstract class is above Domain, Path, and Range and carries most of
* their contextual information.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public abstract class GeneratorContext {
public final Root.Context context;
public final GeneratorContext parent;
public final Node node;
public final int index;
protected GeneratorContext(Root.Context context, GeneratorContext parent, Node node, int index) {
this.context = context;
this.parent = parent;
this.node = node;
this.index = index;
}
public GeneratedValue get(String variable) {
if (parent == null) {
throw exception("Parent context missing");
}
return parent.get(variable);
}
public void put(String variable, GeneratedValue generatedValue) {
if (parent == null) {
throw exception("Parent context missing");
}
parent.put(variable, generatedValue);
}
public String evaluate(String expression) {
return context.input().valueAt(node, expression);
}
| public GeneratedValue getInstance(final GeneratorElement generator, String variable, String unique) {
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/GeneratorContext.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("if")
// public static class Condition extends Visible {
//
// public Narrower narrower;
// public Exists exists;
// public Equals equals;
// public AndCondition and;
// public OrCondition or;
// public NotCondition not;
//
// private static class Outcome {
//
// final GeneratorContext context;
// boolean failure;
//
// private Outcome(GeneratorContext context) {
// this.context = context;
// }
//
// Outcome evaluate(YesOrNo yesOrNo) {
// if (yesOrNo != null && !failure && !yesOrNo.yes(context)) {
// failure = true;
// }
// return this;
// }
// }
//
// public boolean failure(GeneratorContext context) {
// return new Outcome(context)
// .evaluate(narrower)
// .evaluate(exists)
// .evaluate(equals)
// .evaluate(and)
// .evaluate(or)
// .evaluate(not).failure;
// }
//
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
| import org.w3c.dom.Node;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.Condition;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.SourceType;
| }
public GeneratedValue get(String variable) {
if (parent == null) {
throw exception("Parent context missing");
}
return parent.get(variable);
}
public void put(String variable, GeneratedValue generatedValue) {
if (parent == null) {
throw exception("Parent context missing");
}
parent.put(variable, generatedValue);
}
public String evaluate(String expression) {
return context.input().valueAt(node, expression);
}
public GeneratedValue getInstance(final GeneratorElement generator, String variable, String unique) {
if (generator == null) {
throw exception("Value generator missing");
}
GeneratedValue generatedValue;
if (variable != null) {
generatedValue = get(variable);
if (generatedValue == null) {
generatedValue = context.policy().generate(generator.name, new Generator.ArgValues() {
@Override
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("if")
// public static class Condition extends Visible {
//
// public Narrower narrower;
// public Exists exists;
// public Equals equals;
// public AndCondition and;
// public OrCondition or;
// public NotCondition not;
//
// private static class Outcome {
//
// final GeneratorContext context;
// boolean failure;
//
// private Outcome(GeneratorContext context) {
// this.context = context;
// }
//
// Outcome evaluate(YesOrNo yesOrNo) {
// if (yesOrNo != null && !failure && !yesOrNo.yes(context)) {
// failure = true;
// }
// return this;
// }
// }
//
// public boolean failure(GeneratorContext context) {
// return new Outcome(context)
// .evaluate(narrower)
// .evaluate(exists)
// .evaluate(equals)
// .evaluate(and)
// .evaluate(or)
// .evaluate(not).failure;
// }
//
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
// Path: src/main/java/eu/delving/x3ml/engine/GeneratorContext.java
import org.w3c.dom.Node;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.Condition;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.SourceType;
}
public GeneratedValue get(String variable) {
if (parent == null) {
throw exception("Parent context missing");
}
return parent.get(variable);
}
public void put(String variable, GeneratedValue generatedValue) {
if (parent == null) {
throw exception("Parent context missing");
}
parent.put(variable, generatedValue);
}
public String evaluate(String expression) {
return context.input().valueAt(node, expression);
}
public GeneratedValue getInstance(final GeneratorElement generator, String variable, String unique) {
if (generator == null) {
throw exception("Value generator missing");
}
GeneratedValue generatedValue;
if (variable != null) {
generatedValue = get(variable);
if (generatedValue == null) {
generatedValue = context.policy().generate(generator.name, new Generator.ArgValues() {
@Override
| public ArgValue getArgValue(String name, SourceType sourceType) {
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/GeneratorContext.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("if")
// public static class Condition extends Visible {
//
// public Narrower narrower;
// public Exists exists;
// public Equals equals;
// public AndCondition and;
// public OrCondition or;
// public NotCondition not;
//
// private static class Outcome {
//
// final GeneratorContext context;
// boolean failure;
//
// private Outcome(GeneratorContext context) {
// this.context = context;
// }
//
// Outcome evaluate(YesOrNo yesOrNo) {
// if (yesOrNo != null && !failure && !yesOrNo.yes(context)) {
// failure = true;
// }
// return this;
// }
// }
//
// public boolean failure(GeneratorContext context) {
// return new Outcome(context)
// .evaluate(narrower)
// .evaluate(exists)
// .evaluate(equals)
// .evaluate(and)
// .evaluate(or)
// .evaluate(not).failure;
// }
//
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
| import org.w3c.dom.Node;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.Condition;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.SourceType;
| }
public GeneratedValue get(String variable) {
if (parent == null) {
throw exception("Parent context missing");
}
return parent.get(variable);
}
public void put(String variable, GeneratedValue generatedValue) {
if (parent == null) {
throw exception("Parent context missing");
}
parent.put(variable, generatedValue);
}
public String evaluate(String expression) {
return context.input().valueAt(node, expression);
}
public GeneratedValue getInstance(final GeneratorElement generator, String variable, String unique) {
if (generator == null) {
throw exception("Value generator missing");
}
GeneratedValue generatedValue;
if (variable != null) {
generatedValue = get(variable);
if (generatedValue == null) {
generatedValue = context.policy().generate(generator.name, new Generator.ArgValues() {
@Override
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("if")
// public static class Condition extends Visible {
//
// public Narrower narrower;
// public Exists exists;
// public Equals equals;
// public AndCondition and;
// public OrCondition or;
// public NotCondition not;
//
// private static class Outcome {
//
// final GeneratorContext context;
// boolean failure;
//
// private Outcome(GeneratorContext context) {
// this.context = context;
// }
//
// Outcome evaluate(YesOrNo yesOrNo) {
// if (yesOrNo != null && !failure && !yesOrNo.yes(context)) {
// failure = true;
// }
// return this;
// }
// }
//
// public boolean failure(GeneratorContext context) {
// return new Outcome(context)
// .evaluate(narrower)
// .evaluate(exists)
// .evaluate(equals)
// .evaluate(and)
// .evaluate(or)
// .evaluate(not).failure;
// }
//
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
// Path: src/main/java/eu/delving/x3ml/engine/GeneratorContext.java
import org.w3c.dom.Node;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.Condition;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.SourceType;
}
public GeneratedValue get(String variable) {
if (parent == null) {
throw exception("Parent context missing");
}
return parent.get(variable);
}
public void put(String variable, GeneratedValue generatedValue) {
if (parent == null) {
throw exception("Parent context missing");
}
parent.put(variable, generatedValue);
}
public String evaluate(String expression) {
return context.input().valueAt(node, expression);
}
public GeneratedValue getInstance(final GeneratorElement generator, String variable, String unique) {
if (generator == null) {
throw exception("Value generator missing");
}
GeneratedValue generatedValue;
if (variable != null) {
generatedValue = get(variable);
if (generatedValue == null) {
generatedValue = context.policy().generate(generator.name, new Generator.ArgValues() {
@Override
| public ArgValue getArgValue(String name, SourceType sourceType) {
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/GeneratorContext.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("if")
// public static class Condition extends Visible {
//
// public Narrower narrower;
// public Exists exists;
// public Equals equals;
// public AndCondition and;
// public OrCondition or;
// public NotCondition not;
//
// private static class Outcome {
//
// final GeneratorContext context;
// boolean failure;
//
// private Outcome(GeneratorContext context) {
// this.context = context;
// }
//
// Outcome evaluate(YesOrNo yesOrNo) {
// if (yesOrNo != null && !failure && !yesOrNo.yes(context)) {
// failure = true;
// }
// return this;
// }
// }
//
// public boolean failure(GeneratorContext context) {
// return new Outcome(context)
// .evaluate(narrower)
// .evaluate(exists)
// .evaluate(equals)
// .evaluate(and)
// .evaluate(or)
// .evaluate(not).failure;
// }
//
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
| import org.w3c.dom.Node;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.Condition;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.SourceType;
| });
put(variable, generatedValue);
// System.out.println(generator.variable + " ===VAR==> " + generatedValue);
}
// else {
// System.out.println(generator.variable + " <==VAR=== " + generatedValue);
// }
} else {
String nodeName = extractXPath(node) + unique;
generatedValue = context.getGeneratedValue(nodeName);
if (generatedValue == null) {
generatedValue = context.policy().generate(generator.name, new Generator.ArgValues() {
@Override
public ArgValue getArgValue(String name, SourceType sourceType) {
return context.input().evaluateArgument(node, index, generator, name, sourceType);
}
});
context.putGeneratedValue(nodeName, generatedValue);
// System.out.println(nodeName + " ===CTX==> " + generatedValue);
}
// else {
// System.out.println(nodeName + " <==CTX=== " + generatedValue);
// }
}
if (generatedValue == null) {
throw exception("Empty value produced");
}
return generatedValue;
}
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("if")
// public static class Condition extends Visible {
//
// public Narrower narrower;
// public Exists exists;
// public Equals equals;
// public AndCondition and;
// public OrCondition or;
// public NotCondition not;
//
// private static class Outcome {
//
// final GeneratorContext context;
// boolean failure;
//
// private Outcome(GeneratorContext context) {
// this.context = context;
// }
//
// Outcome evaluate(YesOrNo yesOrNo) {
// if (yesOrNo != null && !failure && !yesOrNo.yes(context)) {
// failure = true;
// }
// return this;
// }
// }
//
// public boolean failure(GeneratorContext context) {
// return new Outcome(context)
// .evaluate(narrower)
// .evaluate(exists)
// .evaluate(equals)
// .evaluate(and)
// .evaluate(or)
// .evaluate(not).failure;
// }
//
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
// Path: src/main/java/eu/delving/x3ml/engine/GeneratorContext.java
import org.w3c.dom.Node;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.Condition;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.SourceType;
});
put(variable, generatedValue);
// System.out.println(generator.variable + " ===VAR==> " + generatedValue);
}
// else {
// System.out.println(generator.variable + " <==VAR=== " + generatedValue);
// }
} else {
String nodeName = extractXPath(node) + unique;
generatedValue = context.getGeneratedValue(nodeName);
if (generatedValue == null) {
generatedValue = context.policy().generate(generator.name, new Generator.ArgValues() {
@Override
public ArgValue getArgValue(String name, SourceType sourceType) {
return context.input().evaluateArgument(node, index, generator, name, sourceType);
}
});
context.putGeneratedValue(nodeName, generatedValue);
// System.out.println(nodeName + " ===CTX==> " + generatedValue);
}
// else {
// System.out.println(nodeName + " <==CTX=== " + generatedValue);
// }
}
if (generatedValue == null) {
throw exception("Empty value produced");
}
return generatedValue;
}
| public boolean conditionFails(Condition condition, GeneratorContext context) {
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/X3ML.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
| import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.XppDriver;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static eu.delving.x3ml.X3MLEngine.exception;
| for (Condition condition : list) {
if (!condition.failure(context)) {
result = true;
}
}
return result;
}
}
@XStreamAlias("not")
public static class NotCondition extends Visible implements YesOrNo {
@XStreamAlias("if")
Condition condition;
@Override
public boolean yes(GeneratorContext context) {
return condition.failure(context);
}
}
@XStreamAlias("relationship")
@XStreamConverter(value = ToAttributedValueConverter.class, strings = {"tag"})
public static class Relationship extends Visible {
public String tag;
public String getPrefix() {
int colon = tag.indexOf(':');
if (colon < 0) {
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.XppDriver;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static eu.delving.x3ml.X3MLEngine.exception;
for (Condition condition : list) {
if (!condition.failure(context)) {
result = true;
}
}
return result;
}
}
@XStreamAlias("not")
public static class NotCondition extends Visible implements YesOrNo {
@XStreamAlias("if")
Condition condition;
@Override
public boolean yes(GeneratorContext context) {
return condition.failure(context);
}
}
@XStreamAlias("relationship")
@XStreamConverter(value = ToAttributedValueConverter.class, strings = {"tag"})
public static class Relationship extends Visible {
public String tag;
public String getPrefix() {
int colon = tag.indexOf(':');
if (colon < 0) {
| throw exception("Unqualified tag " + tag);
|
delving/x3ml | src/main/java/eu/delving/x3ml/X3MLCommandLine.java | // Path: src/main/java/eu/delving/x3ml/engine/Generator.java
// public interface Generator {
//
// interface UUIDSource {
//
// String generateUUID();
// }
//
// void setDefaultArgType(SourceType sourceType);
//
// void setLanguageFromMapping(String language);
//
// void setNamespace(String prefix, String uri);
//
// String getLanguageFromMapping();
//
// public interface ArgValues {
//
// ArgValue getArgValue(String name, SourceType sourceType);
// }
//
// GeneratedValue generate(String name, ArgValues arguments);
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
| import java.io.InputStream;
import java.io.PrintStream;
import java.util.List;
import static eu.delving.x3ml.X3MLEngine.exception;
import eu.delving.x3ml.engine.Generator;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException; | uuidTestSizeValue
);
}
catch (Exception e) {
error(e.getMessage());
}
}
static File file(String name) {
File file = new File(name);
if (!file.exists() || !file.isFile()) {
error("File does not exist: " + name);
}
return file;
}
static DocumentBuilderFactory documentBuilderFactory() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
return factory;
}
static Element xml(InputStream inputStream) {
try {
DocumentBuilder builder = documentBuilderFactory().newDocumentBuilder();
Document document = builder.parse(inputStream);
return document.getDocumentElement();
}
catch (Exception e) { | // Path: src/main/java/eu/delving/x3ml/engine/Generator.java
// public interface Generator {
//
// interface UUIDSource {
//
// String generateUUID();
// }
//
// void setDefaultArgType(SourceType sourceType);
//
// void setLanguageFromMapping(String language);
//
// void setNamespace(String prefix, String uri);
//
// String getLanguageFromMapping();
//
// public interface ArgValues {
//
// ArgValue getArgValue(String name, SourceType sourceType);
// }
//
// GeneratedValue generate(String name, ArgValues arguments);
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
// Path: src/main/java/eu/delving/x3ml/X3MLCommandLine.java
import java.io.InputStream;
import java.io.PrintStream;
import java.util.List;
import static eu.delving.x3ml.X3MLEngine.exception;
import eu.delving.x3ml.engine.Generator;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
uuidTestSizeValue
);
}
catch (Exception e) {
error(e.getMessage());
}
}
static File file(String name) {
File file = new File(name);
if (!file.exists() || !file.isFile()) {
error("File does not exist: " + name);
}
return file;
}
static DocumentBuilderFactory documentBuilderFactory() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
return factory;
}
static Element xml(InputStream inputStream) {
try {
DocumentBuilder builder = documentBuilderFactory().newDocumentBuilder();
Document document = builder.parse(inputStream);
return document.getDocumentElement();
}
catch (Exception e) { | throw exception("Unable to parse XML input"); |
delving/x3ml | src/main/java/eu/delving/x3ml/X3MLCommandLine.java | // Path: src/main/java/eu/delving/x3ml/engine/Generator.java
// public interface Generator {
//
// interface UUIDSource {
//
// String generateUUID();
// }
//
// void setDefaultArgType(SourceType sourceType);
//
// void setLanguageFromMapping(String language);
//
// void setNamespace(String prefix, String uri);
//
// String getLanguageFromMapping();
//
// public interface ArgValues {
//
// ArgValue getArgValue(String name, SourceType sourceType);
// }
//
// GeneratedValue generate(String name, ArgValues arguments);
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
| import java.io.InputStream;
import java.io.PrintStream;
import java.util.List;
import static eu.delving.x3ml.X3MLEngine.exception;
import eu.delving.x3ml.engine.Generator;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException; | static DocumentBuilderFactory documentBuilderFactory() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
return factory;
}
static Element xml(InputStream inputStream) {
try {
DocumentBuilder builder = documentBuilderFactory().newDocumentBuilder();
Document document = builder.parse(inputStream);
return document.getDocumentElement();
}
catch (Exception e) {
throw exception("Unable to parse XML input");
}
}
static Element xml(File file) {
return xml(getStream(file));
}
static FileInputStream getStream(File file) {
try {
return new FileInputStream(file);
}
catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
| // Path: src/main/java/eu/delving/x3ml/engine/Generator.java
// public interface Generator {
//
// interface UUIDSource {
//
// String generateUUID();
// }
//
// void setDefaultArgType(SourceType sourceType);
//
// void setLanguageFromMapping(String language);
//
// void setNamespace(String prefix, String uri);
//
// String getLanguageFromMapping();
//
// public interface ArgValues {
//
// ArgValue getArgValue(String name, SourceType sourceType);
// }
//
// GeneratedValue generate(String name, ArgValues arguments);
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
// Path: src/main/java/eu/delving/x3ml/X3MLCommandLine.java
import java.io.InputStream;
import java.io.PrintStream;
import java.util.List;
import static eu.delving.x3ml.X3MLEngine.exception;
import eu.delving.x3ml.engine.Generator;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
static DocumentBuilderFactory documentBuilderFactory() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
return factory;
}
static Element xml(InputStream inputStream) {
try {
DocumentBuilder builder = documentBuilderFactory().newDocumentBuilder();
Document document = builder.parse(inputStream);
return document.getDocumentElement();
}
catch (Exception e) {
throw exception("Unable to parse XML input");
}
}
static Element xml(File file) {
return xml(getStream(file));
}
static FileInputStream getStream(File file) {
try {
return new FileInputStream(file);
}
catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
| static Generator getValuePolicy(String policy, X3MLGeneratorPolicy.UUIDSource uuidSource) { |
delving/x3ml | src/main/java/eu/delving/x3ml/engine/Path.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("path")
// public static class PathElement extends Visible {
//
// public SourceRelation source_relation;
//
// public TargetRelation target_relation;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("range")
// public static class RangeElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("relationship")
// @XStreamConverter(value = ToAttributedValueConverter.class, strings = {"tag"})
// public static class Relationship extends Visible {
//
// public String tag;
//
// public String getPrefix() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(0, colon);
// }
//
// public String getLocalName() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(colon + 1);
// }
// }
| import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import org.w3c.dom.Node;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.PathElement;
import static eu.delving.x3ml.engine.X3ML.RangeElement;
import static eu.delving.x3ml.engine.X3ML.Relationship;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The path relationship handled here. Intermediate nodes possible. Expecting
* always one more path than entity, and they are interlaced. Marshalling
* handled specially.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class Path extends GeneratorContext {
public final Domain domain;
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("path")
// public static class PathElement extends Visible {
//
// public SourceRelation source_relation;
//
// public TargetRelation target_relation;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("range")
// public static class RangeElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("relationship")
// @XStreamConverter(value = ToAttributedValueConverter.class, strings = {"tag"})
// public static class Relationship extends Visible {
//
// public String tag;
//
// public String getPrefix() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(0, colon);
// }
//
// public String getLocalName() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(colon + 1);
// }
// }
// Path: src/main/java/eu/delving/x3ml/engine/Path.java
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import org.w3c.dom.Node;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.PathElement;
import static eu.delving.x3ml.engine.X3ML.RangeElement;
import static eu.delving.x3ml.engine.X3ML.Relationship;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The path relationship handled here. Intermediate nodes possible. Expecting
* always one more path than entity, and they are interlaced. Marshalling
* handled specially.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class Path extends GeneratorContext {
public final Domain domain;
| public final PathElement path;
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/Path.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("path")
// public static class PathElement extends Visible {
//
// public SourceRelation source_relation;
//
// public TargetRelation target_relation;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("range")
// public static class RangeElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("relationship")
// @XStreamConverter(value = ToAttributedValueConverter.class, strings = {"tag"})
// public static class Relationship extends Visible {
//
// public String tag;
//
// public String getPrefix() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(0, colon);
// }
//
// public String getLocalName() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(colon + 1);
// }
// }
| import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import org.w3c.dom.Node;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.PathElement;
import static eu.delving.x3ml.engine.X3ML.RangeElement;
import static eu.delving.x3ml.engine.X3ML.Relationship;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The path relationship handled here. Intermediate nodes possible. Expecting
* always one more path than entity, and they are interlaced. Marshalling
* handled specially.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class Path extends GeneratorContext {
public final Domain domain;
public final PathElement path;
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("path")
// public static class PathElement extends Visible {
//
// public SourceRelation source_relation;
//
// public TargetRelation target_relation;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("range")
// public static class RangeElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("relationship")
// @XStreamConverter(value = ToAttributedValueConverter.class, strings = {"tag"})
// public static class Relationship extends Visible {
//
// public String tag;
//
// public String getPrefix() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(0, colon);
// }
//
// public String getLocalName() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(colon + 1);
// }
// }
// Path: src/main/java/eu/delving/x3ml/engine/Path.java
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import org.w3c.dom.Node;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.PathElement;
import static eu.delving.x3ml.engine.X3ML.RangeElement;
import static eu.delving.x3ml.engine.X3ML.Relationship;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The path relationship handled here. Intermediate nodes possible. Expecting
* always one more path than entity, and they are interlaced. Marshalling
* handled specially.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class Path extends GeneratorContext {
public final Domain domain;
public final PathElement path;
| public Relationship relationship;
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/Path.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("path")
// public static class PathElement extends Visible {
//
// public SourceRelation source_relation;
//
// public TargetRelation target_relation;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("range")
// public static class RangeElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("relationship")
// @XStreamConverter(value = ToAttributedValueConverter.class, strings = {"tag"})
// public static class Relationship extends Visible {
//
// public String tag;
//
// public String getPrefix() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(0, colon);
// }
//
// public String getLocalName() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(colon + 1);
// }
// }
| import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import org.w3c.dom.Node;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.PathElement;
import static eu.delving.x3ml.engine.X3ML.RangeElement;
import static eu.delving.x3ml.engine.X3ML.Relationship;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The path relationship handled here. Intermediate nodes possible. Expecting
* always one more path than entity, and they are interlaced. Marshalling
* handled specially.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class Path extends GeneratorContext {
public final Domain domain;
public final PathElement path;
public Relationship relationship;
public Property property;
public List<IntermediateNode> intermediateNodes;
public List<Resource> lastResources;
public Property lastProperty;
public Path(Root.Context context, Domain domain, PathElement path, Node node, int index) {
super(context, domain, node, index);
this.domain = domain;
this.path = path;
}
public boolean resolve() {
X3ML.TargetRelation relation = path.target_relation;
if (conditionFails(relation.condition, this)) {
return false;
}
if (relation.properties == null || relation.properties.isEmpty()) {
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("path")
// public static class PathElement extends Visible {
//
// public SourceRelation source_relation;
//
// public TargetRelation target_relation;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("range")
// public static class RangeElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("relationship")
// @XStreamConverter(value = ToAttributedValueConverter.class, strings = {"tag"})
// public static class Relationship extends Visible {
//
// public String tag;
//
// public String getPrefix() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(0, colon);
// }
//
// public String getLocalName() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(colon + 1);
// }
// }
// Path: src/main/java/eu/delving/x3ml/engine/Path.java
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import org.w3c.dom.Node;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.PathElement;
import static eu.delving.x3ml.engine.X3ML.RangeElement;
import static eu.delving.x3ml.engine.X3ML.Relationship;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The path relationship handled here. Intermediate nodes possible. Expecting
* always one more path than entity, and they are interlaced. Marshalling
* handled specially.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class Path extends GeneratorContext {
public final Domain domain;
public final PathElement path;
public Relationship relationship;
public Property property;
public List<IntermediateNode> intermediateNodes;
public List<Resource> lastResources;
public Property lastProperty;
public Path(Root.Context context, Domain domain, PathElement path, Node node, int index) {
super(context, domain, node, index);
this.domain = domain;
this.path = path;
}
public boolean resolve() {
X3ML.TargetRelation relation = path.target_relation;
if (conditionFails(relation.condition, this)) {
return false;
}
if (relation.properties == null || relation.properties.isEmpty()) {
| throw exception("Target relation must have at least one property");
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/Path.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("path")
// public static class PathElement extends Visible {
//
// public SourceRelation source_relation;
//
// public TargetRelation target_relation;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("range")
// public static class RangeElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("relationship")
// @XStreamConverter(value = ToAttributedValueConverter.class, strings = {"tag"})
// public static class Relationship extends Visible {
//
// public String tag;
//
// public String getPrefix() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(0, colon);
// }
//
// public String getLocalName() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(colon + 1);
// }
// }
| import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import org.w3c.dom.Node;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.PathElement;
import static eu.delving.x3ml.engine.X3ML.RangeElement;
import static eu.delving.x3ml.engine.X3ML.Relationship;
| throw exception("Target relation must just one property if it has no entities");
}
relationship = relation.properties.get(0);
property = context.output().createProperty(relationship);
intermediateNodes = createIntermediateNodes(relation.entities, relation.properties, this);
return true;
}
public void link() {
domain.link();
if (!domain.entityResolver.hasResources()) {
throw exception("Domain node has no resource");
}
lastResources = domain.entityResolver.resources;
lastProperty = property;
for (IntermediateNode intermediateNode : intermediateNodes) {
intermediateNode.entityResolver.link();
if (!intermediateNode.entityResolver.hasResources()) {
throw exception("Intermediate node has no resources");
}
for (Resource lastResource : lastResources) {
for (Resource resolvedResource : intermediateNode.entityResolver.resources) {
lastResource.addProperty(lastProperty, resolvedResource);
}
}
lastResources = intermediateNode.entityResolver.resources;
lastProperty = intermediateNode.property;
}
}
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("path")
// public static class PathElement extends Visible {
//
// public SourceRelation source_relation;
//
// public TargetRelation target_relation;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("range")
// public static class RangeElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("relationship")
// @XStreamConverter(value = ToAttributedValueConverter.class, strings = {"tag"})
// public static class Relationship extends Visible {
//
// public String tag;
//
// public String getPrefix() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(0, colon);
// }
//
// public String getLocalName() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(colon + 1);
// }
// }
// Path: src/main/java/eu/delving/x3ml/engine/Path.java
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import org.w3c.dom.Node;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.PathElement;
import static eu.delving.x3ml.engine.X3ML.RangeElement;
import static eu.delving.x3ml.engine.X3ML.Relationship;
throw exception("Target relation must just one property if it has no entities");
}
relationship = relation.properties.get(0);
property = context.output().createProperty(relationship);
intermediateNodes = createIntermediateNodes(relation.entities, relation.properties, this);
return true;
}
public void link() {
domain.link();
if (!domain.entityResolver.hasResources()) {
throw exception("Domain node has no resource");
}
lastResources = domain.entityResolver.resources;
lastProperty = property;
for (IntermediateNode intermediateNode : intermediateNodes) {
intermediateNode.entityResolver.link();
if (!intermediateNode.entityResolver.hasResources()) {
throw exception("Intermediate node has no resources");
}
for (Resource lastResource : lastResources) {
for (Resource resolvedResource : intermediateNode.entityResolver.resources) {
lastResource.addProperty(lastProperty, resolvedResource);
}
}
lastResources = intermediateNode.entityResolver.resources;
lastProperty = intermediateNode.property;
}
}
| public List<Range> createRangeContexts(RangeElement range) {
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/Domain.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("domain")
// public static class DomainElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("link")
// public static class LinkElement extends Visible {
//
// public PathElement path;
//
// public RangeElement range;
//
// public void apply(Domain domain) {
// String pathSource = this.path.source_relation.relation.expression;
// String pathSource2 = "";
// String node_inside = "";
//
// System.out.println(pathSource);
// if (this.path.source_relation.relation2 != null) {
// pathSource2 = this.path.source_relation.relation2.expression;
// System.out.println("pathSource2: " + pathSource2);
// }
//
// if (this.path.source_relation.node != null) {
// node_inside = this.path.source_relation.node.expression;
// System.out.println("node: " + node_inside);
// }
//
// if (this.path.source_relation.node != null) {
//
// int equals = pathSource.indexOf("==");
//
// if (equals >= 0) {
//
// String domainForeignKey = pathSource.trim();
// String rangePrimaryKey = pathSource2.trim();
//
// String intermediateFirst = domainForeignKey.substring(domainForeignKey.indexOf("==") + 2).trim();
// String intermediateSecond = rangePrimaryKey.substring(0, rangePrimaryKey.indexOf("==")).trim();
//
// domainForeignKey = domainForeignKey.substring(0, domainForeignKey.indexOf("==")).trim();
// rangePrimaryKey = rangePrimaryKey.substring(rangePrimaryKey.indexOf("==") + 2).trim();
//
// for (Link link : domain.createLinkContexts(this, domainForeignKey, rangePrimaryKey,
// intermediateFirst, intermediateSecond, node_inside)) {
// link.range.link();
// }
//
// }
// } else if (pathSource.contains("==")) {
//
// int equals = pathSource.indexOf("==");
// if (equals >= 0) {
// String domainForeignKey = pathSource.substring(0, equals).trim();
// String rangePrimaryKey = pathSource.substring(equals + 2).trim();
// for (Link link : domain.createLinkContexts(this, domainForeignKey, rangePrimaryKey)) {
// link.range.link();
// }
// }
//
// } else {
// System.out.println(this.path);
// for (Path path : domain.createPathContexts(this.path)) {
// System.out.println(this.path);
// for (Range range : path.createRangeContexts(this.range)) {
// range.link();
// }
// }
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("path")
// public static class PathElement extends Visible {
//
// public SourceRelation source_relation;
//
// public TargetRelation target_relation;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("range")
// public static class RangeElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
| import org.w3c.dom.Node;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.DomainElement;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.LinkElement;
import static eu.delving.x3ml.engine.X3ML.PathElement;
import static eu.delving.x3ml.engine.X3ML.RangeElement;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The domain entity handled here. Resolution delegated. Holding variables here.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class Domain extends GeneratorContext {
public final DomainElement domain;
public EntityResolver entityResolver;
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("domain")
// public static class DomainElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("link")
// public static class LinkElement extends Visible {
//
// public PathElement path;
//
// public RangeElement range;
//
// public void apply(Domain domain) {
// String pathSource = this.path.source_relation.relation.expression;
// String pathSource2 = "";
// String node_inside = "";
//
// System.out.println(pathSource);
// if (this.path.source_relation.relation2 != null) {
// pathSource2 = this.path.source_relation.relation2.expression;
// System.out.println("pathSource2: " + pathSource2);
// }
//
// if (this.path.source_relation.node != null) {
// node_inside = this.path.source_relation.node.expression;
// System.out.println("node: " + node_inside);
// }
//
// if (this.path.source_relation.node != null) {
//
// int equals = pathSource.indexOf("==");
//
// if (equals >= 0) {
//
// String domainForeignKey = pathSource.trim();
// String rangePrimaryKey = pathSource2.trim();
//
// String intermediateFirst = domainForeignKey.substring(domainForeignKey.indexOf("==") + 2).trim();
// String intermediateSecond = rangePrimaryKey.substring(0, rangePrimaryKey.indexOf("==")).trim();
//
// domainForeignKey = domainForeignKey.substring(0, domainForeignKey.indexOf("==")).trim();
// rangePrimaryKey = rangePrimaryKey.substring(rangePrimaryKey.indexOf("==") + 2).trim();
//
// for (Link link : domain.createLinkContexts(this, domainForeignKey, rangePrimaryKey,
// intermediateFirst, intermediateSecond, node_inside)) {
// link.range.link();
// }
//
// }
// } else if (pathSource.contains("==")) {
//
// int equals = pathSource.indexOf("==");
// if (equals >= 0) {
// String domainForeignKey = pathSource.substring(0, equals).trim();
// String rangePrimaryKey = pathSource.substring(equals + 2).trim();
// for (Link link : domain.createLinkContexts(this, domainForeignKey, rangePrimaryKey)) {
// link.range.link();
// }
// }
//
// } else {
// System.out.println(this.path);
// for (Path path : domain.createPathContexts(this.path)) {
// System.out.println(this.path);
// for (Range range : path.createRangeContexts(this.range)) {
// range.link();
// }
// }
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("path")
// public static class PathElement extends Visible {
//
// public SourceRelation source_relation;
//
// public TargetRelation target_relation;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("range")
// public static class RangeElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
// Path: src/main/java/eu/delving/x3ml/engine/Domain.java
import org.w3c.dom.Node;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.DomainElement;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.LinkElement;
import static eu.delving.x3ml.engine.X3ML.PathElement;
import static eu.delving.x3ml.engine.X3ML.RangeElement;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The domain entity handled here. Resolution delegated. Holding variables here.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class Domain extends GeneratorContext {
public final DomainElement domain;
public EntityResolver entityResolver;
| private Map<String, X3ML.GeneratedValue> variables = new TreeMap<String, X3ML.GeneratedValue>();
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/Domain.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("domain")
// public static class DomainElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("link")
// public static class LinkElement extends Visible {
//
// public PathElement path;
//
// public RangeElement range;
//
// public void apply(Domain domain) {
// String pathSource = this.path.source_relation.relation.expression;
// String pathSource2 = "";
// String node_inside = "";
//
// System.out.println(pathSource);
// if (this.path.source_relation.relation2 != null) {
// pathSource2 = this.path.source_relation.relation2.expression;
// System.out.println("pathSource2: " + pathSource2);
// }
//
// if (this.path.source_relation.node != null) {
// node_inside = this.path.source_relation.node.expression;
// System.out.println("node: " + node_inside);
// }
//
// if (this.path.source_relation.node != null) {
//
// int equals = pathSource.indexOf("==");
//
// if (equals >= 0) {
//
// String domainForeignKey = pathSource.trim();
// String rangePrimaryKey = pathSource2.trim();
//
// String intermediateFirst = domainForeignKey.substring(domainForeignKey.indexOf("==") + 2).trim();
// String intermediateSecond = rangePrimaryKey.substring(0, rangePrimaryKey.indexOf("==")).trim();
//
// domainForeignKey = domainForeignKey.substring(0, domainForeignKey.indexOf("==")).trim();
// rangePrimaryKey = rangePrimaryKey.substring(rangePrimaryKey.indexOf("==") + 2).trim();
//
// for (Link link : domain.createLinkContexts(this, domainForeignKey, rangePrimaryKey,
// intermediateFirst, intermediateSecond, node_inside)) {
// link.range.link();
// }
//
// }
// } else if (pathSource.contains("==")) {
//
// int equals = pathSource.indexOf("==");
// if (equals >= 0) {
// String domainForeignKey = pathSource.substring(0, equals).trim();
// String rangePrimaryKey = pathSource.substring(equals + 2).trim();
// for (Link link : domain.createLinkContexts(this, domainForeignKey, rangePrimaryKey)) {
// link.range.link();
// }
// }
//
// } else {
// System.out.println(this.path);
// for (Path path : domain.createPathContexts(this.path)) {
// System.out.println(this.path);
// for (Range range : path.createRangeContexts(this.range)) {
// range.link();
// }
// }
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("path")
// public static class PathElement extends Visible {
//
// public SourceRelation source_relation;
//
// public TargetRelation target_relation;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("range")
// public static class RangeElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
| import org.w3c.dom.Node;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.DomainElement;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.LinkElement;
import static eu.delving.x3ml.engine.X3ML.PathElement;
import static eu.delving.x3ml.engine.X3ML.RangeElement;
| return variables.get(variable);
}
@Override
public void put(String variable, GeneratedValue generatedValue) {
variables.put(variable, generatedValue);
}
public boolean resolve() {
if (conditionFails(domain.target_node.condition, this)) {
return false;
}
entityResolver = new EntityResolver(context.output(), domain.target_node.entityElement, this);
return entityResolver.resolve();
}
public List<Link> createLinkContexts(LinkElement linkElement, String domainForeignKey, String rangePrimaryKey,
String intermediateFirst, String intermediateSecond, String node_inside) {
PathElement pathElement = linkElement.path;
System.out.println("Node Inside" + node_inside);
String pathExpression = pathElement.source_relation.relation.expression;
RangeElement rangeElement = linkElement.range;
String rangeExpression = rangeElement.source_node.expression;
if (rangeExpression == null) {
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("domain")
// public static class DomainElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("link")
// public static class LinkElement extends Visible {
//
// public PathElement path;
//
// public RangeElement range;
//
// public void apply(Domain domain) {
// String pathSource = this.path.source_relation.relation.expression;
// String pathSource2 = "";
// String node_inside = "";
//
// System.out.println(pathSource);
// if (this.path.source_relation.relation2 != null) {
// pathSource2 = this.path.source_relation.relation2.expression;
// System.out.println("pathSource2: " + pathSource2);
// }
//
// if (this.path.source_relation.node != null) {
// node_inside = this.path.source_relation.node.expression;
// System.out.println("node: " + node_inside);
// }
//
// if (this.path.source_relation.node != null) {
//
// int equals = pathSource.indexOf("==");
//
// if (equals >= 0) {
//
// String domainForeignKey = pathSource.trim();
// String rangePrimaryKey = pathSource2.trim();
//
// String intermediateFirst = domainForeignKey.substring(domainForeignKey.indexOf("==") + 2).trim();
// String intermediateSecond = rangePrimaryKey.substring(0, rangePrimaryKey.indexOf("==")).trim();
//
// domainForeignKey = domainForeignKey.substring(0, domainForeignKey.indexOf("==")).trim();
// rangePrimaryKey = rangePrimaryKey.substring(rangePrimaryKey.indexOf("==") + 2).trim();
//
// for (Link link : domain.createLinkContexts(this, domainForeignKey, rangePrimaryKey,
// intermediateFirst, intermediateSecond, node_inside)) {
// link.range.link();
// }
//
// }
// } else if (pathSource.contains("==")) {
//
// int equals = pathSource.indexOf("==");
// if (equals >= 0) {
// String domainForeignKey = pathSource.substring(0, equals).trim();
// String rangePrimaryKey = pathSource.substring(equals + 2).trim();
// for (Link link : domain.createLinkContexts(this, domainForeignKey, rangePrimaryKey)) {
// link.range.link();
// }
// }
//
// } else {
// System.out.println(this.path);
// for (Path path : domain.createPathContexts(this.path)) {
// System.out.println(this.path);
// for (Range range : path.createRangeContexts(this.range)) {
// range.link();
// }
// }
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("path")
// public static class PathElement extends Visible {
//
// public SourceRelation source_relation;
//
// public TargetRelation target_relation;
//
// public Comments comments;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("range")
// public static class RangeElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
// Path: src/main/java/eu/delving/x3ml/engine/Domain.java
import org.w3c.dom.Node;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.DomainElement;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.LinkElement;
import static eu.delving.x3ml.engine.X3ML.PathElement;
import static eu.delving.x3ml.engine.X3ML.RangeElement;
return variables.get(variable);
}
@Override
public void put(String variable, GeneratedValue generatedValue) {
variables.put(variable, generatedValue);
}
public boolean resolve() {
if (conditionFails(domain.target_node.condition, this)) {
return false;
}
entityResolver = new EntityResolver(context.output(), domain.target_node.entityElement, this);
return entityResolver.resolve();
}
public List<Link> createLinkContexts(LinkElement linkElement, String domainForeignKey, String rangePrimaryKey,
String intermediateFirst, String intermediateSecond, String node_inside) {
PathElement pathElement = linkElement.path;
System.out.println("Node Inside" + node_inside);
String pathExpression = pathElement.source_relation.relation.expression;
RangeElement rangeElement = linkElement.range;
String rangeExpression = rangeElement.source_node.expression;
if (rangeExpression == null) {
| throw exception("Range source absent: " + linkElement);
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/ModelOutput.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public interface Output {
//
// void write(PrintStream printStream, String rdfFormat);
//
// void writeXML(PrintStream printStream);
//
// Model getModel();
//
// String[] toStringArray();
//
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("type")
// @XStreamConverter(value = ToAttributedValueConverter.class, strings = {"tag"})
// public static class TypeElement extends Visible {
//
// public String tag;
//
// @XStreamOmitField
// public String namespaceUri;
//
// public TypeElement() {
// }
//
// public TypeElement(String tag, String namespaceUri) {
// this.tag = tag;
// this.namespaceUri = namespaceUri;
// }
//
// public String getPrefix() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(0, colon);
// }
//
// public String getLocalName() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(colon + 1);
// }
// }
| import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import javax.xml.namespace.NamespaceContext;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static eu.delving.x3ml.X3MLEngine.Output;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.TypeElement;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The output sent to a Jena graph model.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class ModelOutput implements Output {
private final Model model;
private final NamespaceContext namespaceContext;
public ModelOutput(Model model, NamespaceContext namespaceContext) {
this.model = model;
this.namespaceContext = namespaceContext;
}
public Model getModel() {
return model;
}
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public interface Output {
//
// void write(PrintStream printStream, String rdfFormat);
//
// void writeXML(PrintStream printStream);
//
// Model getModel();
//
// String[] toStringArray();
//
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("type")
// @XStreamConverter(value = ToAttributedValueConverter.class, strings = {"tag"})
// public static class TypeElement extends Visible {
//
// public String tag;
//
// @XStreamOmitField
// public String namespaceUri;
//
// public TypeElement() {
// }
//
// public TypeElement(String tag, String namespaceUri) {
// this.tag = tag;
// this.namespaceUri = namespaceUri;
// }
//
// public String getPrefix() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(0, colon);
// }
//
// public String getLocalName() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(colon + 1);
// }
// }
// Path: src/main/java/eu/delving/x3ml/engine/ModelOutput.java
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import javax.xml.namespace.NamespaceContext;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static eu.delving.x3ml.X3MLEngine.Output;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.TypeElement;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The output sent to a Jena graph model.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class ModelOutput implements Output {
private final Model model;
private final NamespaceContext namespaceContext;
public ModelOutput(Model model, NamespaceContext namespaceContext) {
this.model = model;
this.namespaceContext = namespaceContext;
}
public Model getModel() {
return model;
}
| public Resource createTypedResource(String uriString, TypeElement typeElement) {
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/ModelOutput.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public interface Output {
//
// void write(PrintStream printStream, String rdfFormat);
//
// void writeXML(PrintStream printStream);
//
// Model getModel();
//
// String[] toStringArray();
//
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("type")
// @XStreamConverter(value = ToAttributedValueConverter.class, strings = {"tag"})
// public static class TypeElement extends Visible {
//
// public String tag;
//
// @XStreamOmitField
// public String namespaceUri;
//
// public TypeElement() {
// }
//
// public TypeElement(String tag, String namespaceUri) {
// this.tag = tag;
// this.namespaceUri = namespaceUri;
// }
//
// public String getPrefix() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(0, colon);
// }
//
// public String getLocalName() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(colon + 1);
// }
// }
| import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import javax.xml.namespace.NamespaceContext;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static eu.delving.x3ml.X3MLEngine.Output;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.TypeElement;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The output sent to a Jena graph model.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class ModelOutput implements Output {
private final Model model;
private final NamespaceContext namespaceContext;
public ModelOutput(Model model, NamespaceContext namespaceContext) {
this.model = model;
this.namespaceContext = namespaceContext;
}
public Model getModel() {
return model;
}
public Resource createTypedResource(String uriString, TypeElement typeElement) {
if (typeElement == null) {
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public interface Output {
//
// void write(PrintStream printStream, String rdfFormat);
//
// void writeXML(PrintStream printStream);
//
// Model getModel();
//
// String[] toStringArray();
//
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("type")
// @XStreamConverter(value = ToAttributedValueConverter.class, strings = {"tag"})
// public static class TypeElement extends Visible {
//
// public String tag;
//
// @XStreamOmitField
// public String namespaceUri;
//
// public TypeElement() {
// }
//
// public TypeElement(String tag, String namespaceUri) {
// this.tag = tag;
// this.namespaceUri = namespaceUri;
// }
//
// public String getPrefix() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(0, colon);
// }
//
// public String getLocalName() {
// int colon = tag.indexOf(':');
// if (colon < 0) {
// throw exception("Unqualified tag " + tag);
// }
// return tag.substring(colon + 1);
// }
// }
// Path: src/main/java/eu/delving/x3ml/engine/ModelOutput.java
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import javax.xml.namespace.NamespaceContext;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static eu.delving.x3ml.X3MLEngine.Output;
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.TypeElement;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The output sent to a Jena graph model.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class ModelOutput implements Output {
private final Model model;
private final NamespaceContext namespaceContext;
public ModelOutput(Model model, NamespaceContext namespaceContext) {
this.model = model;
this.namespaceContext = namespaceContext;
}
public Model getModel() {
return model;
}
public Resource createTypedResource(String uriString, TypeElement typeElement) {
if (typeElement == null) {
| throw exception("Missing qualified name");
|
delving/x3ml | src/test/java/gr/forth/URIorUUID.java | // Path: src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
// public interface CustomGenerator {
// void setArg(String name, String value) throws CustomGeneratorException;
//
// String getValue() throws CustomGeneratorException;
//
// String getValueType() throws CustomGeneratorException;
//
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
// public static class CustomGeneratorException extends Exception {
// public CustomGeneratorException(String message) {
// super(message);
// }
// }
| import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import static eu.delving.x3ml.X3MLGeneratorPolicy.CustomGenerator;
import static eu.delving.x3ml.X3MLGeneratorPolicy.CustomGeneratorException; | //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 gr.forth;
/**
* an excample date interpreter
*/
public class URIorUUID implements CustomGenerator {
private String text;
@Override | // Path: src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
// public interface CustomGenerator {
// void setArg(String name, String value) throws CustomGeneratorException;
//
// String getValue() throws CustomGeneratorException;
//
// String getValueType() throws CustomGeneratorException;
//
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
// public static class CustomGeneratorException extends Exception {
// public CustomGeneratorException(String message) {
// super(message);
// }
// }
// Path: src/test/java/gr/forth/URIorUUID.java
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import static eu.delving.x3ml.X3MLGeneratorPolicy.CustomGenerator;
import static eu.delving.x3ml.X3MLGeneratorPolicy.CustomGeneratorException;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 gr.forth;
/**
* an excample date interpreter
*/
public class URIorUUID implements CustomGenerator {
private String text;
@Override | public void setArg(String name, String value) throws CustomGeneratorException { |
delving/x3ml | src/main/java/eu/delving/x3ml/engine/Generator.java | // Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
| import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.SourceType;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* This is what a generator looks like to the internal code.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public interface Generator {
interface UUIDSource {
String generateUUID();
}
| // Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
// Path: src/main/java/eu/delving/x3ml/engine/Generator.java
import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.SourceType;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* This is what a generator looks like to the internal code.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public interface Generator {
interface UUIDSource {
String generateUUID();
}
| void setDefaultArgType(SourceType sourceType);
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/Generator.java | // Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
| import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.SourceType;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* This is what a generator looks like to the internal code.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public interface Generator {
interface UUIDSource {
String generateUUID();
}
void setDefaultArgType(SourceType sourceType);
void setLanguageFromMapping(String language);
void setNamespace(String prefix, String uri);
String getLanguageFromMapping();
public interface ArgValues {
| // Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
// Path: src/main/java/eu/delving/x3ml/engine/Generator.java
import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.SourceType;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* This is what a generator looks like to the internal code.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public interface Generator {
interface UUIDSource {
String generateUUID();
}
void setDefaultArgType(SourceType sourceType);
void setLanguageFromMapping(String language);
void setNamespace(String prefix, String uri);
String getLanguageFromMapping();
public interface ArgValues {
| ArgValue getArgValue(String name, SourceType sourceType);
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/Generator.java | // Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
| import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.SourceType;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* This is what a generator looks like to the internal code.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public interface Generator {
interface UUIDSource {
String generateUUID();
}
void setDefaultArgType(SourceType sourceType);
void setLanguageFromMapping(String language);
void setNamespace(String prefix, String uri);
String getLanguageFromMapping();
public interface ArgValues {
ArgValue getArgValue(String name, SourceType sourceType);
}
| // Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class ArgValue {
//
// public final String string;
// public final String language;
//
// public ArgValue(String string, String language) {
// this.string = string;
// this.language = language;
// }
//
// public String toString() {
// if (string != null) {
// return "ArgValue(" + string + ")";
// } else {
// return "ArgValue?";
// }
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static class GeneratedValue {
//
// public final GeneratedType type;
// public final String text;
// public final String language;
//
// public GeneratedValue(GeneratedType type, String text, String language) {
// this.type = type;
// this.text = text;
// this.language = language;
// }
//
// public GeneratedValue(GeneratedType type, String text) {
// this(type, text, null);
// }
//
// public String toString() {
// return type + ":" + text;
// }
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
// Path: src/main/java/eu/delving/x3ml/engine/Generator.java
import static eu.delving.x3ml.engine.X3ML.ArgValue;
import static eu.delving.x3ml.engine.X3ML.GeneratedValue;
import static eu.delving.x3ml.engine.X3ML.SourceType;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* This is what a generator looks like to the internal code.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public interface Generator {
interface UUIDSource {
String generateUUID();
}
void setDefaultArgType(SourceType sourceType);
void setLanguageFromMapping(String language);
void setNamespace(String prefix, String uri);
String getLanguageFromMapping();
public interface ArgValues {
ArgValue getArgValue(String name, SourceType sourceType);
}
| GeneratedValue generate(String name, ArgValues arguments);
|
delving/x3ml | src/main/java/gr/forth/URIorUUID.java | // Path: src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
// public interface CustomGenerator {
// void setArg(String name, String value) throws CustomGeneratorException;
//
// String getValue() throws CustomGeneratorException;
//
// String getValueType() throws CustomGeneratorException;
//
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
// public static class CustomGeneratorException extends Exception {
// public CustomGeneratorException(String message) {
// super(message);
// }
// }
| import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import static eu.delving.x3ml.X3MLGeneratorPolicy.CustomGenerator;
import static eu.delving.x3ml.X3MLGeneratorPolicy.CustomGeneratorException;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 gr.forth;
/**
* an excample date interpreter
*/
public class URIorUUID implements CustomGenerator {
private String text;
@Override
| // Path: src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
// public interface CustomGenerator {
// void setArg(String name, String value) throws CustomGeneratorException;
//
// String getValue() throws CustomGeneratorException;
//
// String getValueType() throws CustomGeneratorException;
//
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
// public static class CustomGeneratorException extends Exception {
// public CustomGeneratorException(String message) {
// super(message);
// }
// }
// Path: src/main/java/gr/forth/URIorUUID.java
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import static eu.delving.x3ml.X3MLGeneratorPolicy.CustomGenerator;
import static eu.delving.x3ml.X3MLGeneratorPolicy.CustomGeneratorException;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 gr.forth;
/**
* an excample date interpreter
*/
public class URIorUUID implements CustomGenerator {
private String text;
@Override
| public void setArg(String name, String value) throws CustomGeneratorException {
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/Range.java | // Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("range")
// public static class RangeElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
| import com.hp.hpl.jena.rdf.model.Resource;
import org.w3c.dom.Node;
import static eu.delving.x3ml.engine.X3ML.RangeElement;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The range entity handled here. Resolution delegated.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class Range extends GeneratorContext {
public final Path path;
| // Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("range")
// public static class RangeElement extends Visible {
//
// public Source source_node;
//
// public TargetNode target_node;
//
// public Comments comments;
// }
// Path: src/main/java/eu/delving/x3ml/engine/Range.java
import com.hp.hpl.jena.rdf.model.Resource;
import org.w3c.dom.Node;
import static eu.delving.x3ml.engine.X3ML.RangeElement;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The range entity handled here. Resolution delegated.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class Range extends GeneratorContext {
public final Path path;
| public final RangeElement range;
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/XPathInput.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static ArgValue argVal(String string, String language) {
// return new ArgValue(string, language);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
| import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.Helper.argVal;
import static eu.delving.x3ml.engine.X3ML.SourceType;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The source data is accessed using xpath to fetch nodes from a DOM tree.
* <p/>
* Here we have tools for evaluating xpaths in various contexts.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class XPathInput {
private final XPathFactory pathFactory = net.sf.saxon.xpath.XPathFactoryImpl.newInstance();
private final NamespaceContext namespaceContext;
private final String languageFromMapping;
private final Node rootNode;
private Map<String, Map<String, List<Node>>> rangeMapCache = new TreeMap<String, Map<String, List<Node>>>();
public XPathInput(Node rootNode, NamespaceContext namespaceContext, String languageFromMapping) {
this.rootNode = rootNode;
this.namespaceContext = namespaceContext;
this.languageFromMapping = languageFromMapping;
}
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static ArgValue argVal(String string, String language) {
// return new ArgValue(string, language);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
// Path: src/main/java/eu/delving/x3ml/engine/XPathInput.java
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.Helper.argVal;
import static eu.delving.x3ml.engine.X3ML.SourceType;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The source data is accessed using xpath to fetch nodes from a DOM tree.
* <p/>
* Here we have tools for evaluating xpaths in various contexts.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class XPathInput {
private final XPathFactory pathFactory = net.sf.saxon.xpath.XPathFactoryImpl.newInstance();
private final NamespaceContext namespaceContext;
private final String languageFromMapping;
private final Node rootNode;
private Map<String, Map<String, List<Node>>> rangeMapCache = new TreeMap<String, Map<String, List<Node>>>();
public XPathInput(Node rootNode, NamespaceContext namespaceContext, String languageFromMapping) {
this.rootNode = rootNode;
this.namespaceContext = namespaceContext;
this.languageFromMapping = languageFromMapping;
}
| public X3ML.ArgValue evaluateArgument(Node node, int index, GeneratorElement generatorElement, String argName, SourceType defaultType) {
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/XPathInput.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static ArgValue argVal(String string, String language) {
// return new ArgValue(string, language);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
| import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.Helper.argVal;
import static eu.delving.x3ml.engine.X3ML.SourceType;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
| //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The source data is accessed using xpath to fetch nodes from a DOM tree.
* <p/>
* Here we have tools for evaluating xpaths in various contexts.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class XPathInput {
private final XPathFactory pathFactory = net.sf.saxon.xpath.XPathFactoryImpl.newInstance();
private final NamespaceContext namespaceContext;
private final String languageFromMapping;
private final Node rootNode;
private Map<String, Map<String, List<Node>>> rangeMapCache = new TreeMap<String, Map<String, List<Node>>>();
public XPathInput(Node rootNode, NamespaceContext namespaceContext, String languageFromMapping) {
this.rootNode = rootNode;
this.namespaceContext = namespaceContext;
this.languageFromMapping = languageFromMapping;
}
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static ArgValue argVal(String string, String language) {
// return new ArgValue(string, language);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
// Path: src/main/java/eu/delving/x3ml/engine/XPathInput.java
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.Helper.argVal;
import static eu.delving.x3ml.engine.X3ML.SourceType;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml.engine;
/**
* The source data is accessed using xpath to fetch nodes from a DOM tree.
* <p/>
* Here we have tools for evaluating xpaths in various contexts.
*
* @author Gerald de Jong <gerald@delving.eu>
*/
public class XPathInput {
private final XPathFactory pathFactory = net.sf.saxon.xpath.XPathFactoryImpl.newInstance();
private final NamespaceContext namespaceContext;
private final String languageFromMapping;
private final Node rootNode;
private Map<String, Map<String, List<Node>>> rangeMapCache = new TreeMap<String, Map<String, List<Node>>>();
public XPathInput(Node rootNode, NamespaceContext namespaceContext, String languageFromMapping) {
this.rootNode = rootNode;
this.namespaceContext = namespaceContext;
this.languageFromMapping = languageFromMapping;
}
| public X3ML.ArgValue evaluateArgument(Node node, int index, GeneratorElement generatorElement, String argName, SourceType defaultType) {
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/XPathInput.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static ArgValue argVal(String string, String language) {
// return new ArgValue(string, language);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
| import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.Helper.argVal;
import static eu.delving.x3ml.engine.X3ML.SourceType;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
| }
public X3ML.ArgValue evaluateArgument(Node node, int index, GeneratorElement generatorElement, String argName, SourceType defaultType) {
X3ML.GeneratorArg foundArg = null;
SourceType type = defaultType;
if (generatorElement.args != null) {
for (X3ML.GeneratorArg arg : generatorElement.args) {
if (arg.name == null) {
// throw exception("Argument needs a name in generator "+generatorElement.name);
arg.name = "text";
}
if (arg.name.equals(argName)) {
foundArg = arg;
type = sourceType(arg.type, defaultType);
}
}
}
X3ML.ArgValue value = null;
switch (type) {
case xpath:
if (foundArg == null) {
return null;
}
String lang = getLanguageFromSource(node);
if (lang == null) {
lang = languageFromMapping;
}
if (!foundArg.value.isEmpty()) {
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static ArgValue argVal(String string, String language) {
// return new ArgValue(string, language);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
// Path: src/main/java/eu/delving/x3ml/engine/XPathInput.java
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.Helper.argVal;
import static eu.delving.x3ml.engine.X3ML.SourceType;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
}
public X3ML.ArgValue evaluateArgument(Node node, int index, GeneratorElement generatorElement, String argName, SourceType defaultType) {
X3ML.GeneratorArg foundArg = null;
SourceType type = defaultType;
if (generatorElement.args != null) {
for (X3ML.GeneratorArg arg : generatorElement.args) {
if (arg.name == null) {
// throw exception("Argument needs a name in generator "+generatorElement.name);
arg.name = "text";
}
if (arg.name.equals(argName)) {
foundArg = arg;
type = sourceType(arg.type, defaultType);
}
}
}
X3ML.ArgValue value = null;
switch (type) {
case xpath:
if (foundArg == null) {
return null;
}
String lang = getLanguageFromSource(node);
if (lang == null) {
lang = languageFromMapping;
}
if (!foundArg.value.isEmpty()) {
| value = argVal(valueAt(node, foundArg.value), lang);
|
delving/x3ml | src/main/java/eu/delving/x3ml/engine/XPathInput.java | // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static ArgValue argVal(String string, String language) {
// return new ArgValue(string, language);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
| import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.Helper.argVal;
import static eu.delving.x3ml.engine.X3ML.SourceType;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
| public X3ML.ArgValue evaluateArgument(Node node, int index, GeneratorElement generatorElement, String argName, SourceType defaultType) {
X3ML.GeneratorArg foundArg = null;
SourceType type = defaultType;
if (generatorElement.args != null) {
for (X3ML.GeneratorArg arg : generatorElement.args) {
if (arg.name == null) {
// throw exception("Argument needs a name in generator "+generatorElement.name);
arg.name = "text";
}
if (arg.name.equals(argName)) {
foundArg = arg;
type = sourceType(arg.type, defaultType);
}
}
}
X3ML.ArgValue value = null;
switch (type) {
case xpath:
if (foundArg == null) {
return null;
}
String lang = getLanguageFromSource(node);
if (lang == null) {
lang = languageFromMapping;
}
if (!foundArg.value.isEmpty()) {
value = argVal(valueAt(node, foundArg.value), lang);
if (value.string.isEmpty()) {
| // Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// @XStreamAlias("label_generator")
// public static class GeneratorElement extends Visible {
//
// @XStreamAsAttribute
// public String name;
//
// @XStreamImplicit
// public List<GeneratorArg> args;
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public static ArgValue argVal(String string, String language) {
// return new ArgValue(string, language);
// }
//
// Path: src/main/java/eu/delving/x3ml/engine/X3ML.java
// public enum SourceType {
//
// xpath,
// constant,
// position
// }
// Path: src/main/java/eu/delving/x3ml/engine/XPathInput.java
import static eu.delving.x3ml.X3MLEngine.exception;
import static eu.delving.x3ml.engine.X3ML.GeneratorElement;
import static eu.delving.x3ml.engine.X3ML.Helper.argVal;
import static eu.delving.x3ml.engine.X3ML.SourceType;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public X3ML.ArgValue evaluateArgument(Node node, int index, GeneratorElement generatorElement, String argName, SourceType defaultType) {
X3ML.GeneratorArg foundArg = null;
SourceType type = defaultType;
if (generatorElement.args != null) {
for (X3ML.GeneratorArg arg : generatorElement.args) {
if (arg.name == null) {
// throw exception("Argument needs a name in generator "+generatorElement.name);
arg.name = "text";
}
if (arg.name.equals(argName)) {
foundArg = arg;
type = sourceType(arg.type, defaultType);
}
}
}
X3ML.ArgValue value = null;
switch (type) {
case xpath:
if (foundArg == null) {
return null;
}
String lang = getLanguageFromSource(node);
if (lang == null) {
lang = languageFromMapping;
}
if (!foundArg.value.isEmpty()) {
value = argVal(valueAt(node, foundArg.value), lang);
if (value.string.isEmpty()) {
| throw exception("Empty result for arg " + foundArg.name + " at node " + node.getNodeName() + " in generator\n" + generatorElement);
|
delving/x3ml | src/main/java/gr/forth/GermanDate.java | // Path: src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
// public interface CustomGenerator {
// void setArg(String name, String value) throws CustomGeneratorException;
//
// String getValue() throws CustomGeneratorException;
//
// String getValueType() throws CustomGeneratorException;
//
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
// public static class CustomGeneratorException extends Exception {
// public CustomGeneratorException(String message) {
// super(message);
// }
// }
| import eu.delving.x3ml.X3MLGeneratorPolicy.CustomGenerator;
import eu.delving.x3ml.X3MLGeneratorPolicy.CustomGeneratorException;
import java.util.Date; | //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 gr.forth;
/**
* an excample date interpreter
*/
public class GermanDate implements CustomGenerator {
private String text;
private Bounds bounds;
enum Bounds {
Upper, Lower
}
@Override | // Path: src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
// public interface CustomGenerator {
// void setArg(String name, String value) throws CustomGeneratorException;
//
// String getValue() throws CustomGeneratorException;
//
// String getValueType() throws CustomGeneratorException;
//
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
// public static class CustomGeneratorException extends Exception {
// public CustomGeneratorException(String message) {
// super(message);
// }
// }
// Path: src/main/java/gr/forth/GermanDate.java
import eu.delving.x3ml.X3MLGeneratorPolicy.CustomGenerator;
import eu.delving.x3ml.X3MLGeneratorPolicy.CustomGeneratorException;
import java.util.Date;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 gr.forth;
/**
* an excample date interpreter
*/
public class GermanDate implements CustomGenerator {
private String text;
private Bounds bounds;
enum Bounds {
Upper, Lower
}
@Override | public void setArg(String name, String value) throws CustomGeneratorException { |
delving/x3ml | src/test/java/eu/delving/x3ml/AllTests.java | // Path: src/main/java/eu/delving/x3ml/engine/Generator.java
// public interface Generator {
//
// interface UUIDSource {
//
// String generateUUID();
// }
//
// void setDefaultArgType(SourceType sourceType);
//
// void setLanguageFromMapping(String language);
//
// void setNamespace(String prefix, String uri);
//
// String getLanguageFromMapping();
//
// public interface ArgValues {
//
// ArgValue getArgValue(String name, SourceType sourceType);
// }
//
// GeneratedValue generate(String name, ArgValues arguments);
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
| import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import eu.delving.x3ml.engine.Generator;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Namespace;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static eu.delving.x3ml.X3MLEngine.exception;
import static org.junit.Assert.assertTrue; | //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml;
/**
* @author Gerald de Jong <gerald@delving.eu>
*/
@RunWith(Suite.class)
@org.junit.runners.Suite.SuiteClasses({
TestConditions.class,
TestBase.class,
TestCoinA.class,
TestCoinB.class,
TestLido07.class,
TestBM.class,
TestRijks.class,
TestGML.class,
TestDoubleJoin.class
})
public class AllTests {
public static final String MISSING = "!expect : ";
public static final String CORRECT = " ";
public static final String ERROR = "!error ";
private static XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
private static XMLEventFactory eventFactory = XMLEventFactory.newInstance();
private static List<String> indentStrings = new ArrayList<String>();
public static X3MLEngine engine(String path) {
List<String> errors = X3MLEngine.validate(resource(path));
assertTrue("Invalid: " + errors, errors.isEmpty());
return X3MLEngine.load(resource(path));
}
// public static X3MLContext context(String contextPath, String policyPath) throws X3MLException {
// return X3MLContext.create(document(contextPath), policy(policyPath));
// }
//
// public static X3MLContext context(String contextPath, X3ML.ValuePolicy policy) throws X3MLException {
// return X3MLContext.create(document(contextPath), policy);
// }
// | // Path: src/main/java/eu/delving/x3ml/engine/Generator.java
// public interface Generator {
//
// interface UUIDSource {
//
// String generateUUID();
// }
//
// void setDefaultArgType(SourceType sourceType);
//
// void setLanguageFromMapping(String language);
//
// void setNamespace(String prefix, String uri);
//
// String getLanguageFromMapping();
//
// public interface ArgValues {
//
// ArgValue getArgValue(String name, SourceType sourceType);
// }
//
// GeneratedValue generate(String name, ArgValues arguments);
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
// Path: src/test/java/eu/delving/x3ml/AllTests.java
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import eu.delving.x3ml.engine.Generator;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Namespace;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static eu.delving.x3ml.X3MLEngine.exception;
import static org.junit.Assert.assertTrue;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.x3ml;
/**
* @author Gerald de Jong <gerald@delving.eu>
*/
@RunWith(Suite.class)
@org.junit.runners.Suite.SuiteClasses({
TestConditions.class,
TestBase.class,
TestCoinA.class,
TestCoinB.class,
TestLido07.class,
TestBM.class,
TestRijks.class,
TestGML.class,
TestDoubleJoin.class
})
public class AllTests {
public static final String MISSING = "!expect : ";
public static final String CORRECT = " ";
public static final String ERROR = "!error ";
private static XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
private static XMLEventFactory eventFactory = XMLEventFactory.newInstance();
private static List<String> indentStrings = new ArrayList<String>();
public static X3MLEngine engine(String path) {
List<String> errors = X3MLEngine.validate(resource(path));
assertTrue("Invalid: " + errors, errors.isEmpty());
return X3MLEngine.load(resource(path));
}
// public static X3MLContext context(String contextPath, String policyPath) throws X3MLException {
// return X3MLContext.create(document(contextPath), policy(policyPath));
// }
//
// public static X3MLContext context(String contextPath, X3ML.ValuePolicy policy) throws X3MLException {
// return X3MLContext.create(document(contextPath), policy);
// }
// | public static Generator policy(String path) { |
delving/x3ml | src/test/java/eu/delving/x3ml/AllTests.java | // Path: src/main/java/eu/delving/x3ml/engine/Generator.java
// public interface Generator {
//
// interface UUIDSource {
//
// String generateUUID();
// }
//
// void setDefaultArgType(SourceType sourceType);
//
// void setLanguageFromMapping(String language);
//
// void setNamespace(String prefix, String uri);
//
// String getLanguageFromMapping();
//
// public interface ArgValues {
//
// ArgValue getArgValue(String name, SourceType sourceType);
// }
//
// GeneratedValue generate(String name, ArgValues arguments);
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
| import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import eu.delving.x3ml.engine.Generator;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Namespace;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static eu.delving.x3ml.X3MLEngine.exception;
import static org.junit.Assert.assertTrue; | public static final String MISSING = "!expect : ";
public static final String CORRECT = " ";
public static final String ERROR = "!error ";
private static XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
private static XMLEventFactory eventFactory = XMLEventFactory.newInstance();
private static List<String> indentStrings = new ArrayList<String>();
public static X3MLEngine engine(String path) {
List<String> errors = X3MLEngine.validate(resource(path));
assertTrue("Invalid: " + errors, errors.isEmpty());
return X3MLEngine.load(resource(path));
}
// public static X3MLContext context(String contextPath, String policyPath) throws X3MLException {
// return X3MLContext.create(document(contextPath), policy(policyPath));
// }
//
// public static X3MLContext context(String contextPath, X3ML.ValuePolicy policy) throws X3MLException {
// return X3MLContext.create(document(contextPath), policy);
// }
//
public static Generator policy(String path) {
return X3MLGeneratorPolicy.load(resource(path), X3MLGeneratorPolicy.createUUIDSource(1));
}
public static Element document(String path) {
try {
return documentBuilderFactory().newDocumentBuilder().parse(resource(path)).getDocumentElement();
}
catch (Exception e) { | // Path: src/main/java/eu/delving/x3ml/engine/Generator.java
// public interface Generator {
//
// interface UUIDSource {
//
// String generateUUID();
// }
//
// void setDefaultArgType(SourceType sourceType);
//
// void setLanguageFromMapping(String language);
//
// void setNamespace(String prefix, String uri);
//
// String getLanguageFromMapping();
//
// public interface ArgValues {
//
// ArgValue getArgValue(String name, SourceType sourceType);
// }
//
// GeneratedValue generate(String name, ArgValues arguments);
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLEngine.java
// public static X3MLException exception(String message) {
// return new X3MLException(message);
// }
// Path: src/test/java/eu/delving/x3ml/AllTests.java
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import eu.delving.x3ml.engine.Generator;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Namespace;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static eu.delving.x3ml.X3MLEngine.exception;
import static org.junit.Assert.assertTrue;
public static final String MISSING = "!expect : ";
public static final String CORRECT = " ";
public static final String ERROR = "!error ";
private static XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
private static XMLEventFactory eventFactory = XMLEventFactory.newInstance();
private static List<String> indentStrings = new ArrayList<String>();
public static X3MLEngine engine(String path) {
List<String> errors = X3MLEngine.validate(resource(path));
assertTrue("Invalid: " + errors, errors.isEmpty());
return X3MLEngine.load(resource(path));
}
// public static X3MLContext context(String contextPath, String policyPath) throws X3MLException {
// return X3MLContext.create(document(contextPath), policy(policyPath));
// }
//
// public static X3MLContext context(String contextPath, X3ML.ValuePolicy policy) throws X3MLException {
// return X3MLContext.create(document(contextPath), policy);
// }
//
public static Generator policy(String path) {
return X3MLGeneratorPolicy.load(resource(path), X3MLGeneratorPolicy.createUUIDSource(1));
}
public static Element document(String path) {
try {
return documentBuilderFactory().newDocumentBuilder().parse(resource(path)).getDocumentElement();
}
catch (Exception e) { | throw exception("Unable to parse " + path); |
delving/x3ml | src/test/java/eu/delving/custom/GermanDate.java | // Path: src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
// public interface CustomGenerator {
// void setArg(String name, String value) throws CustomGeneratorException;
//
// String getValue() throws CustomGeneratorException;
//
// String getValueType() throws CustomGeneratorException;
//
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
// public static class CustomGeneratorException extends Exception {
// public CustomGeneratorException(String message) {
// super(message);
// }
// }
| import static eu.delving.x3ml.X3MLGeneratorPolicy.CustomGenerator;
import static eu.delving.x3ml.X3MLGeneratorPolicy.CustomGeneratorException; | //===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.custom;
/**
* an excample date interpreter
*/
public class GermanDate implements CustomGenerator {
private String text;
private Bounds bounds;
enum Bounds {
Upper, Lower
}
@Override | // Path: src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
// public interface CustomGenerator {
// void setArg(String name, String value) throws CustomGeneratorException;
//
// String getValue() throws CustomGeneratorException;
//
// String getValueType() throws CustomGeneratorException;
//
// }
//
// Path: src/main/java/eu/delving/x3ml/X3MLGeneratorPolicy.java
// public static class CustomGeneratorException extends Exception {
// public CustomGeneratorException(String message) {
// super(message);
// }
// }
// Path: src/test/java/eu/delving/custom/GermanDate.java
import static eu.delving.x3ml.X3MLGeneratorPolicy.CustomGenerator;
import static eu.delving.x3ml.X3MLGeneratorPolicy.CustomGeneratorException;
//===========================================================================
// Copyright 2014 Delving B.V.
//
// 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 eu.delving.custom;
/**
* an excample date interpreter
*/
public class GermanDate implements CustomGenerator {
private String text;
private Bounds bounds;
enum Bounds {
Upper, Lower
}
@Override | public void setArg(String name, String value) throws CustomGeneratorException { |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/entity/BlightFireEntity.java | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModEntities.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModEntities {
// BLIGHT_FIRE(() -> EntityType.Builder.create((type, world) -> new BlightFireEntity(world), EntityClassification.AMBIENT));
//
// private final Lazy<EntityType<?>> type;
//
// ModEntities(Supplier<EntityType.Builder<?>> factory) {
// this.type = Lazy.of(() -> {
// ResourceLocation id = ScalingHealth.getId(this.getName());
// return factory.get().build(id.toString());
// });
// }
//
// public EntityType<?> type() {
// return type.get();
// }
//
// private String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<EntityType<?>> event) {
// for (ModEntities entity : values()) {
// register(entity.getName(), entity.type());
// }
// }
//
// @SubscribeEvent
// public static void registerRenderers(FMLClientSetupEvent event) {
// RenderingRegistry.registerEntityRenderingHandler(BlightFireEntity.class, new BlightFireRenderer.Factory());
// }
//
// private static void register(String name, EntityType<?> entityType) {
// ResourceLocation id = new ResourceLocation(ScalingHealth.MOD_ID, name);
// entityType.setRegistryName(id);
// ForgeRegistries.ENTITIES.register(entityType);
// }
// }
| import net.minecraft.entity.Entity;
import net.minecraft.entity.MobEntity;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.IPacket;
import net.minecraft.world.World;
import net.minecraftforge.fml.network.NetworkHooks;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.init.ModEntities; | /*
* Scaling Health
* Copyright (C) 2018 SilentChaos512
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 3
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.silentchaos512.scalinghealth.entity;
public class BlightFireEntity extends Entity {
public BlightFireEntity(World worldIn) { | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModEntities.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModEntities {
// BLIGHT_FIRE(() -> EntityType.Builder.create((type, world) -> new BlightFireEntity(world), EntityClassification.AMBIENT));
//
// private final Lazy<EntityType<?>> type;
//
// ModEntities(Supplier<EntityType.Builder<?>> factory) {
// this.type = Lazy.of(() -> {
// ResourceLocation id = ScalingHealth.getId(this.getName());
// return factory.get().build(id.toString());
// });
// }
//
// public EntityType<?> type() {
// return type.get();
// }
//
// private String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<EntityType<?>> event) {
// for (ModEntities entity : values()) {
// register(entity.getName(), entity.type());
// }
// }
//
// @SubscribeEvent
// public static void registerRenderers(FMLClientSetupEvent event) {
// RenderingRegistry.registerEntityRenderingHandler(BlightFireEntity.class, new BlightFireRenderer.Factory());
// }
//
// private static void register(String name, EntityType<?> entityType) {
// ResourceLocation id = new ResourceLocation(ScalingHealth.MOD_ID, name);
// entityType.setRegistryName(id);
// ForgeRegistries.ENTITIES.register(entityType);
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/entity/BlightFireEntity.java
import net.minecraft.entity.Entity;
import net.minecraft.entity.MobEntity;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.IPacket;
import net.minecraft.world.World;
import net.minecraftforge.fml.network.NetworkHooks;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.init.ModEntities;
/*
* Scaling Health
* Copyright (C) 2018 SilentChaos512
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 3
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.silentchaos512.scalinghealth.entity;
public class BlightFireEntity extends Entity {
public BlightFireEntity(World worldIn) { | super(ModEntities.BLIGHT_FIRE.type(), worldIn); |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/entity/BlightFireEntity.java | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModEntities.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModEntities {
// BLIGHT_FIRE(() -> EntityType.Builder.create((type, world) -> new BlightFireEntity(world), EntityClassification.AMBIENT));
//
// private final Lazy<EntityType<?>> type;
//
// ModEntities(Supplier<EntityType.Builder<?>> factory) {
// this.type = Lazy.of(() -> {
// ResourceLocation id = ScalingHealth.getId(this.getName());
// return factory.get().build(id.toString());
// });
// }
//
// public EntityType<?> type() {
// return type.get();
// }
//
// private String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<EntityType<?>> event) {
// for (ModEntities entity : values()) {
// register(entity.getName(), entity.type());
// }
// }
//
// @SubscribeEvent
// public static void registerRenderers(FMLClientSetupEvent event) {
// RenderingRegistry.registerEntityRenderingHandler(BlightFireEntity.class, new BlightFireRenderer.Factory());
// }
//
// private static void register(String name, EntityType<?> entityType) {
// ResourceLocation id = new ResourceLocation(ScalingHealth.MOD_ID, name);
// entityType.setRegistryName(id);
// ForgeRegistries.ENTITIES.register(entityType);
// }
// }
| import net.minecraft.entity.Entity;
import net.minecraft.entity.MobEntity;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.IPacket;
import net.minecraft.world.World;
import net.minecraftforge.fml.network.NetworkHooks;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.init.ModEntities; | /*
* Scaling Health
* Copyright (C) 2018 SilentChaos512
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 3
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.silentchaos512.scalinghealth.entity;
public class BlightFireEntity extends Entity {
public BlightFireEntity(World worldIn) {
super(ModEntities.BLIGHT_FIRE.type(), worldIn);
}
public BlightFireEntity(MobEntity p) {
this(p.world);
this.startRiding(p);
}
@Override
protected void registerData() {
}
@Override
public void tick() {
// Server side only, blight fire must have a parent.
if(world.isRemote) return;
Entity parent = this.getRidingEntity();
if (parent == null || !parent.isAlive()) { | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModEntities.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModEntities {
// BLIGHT_FIRE(() -> EntityType.Builder.create((type, world) -> new BlightFireEntity(world), EntityClassification.AMBIENT));
//
// private final Lazy<EntityType<?>> type;
//
// ModEntities(Supplier<EntityType.Builder<?>> factory) {
// this.type = Lazy.of(() -> {
// ResourceLocation id = ScalingHealth.getId(this.getName());
// return factory.get().build(id.toString());
// });
// }
//
// public EntityType<?> type() {
// return type.get();
// }
//
// private String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<EntityType<?>> event) {
// for (ModEntities entity : values()) {
// register(entity.getName(), entity.type());
// }
// }
//
// @SubscribeEvent
// public static void registerRenderers(FMLClientSetupEvent event) {
// RenderingRegistry.registerEntityRenderingHandler(BlightFireEntity.class, new BlightFireRenderer.Factory());
// }
//
// private static void register(String name, EntityType<?> entityType) {
// ResourceLocation id = new ResourceLocation(ScalingHealth.MOD_ID, name);
// entityType.setRegistryName(id);
// ForgeRegistries.ENTITIES.register(entityType);
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/entity/BlightFireEntity.java
import net.minecraft.entity.Entity;
import net.minecraft.entity.MobEntity;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.IPacket;
import net.minecraft.world.World;
import net.minecraftforge.fml.network.NetworkHooks;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.init.ModEntities;
/*
* Scaling Health
* Copyright (C) 2018 SilentChaos512
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 3
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.silentchaos512.scalinghealth.entity;
public class BlightFireEntity extends Entity {
public BlightFireEntity(World worldIn) {
super(ModEntities.BLIGHT_FIRE.type(), worldIn);
}
public BlightFireEntity(MobEntity p) {
this(p.world);
this.startRiding(p);
}
@Override
protected void registerData() {
}
@Override
public void tick() {
// Server side only, blight fire must have a parent.
if(world.isRemote) return;
Entity parent = this.getRidingEntity();
if (parent == null || !parent.isAlive()) { | if (ScalingHealth.LOGGER.isDebugEnabled()) { |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/datagen/SHTags.java | // Path: src/main/java/net/silentchaos512/scalinghealth/tags/EntityTags.java
// public class EntityTags {
// public static final Tag<EntityType<?>> DIFFICULTY_EXEMPT = new EntityTypeTags.Wrapper(ScalingHealth.getId("difficulty_exempt"));
// public static final Tag<EntityType<?>> BLIGHT_EXEMPT = new EntityTypeTags.Wrapper(ScalingHealth.getId("blight_exempt"));
// }
| import net.minecraft.data.DataGenerator;
import net.minecraft.data.EntityTypeTagsProvider;
import net.silentchaos512.scalinghealth.tags.EntityTags;
import static net.minecraft.entity.EntityType.*; | package net.silentchaos512.scalinghealth.datagen;
public class SHTags extends EntityTypeTagsProvider {
public SHTags(DataGenerator generator) {
super(generator);
}
@Override
protected void registerTags() { | // Path: src/main/java/net/silentchaos512/scalinghealth/tags/EntityTags.java
// public class EntityTags {
// public static final Tag<EntityType<?>> DIFFICULTY_EXEMPT = new EntityTypeTags.Wrapper(ScalingHealth.getId("difficulty_exempt"));
// public static final Tag<EntityType<?>> BLIGHT_EXEMPT = new EntityTypeTags.Wrapper(ScalingHealth.getId("blight_exempt"));
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/datagen/SHTags.java
import net.minecraft.data.DataGenerator;
import net.minecraft.data.EntityTypeTagsProvider;
import net.silentchaos512.scalinghealth.tags.EntityTags;
import static net.minecraft.entity.EntityType.*;
package net.silentchaos512.scalinghealth.datagen;
public class SHTags extends EntityTypeTagsProvider {
public SHTags(DataGenerator generator) {
super(generator);
}
@Override
protected void registerTags() { | this.getBuilder(EntityTags.BLIGHT_EXEMPT).add(BAT, CAT, CHICKEN, COD, COW, DONKEY, FOX, HORSE, MOOSHROOM, MULE, |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/network/Network.java | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/client/ClientHandler.java
// public final class ClientHandler {
// private static final Marker MARKER = MarkerManager.getMarker("ClientHandler");
// // Frequent updates (up to once per second)
// public static float playerDifficulty;
// public static float areaDifficulty;
// public static int regenTimer;
// public static int locationMultiPercent;
// // Infrequent updates (join server/world, travel to new dimension)
// public static AreaDifficultyMode areaMode = AreaDifficultyMode.WEIGHTED_AVERAGE;
// public static float maxDifficultyValue;
//
// private ClientHandler() {}
//
// public static void onMessage(ClientSyncMessage msg, Supplier<NetworkEvent.Context> ctx) {
// ctx.get().enqueueWork(() -> handleSyncMessage(msg));
// ctx.get().setPacketHandled(true);
// }
//
// private static void handleSyncMessage(ClientSyncMessage msg) {
// playerDifficulty = msg.playerDifficulty;
// areaDifficulty = msg.areaDifficulty;
// regenTimer = msg.regenTimer;
// locationMultiPercent = msg.locationMultiPercent;
//
// Minecraft mc = Minecraft.getInstance();
// ClientPlayerEntity player = mc.player;
// if (player != null) {
// player.experienceLevel = msg.experienceLevel;
// }
// }
//
// public static void onLoginMessage(ClientLoginMessage msg, Supplier<NetworkEvent.Context> ctx) {
// ctx.get().enqueueWork(() -> handleLoginMessage(msg));
// ctx.get().setPacketHandled(true);
// }
//
// private static void handleLoginMessage(ClientLoginMessage msg) {
// ScalingHealth.LOGGER.info(MARKER, "Processing login packet");
// areaMode = msg.areaMode;
// maxDifficultyValue = msg.maxDifficultyValue;
// ScalingHealth.LOGGER.info(MARKER, "World area mode: {}", areaMode.getDisplayName().getFormattedText());
// ScalingHealth.LOGGER.info(MARKER, "World max difficulty: {}", maxDifficultyValue);
// }
// }
| import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.network.NetworkRegistry;
import net.minecraftforge.fml.network.simple.SimpleChannel;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.client.ClientHandler;
import java.util.Objects; | package net.silentchaos512.scalinghealth.network;
public final class Network {
private static final ResourceLocation NAME = ScalingHealth.getId("network");
public static SimpleChannel channel;
static {
channel = NetworkRegistry.ChannelBuilder.named(NAME)
.clientAcceptedVersions(s -> Objects.equals(s, "1"))
.serverAcceptedVersions(s -> Objects.equals(s, "1"))
.networkProtocolVersion(() -> "1")
.simpleChannel();
channel.messageBuilder(ClientSyncMessage.class, 1)
.decoder(ClientSyncMessage::fromBytes)
.encoder(ClientSyncMessage::toBytes) | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/client/ClientHandler.java
// public final class ClientHandler {
// private static final Marker MARKER = MarkerManager.getMarker("ClientHandler");
// // Frequent updates (up to once per second)
// public static float playerDifficulty;
// public static float areaDifficulty;
// public static int regenTimer;
// public static int locationMultiPercent;
// // Infrequent updates (join server/world, travel to new dimension)
// public static AreaDifficultyMode areaMode = AreaDifficultyMode.WEIGHTED_AVERAGE;
// public static float maxDifficultyValue;
//
// private ClientHandler() {}
//
// public static void onMessage(ClientSyncMessage msg, Supplier<NetworkEvent.Context> ctx) {
// ctx.get().enqueueWork(() -> handleSyncMessage(msg));
// ctx.get().setPacketHandled(true);
// }
//
// private static void handleSyncMessage(ClientSyncMessage msg) {
// playerDifficulty = msg.playerDifficulty;
// areaDifficulty = msg.areaDifficulty;
// regenTimer = msg.regenTimer;
// locationMultiPercent = msg.locationMultiPercent;
//
// Minecraft mc = Minecraft.getInstance();
// ClientPlayerEntity player = mc.player;
// if (player != null) {
// player.experienceLevel = msg.experienceLevel;
// }
// }
//
// public static void onLoginMessage(ClientLoginMessage msg, Supplier<NetworkEvent.Context> ctx) {
// ctx.get().enqueueWork(() -> handleLoginMessage(msg));
// ctx.get().setPacketHandled(true);
// }
//
// private static void handleLoginMessage(ClientLoginMessage msg) {
// ScalingHealth.LOGGER.info(MARKER, "Processing login packet");
// areaMode = msg.areaMode;
// maxDifficultyValue = msg.maxDifficultyValue;
// ScalingHealth.LOGGER.info(MARKER, "World area mode: {}", areaMode.getDisplayName().getFormattedText());
// ScalingHealth.LOGGER.info(MARKER, "World max difficulty: {}", maxDifficultyValue);
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/network/Network.java
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.network.NetworkRegistry;
import net.minecraftforge.fml.network.simple.SimpleChannel;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.client.ClientHandler;
import java.util.Objects;
package net.silentchaos512.scalinghealth.network;
public final class Network {
private static final ResourceLocation NAME = ScalingHealth.getId("network");
public static SimpleChannel channel;
static {
channel = NetworkRegistry.ChannelBuilder.named(NAME)
.clientAcceptedVersions(s -> Objects.equals(s, "1"))
.serverAcceptedVersions(s -> Objects.equals(s, "1"))
.networkProtocolVersion(() -> "1")
.simpleChannel();
channel.messageBuilder(ClientSyncMessage.class, 1)
.decoder(ClientSyncMessage::fromBytes)
.encoder(ClientSyncMessage::toBytes) | .consumer(ClientHandler::onMessage) |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/datagen/Recipes.java | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModItems.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModItems implements IItemProvider {
// HEART_CRYSTAL(HeartCrystal::new),
// HEART_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// HEART_DUST(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// POWER_CRYSTAL(PowerCrystal::new),
// POWER_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// BANDAGES(() -> new HealingItem(0.3f, 1)),
// MEDKIT(() -> new HealingItem(0.7f, 4)),
// CURSED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CURSED)),
// ENCHANTED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.ENCHANTED)),
// CHANCE_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CHANCE));
//
// private final Lazy<Item> item;
//
// ModItems(Supplier<Item> factory) {
// item = Lazy.of(factory);
// }
//
// @Override
// public Item asItem() {
// return item.get();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// static final Collection<BlockItem> blocksToRegister = new ArrayList<>();
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Item> event) {
// blocksToRegister.forEach(ForgeRegistries.ITEMS::register);
//
// for (ModItems item : values()) {
// register(item.getName(), item.asItem());
// }
// }
//
// private static void register(String name, Item item) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// item.setRegistryName(registryName);
// ForgeRegistries.ITEMS.register(item);
// }
// }
| import net.minecraft.advancements.ICriterionInstance;
import net.minecraft.advancements.criterion.InventoryChangeTrigger;
import net.minecraft.data.*;
import net.minecraft.item.Items;
import net.minecraft.util.IItemProvider;
import net.minecraftforge.common.Tags;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.init.ModItems;
import java.util.function.Consumer; | package net.silentchaos512.scalinghealth.datagen;
public class Recipes extends RecipeProvider {
public Recipes (DataGenerator gen) {
super(gen);
}
@Override
protected void registerRecipes(Consumer<IFinishedRecipe> consumer) { | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModItems.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModItems implements IItemProvider {
// HEART_CRYSTAL(HeartCrystal::new),
// HEART_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// HEART_DUST(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// POWER_CRYSTAL(PowerCrystal::new),
// POWER_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// BANDAGES(() -> new HealingItem(0.3f, 1)),
// MEDKIT(() -> new HealingItem(0.7f, 4)),
// CURSED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CURSED)),
// ENCHANTED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.ENCHANTED)),
// CHANCE_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CHANCE));
//
// private final Lazy<Item> item;
//
// ModItems(Supplier<Item> factory) {
// item = Lazy.of(factory);
// }
//
// @Override
// public Item asItem() {
// return item.get();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// static final Collection<BlockItem> blocksToRegister = new ArrayList<>();
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Item> event) {
// blocksToRegister.forEach(ForgeRegistries.ITEMS::register);
//
// for (ModItems item : values()) {
// register(item.getName(), item.asItem());
// }
// }
//
// private static void register(String name, Item item) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// item.setRegistryName(registryName);
// ForgeRegistries.ITEMS.register(item);
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/datagen/Recipes.java
import net.minecraft.advancements.ICriterionInstance;
import net.minecraft.advancements.criterion.InventoryChangeTrigger;
import net.minecraft.data.*;
import net.minecraft.item.Items;
import net.minecraft.util.IItemProvider;
import net.minecraftforge.common.Tags;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.init.ModItems;
import java.util.function.Consumer;
package net.silentchaos512.scalinghealth.datagen;
public class Recipes extends RecipeProvider {
public Recipes (DataGenerator gen) {
super(gen);
}
@Override
protected void registerRecipes(Consumer<IFinishedRecipe> consumer) { | fullBlockRecipe(consumer, ModItems.HEART_CRYSTAL, ModItems.HEART_CRYSTAL_SHARD); |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/datagen/Recipes.java | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModItems.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModItems implements IItemProvider {
// HEART_CRYSTAL(HeartCrystal::new),
// HEART_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// HEART_DUST(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// POWER_CRYSTAL(PowerCrystal::new),
// POWER_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// BANDAGES(() -> new HealingItem(0.3f, 1)),
// MEDKIT(() -> new HealingItem(0.7f, 4)),
// CURSED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CURSED)),
// ENCHANTED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.ENCHANTED)),
// CHANCE_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CHANCE));
//
// private final Lazy<Item> item;
//
// ModItems(Supplier<Item> factory) {
// item = Lazy.of(factory);
// }
//
// @Override
// public Item asItem() {
// return item.get();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// static final Collection<BlockItem> blocksToRegister = new ArrayList<>();
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Item> event) {
// blocksToRegister.forEach(ForgeRegistries.ITEMS::register);
//
// for (ModItems item : values()) {
// register(item.getName(), item.asItem());
// }
// }
//
// private static void register(String name, Item item) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// item.setRegistryName(registryName);
// ForgeRegistries.ITEMS.register(item);
// }
// }
| import net.minecraft.advancements.ICriterionInstance;
import net.minecraft.advancements.criterion.InventoryChangeTrigger;
import net.minecraft.data.*;
import net.minecraft.item.Items;
import net.minecraft.util.IItemProvider;
import net.minecraftforge.common.Tags;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.init.ModItems;
import java.util.function.Consumer; | package net.silentchaos512.scalinghealth.datagen;
public class Recipes extends RecipeProvider {
public Recipes (DataGenerator gen) {
super(gen);
}
@Override
protected void registerRecipes(Consumer<IFinishedRecipe> consumer) {
fullBlockRecipe(consumer, ModItems.HEART_CRYSTAL, ModItems.HEART_CRYSTAL_SHARD);
fullBlockRecipe(consumer, ModItems.POWER_CRYSTAL, ModItems.POWER_CRYSTAL_SHARD);
ShapelessRecipeBuilder.shapelessRecipe(ModItems.HEART_DUST, 24)
.addIngredient(ModItems.HEART_CRYSTAL)
.addCriterion("cobblestone", getDefaultTrigger()) | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModItems.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModItems implements IItemProvider {
// HEART_CRYSTAL(HeartCrystal::new),
// HEART_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// HEART_DUST(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// POWER_CRYSTAL(PowerCrystal::new),
// POWER_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// BANDAGES(() -> new HealingItem(0.3f, 1)),
// MEDKIT(() -> new HealingItem(0.7f, 4)),
// CURSED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CURSED)),
// ENCHANTED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.ENCHANTED)),
// CHANCE_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CHANCE));
//
// private final Lazy<Item> item;
//
// ModItems(Supplier<Item> factory) {
// item = Lazy.of(factory);
// }
//
// @Override
// public Item asItem() {
// return item.get();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// static final Collection<BlockItem> blocksToRegister = new ArrayList<>();
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Item> event) {
// blocksToRegister.forEach(ForgeRegistries.ITEMS::register);
//
// for (ModItems item : values()) {
// register(item.getName(), item.asItem());
// }
// }
//
// private static void register(String name, Item item) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// item.setRegistryName(registryName);
// ForgeRegistries.ITEMS.register(item);
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/datagen/Recipes.java
import net.minecraft.advancements.ICriterionInstance;
import net.minecraft.advancements.criterion.InventoryChangeTrigger;
import net.minecraft.data.*;
import net.minecraft.item.Items;
import net.minecraft.util.IItemProvider;
import net.minecraftforge.common.Tags;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.init.ModItems;
import java.util.function.Consumer;
package net.silentchaos512.scalinghealth.datagen;
public class Recipes extends RecipeProvider {
public Recipes (DataGenerator gen) {
super(gen);
}
@Override
protected void registerRecipes(Consumer<IFinishedRecipe> consumer) {
fullBlockRecipe(consumer, ModItems.HEART_CRYSTAL, ModItems.HEART_CRYSTAL_SHARD);
fullBlockRecipe(consumer, ModItems.POWER_CRYSTAL, ModItems.POWER_CRYSTAL_SHARD);
ShapelessRecipeBuilder.shapelessRecipe(ModItems.HEART_DUST, 24)
.addIngredient(ModItems.HEART_CRYSTAL)
.addCriterion("cobblestone", getDefaultTrigger()) | .setGroup(ScalingHealth.MOD_ID) |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/client/render/entity/BlightFireRenderer.java | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/entity/BlightFireEntity.java
// public class BlightFireEntity extends Entity {
// public BlightFireEntity(World worldIn) {
// super(ModEntities.BLIGHT_FIRE.type(), worldIn);
// }
//
// public BlightFireEntity(MobEntity p) {
// this(p.world);
// this.startRiding(p);
// }
//
// @Override
// protected void registerData() {
//
// }
//
// @Override
// public void tick() {
// // Server side only, blight fire must have a parent.
// if(world.isRemote) return;
// Entity parent = this.getRidingEntity();
// if (parent == null || !parent.isAlive()) {
// if (ScalingHealth.LOGGER.isDebugEnabled()) {
// ScalingHealth.LOGGER.debug("Removed blight fire (parent missing or dead)");
// }
// remove();
// }
// }
//
// @Override
// public int getBrightnessForRender() {
// return 15728880;
// }
//
// @Override
// protected void readAdditional(CompoundNBT compound) {
//
// }
//
// @Override
// protected void writeAdditional(CompoundNBT compound) {
//
// }
//
// @Override
// public IPacket<?> createSpawnPacket() {
// ScalingHealth.LOGGER.debug("Blight Fire spawned on the SERVER");
// return NetworkHooks.getEntitySpawningPacket(this);
// }
// }
| import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.entity.BlightFireEntity;
import javax.annotation.Nonnull;
import com.mojang.blaze3d.platform.GlStateManager;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.culling.ICamera;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.client.renderer.entity.EntityRendererManager;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.entity.MobEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraftforge.fml.client.registry.IRenderFactory;
import net.silentchaos512.lib.event.ClientTicks; | /*
* Scaling Health
* Copyright (C) 2018 SilentChaos512
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 3
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.silentchaos512.scalinghealth.client.render.entity;
public final class BlightFireRenderer extends EntityRenderer<BlightFireEntity> {
private static final float FIRE_SCALE = 1.8F;
| // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/entity/BlightFireEntity.java
// public class BlightFireEntity extends Entity {
// public BlightFireEntity(World worldIn) {
// super(ModEntities.BLIGHT_FIRE.type(), worldIn);
// }
//
// public BlightFireEntity(MobEntity p) {
// this(p.world);
// this.startRiding(p);
// }
//
// @Override
// protected void registerData() {
//
// }
//
// @Override
// public void tick() {
// // Server side only, blight fire must have a parent.
// if(world.isRemote) return;
// Entity parent = this.getRidingEntity();
// if (parent == null || !parent.isAlive()) {
// if (ScalingHealth.LOGGER.isDebugEnabled()) {
// ScalingHealth.LOGGER.debug("Removed blight fire (parent missing or dead)");
// }
// remove();
// }
// }
//
// @Override
// public int getBrightnessForRender() {
// return 15728880;
// }
//
// @Override
// protected void readAdditional(CompoundNBT compound) {
//
// }
//
// @Override
// protected void writeAdditional(CompoundNBT compound) {
//
// }
//
// @Override
// public IPacket<?> createSpawnPacket() {
// ScalingHealth.LOGGER.debug("Blight Fire spawned on the SERVER");
// return NetworkHooks.getEntitySpawningPacket(this);
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/client/render/entity/BlightFireRenderer.java
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.entity.BlightFireEntity;
import javax.annotation.Nonnull;
import com.mojang.blaze3d.platform.GlStateManager;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.culling.ICamera;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.client.renderer.entity.EntityRendererManager;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.entity.MobEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraftforge.fml.client.registry.IRenderFactory;
import net.silentchaos512.lib.event.ClientTicks;
/*
* Scaling Health
* Copyright (C) 2018 SilentChaos512
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 3
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.silentchaos512.scalinghealth.client.render.entity;
public final class BlightFireRenderer extends EntityRenderer<BlightFireEntity> {
private static final float FIRE_SCALE = 1.8F;
| private static final ResourceLocation TEXTURE = ScalingHealth.getId("textures/entity/blightfire.png"); |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/client/particles/ModParticle.java | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
| import net.minecraft.client.Minecraft;
import net.minecraft.client.particle.IParticleFactory;
import net.minecraft.client.particle.IParticleRenderType;
import net.minecraft.client.particle.Particle;
import net.minecraft.client.particle.TexturedParticle;
import net.minecraft.client.renderer.ActiveRenderInfo;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.particles.BasicParticleType;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.utils.Color;
import net.silentchaos512.utils.MathUtils;
import javax.annotation.Nullable;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream; | package net.silentchaos512.scalinghealth.client.particles;
@OnlyIn(Dist.CLIENT)
public class ModParticle extends TexturedParticle {
private static final List<ResourceLocation> TEXTURES = IntStream.range(0, 4).boxed() | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/client/particles/ModParticle.java
import net.minecraft.client.Minecraft;
import net.minecraft.client.particle.IParticleFactory;
import net.minecraft.client.particle.IParticleRenderType;
import net.minecraft.client.particle.Particle;
import net.minecraft.client.particle.TexturedParticle;
import net.minecraft.client.renderer.ActiveRenderInfo;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.particles.BasicParticleType;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.utils.Color;
import net.silentchaos512.utils.MathUtils;
import javax.annotation.Nullable;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
package net.silentchaos512.scalinghealth.client.particles;
@OnlyIn(Dist.CLIENT)
public class ModParticle extends TexturedParticle {
private static final List<ResourceLocation> TEXTURES = IntStream.range(0, 4).boxed() | .map(k -> new ResourceLocation(ScalingHealth.MOD_ID, "textures/particle/generic" + k + ".png")) |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/config/MobPotionConfig.java | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/lib/EntityGroup.java
// public enum EntityGroup {
// PEACEFUL,
// HOSTILE,
// BOSS,
// BLIGHT,
// PLAYER;
//
// public static EntityGroup from(String name) {
// for(EntityGroup group : values()){
// if(group.name().equalsIgnoreCase(name)){
// return group;
// }
// }
// throw new RuntimeException("Could not get an entity group from name: " + name);
// }
//
// public static EntityGroup from(LivingEntity entity) {
// return from(entity, false);
// }
//
// public static EntityGroup from(LivingEntity entity, boolean ignoreBlightStatus) {
// if (entity instanceof PlayerEntity)
// return PLAYER;
// if (!entity.isNonBoss())
// return BOSS;
// if (entity instanceof IMob) {
// if (!ignoreBlightStatus && SHMobs.isBlight((MobEntity) entity))
// return BLIGHT;
// return HOSTILE;
// }
// return PEACEFUL;
// }
//
// public double getPotionChance() {
// if (this == PEACEFUL)
// return SHMobs.passivePotionChance();
// return SHMobs.hostilePotionChance();
// }
//
// public MobHealthMode getHealthMode() {
// return SHMobs.healthMode();
// }
//
// public boolean isAffectedByDamageScaling() {
// switch (this) {
// case PLAYER:
// return EnabledFeatures.playerDamageScalingEnabled();
// case PEACEFUL:
// return Config.GENERAL.damageScaling.affectPeacefuls.get();
// default:
// return Config.GENERAL.damageScaling.affectHostiles.get();
// }
// }
// }
| import com.electronwill.nightconfig.core.CommentedConfig;
import com.electronwill.nightconfig.core.ConfigSpec;
import net.minecraft.entity.LivingEntity;
import net.minecraft.potion.Effect;
import net.minecraft.potion.EffectInstance;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistries;
import net.silentchaos512.lib.util.TimeUtils;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.lib.EntityGroup;
import net.silentchaos512.utils.Lazy;
import net.silentchaos512.utils.MathUtils;
import net.silentchaos512.utils.config.ConfigSpecWrapper;
import net.silentchaos512.utils.config.ConfigValue;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors; | package net.silentchaos512.scalinghealth.config;
public class MobPotionConfig {
private static final Marker MARKER = MarkerManager.getMarker("MobPotionConfig");
private Lazy<List<EffectEntry>> potions;
private final List<EffectEntry> temp = new ArrayList<>();
public void tryApply(LivingEntity entity, double difficulty) { | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/lib/EntityGroup.java
// public enum EntityGroup {
// PEACEFUL,
// HOSTILE,
// BOSS,
// BLIGHT,
// PLAYER;
//
// public static EntityGroup from(String name) {
// for(EntityGroup group : values()){
// if(group.name().equalsIgnoreCase(name)){
// return group;
// }
// }
// throw new RuntimeException("Could not get an entity group from name: " + name);
// }
//
// public static EntityGroup from(LivingEntity entity) {
// return from(entity, false);
// }
//
// public static EntityGroup from(LivingEntity entity, boolean ignoreBlightStatus) {
// if (entity instanceof PlayerEntity)
// return PLAYER;
// if (!entity.isNonBoss())
// return BOSS;
// if (entity instanceof IMob) {
// if (!ignoreBlightStatus && SHMobs.isBlight((MobEntity) entity))
// return BLIGHT;
// return HOSTILE;
// }
// return PEACEFUL;
// }
//
// public double getPotionChance() {
// if (this == PEACEFUL)
// return SHMobs.passivePotionChance();
// return SHMobs.hostilePotionChance();
// }
//
// public MobHealthMode getHealthMode() {
// return SHMobs.healthMode();
// }
//
// public boolean isAffectedByDamageScaling() {
// switch (this) {
// case PLAYER:
// return EnabledFeatures.playerDamageScalingEnabled();
// case PEACEFUL:
// return Config.GENERAL.damageScaling.affectPeacefuls.get();
// default:
// return Config.GENERAL.damageScaling.affectHostiles.get();
// }
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/config/MobPotionConfig.java
import com.electronwill.nightconfig.core.CommentedConfig;
import com.electronwill.nightconfig.core.ConfigSpec;
import net.minecraft.entity.LivingEntity;
import net.minecraft.potion.Effect;
import net.minecraft.potion.EffectInstance;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistries;
import net.silentchaos512.lib.util.TimeUtils;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.lib.EntityGroup;
import net.silentchaos512.utils.Lazy;
import net.silentchaos512.utils.MathUtils;
import net.silentchaos512.utils.config.ConfigSpecWrapper;
import net.silentchaos512.utils.config.ConfigValue;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
package net.silentchaos512.scalinghealth.config;
public class MobPotionConfig {
private static final Marker MARKER = MarkerManager.getMarker("MobPotionConfig");
private Lazy<List<EffectEntry>> potions;
private final List<EffectEntry> temp = new ArrayList<>();
public void tryApply(LivingEntity entity, double difficulty) { | double chance = EntityGroup.from(entity).getPotionChance(); |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/network/SpawnBlightFirePacket.java | // Path: src/main/java/net/silentchaos512/scalinghealth/entity/BlightFireEntity.java
// public class BlightFireEntity extends Entity {
// public BlightFireEntity(World worldIn) {
// super(ModEntities.BLIGHT_FIRE.type(), worldIn);
// }
//
// public BlightFireEntity(MobEntity p) {
// this(p.world);
// this.startRiding(p);
// }
//
// @Override
// protected void registerData() {
//
// }
//
// @Override
// public void tick() {
// // Server side only, blight fire must have a parent.
// if(world.isRemote) return;
// Entity parent = this.getRidingEntity();
// if (parent == null || !parent.isAlive()) {
// if (ScalingHealth.LOGGER.isDebugEnabled()) {
// ScalingHealth.LOGGER.debug("Removed blight fire (parent missing or dead)");
// }
// remove();
// }
// }
//
// @Override
// public int getBrightnessForRender() {
// return 15728880;
// }
//
// @Override
// protected void readAdditional(CompoundNBT compound) {
//
// }
//
// @Override
// protected void writeAdditional(CompoundNBT compound) {
//
// }
//
// @Override
// public IPacket<?> createSpawnPacket() {
// ScalingHealth.LOGGER.debug("Blight Fire spawned on the SERVER");
// return NetworkHooks.getEntitySpawningPacket(this);
// }
// }
| import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.MobEntity;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.fml.network.NetworkDirection;
import net.minecraftforge.fml.network.NetworkEvent;
import net.silentchaos512.scalinghealth.entity.BlightFireEntity;
import javax.annotation.Nullable;
import java.util.function.Supplier; | package net.silentchaos512.scalinghealth.network;
public class SpawnBlightFirePacket {
private int parentId;
public SpawnBlightFirePacket() {
}
public SpawnBlightFirePacket(MobEntity parent) {
this.parentId = parent.getEntityId();
}
public static SpawnBlightFirePacket fromBytes(PacketBuffer buffer) {
SpawnBlightFirePacket packet = new SpawnBlightFirePacket();
packet.parentId = buffer.readVarInt();
return packet;
}
public void toBytes(PacketBuffer buffer) {
buffer.writeVarInt(this.parentId);
}
public static void handle(SpawnBlightFirePacket packet, Supplier<NetworkEvent.Context> context) {
context.get().enqueueWork(() -> {
if(context.get().getDirection() == NetworkDirection.PLAY_TO_SERVER){
Entity entity = getTargetEntity(packet.parentId);
if (entity instanceof MobEntity) { | // Path: src/main/java/net/silentchaos512/scalinghealth/entity/BlightFireEntity.java
// public class BlightFireEntity extends Entity {
// public BlightFireEntity(World worldIn) {
// super(ModEntities.BLIGHT_FIRE.type(), worldIn);
// }
//
// public BlightFireEntity(MobEntity p) {
// this(p.world);
// this.startRiding(p);
// }
//
// @Override
// protected void registerData() {
//
// }
//
// @Override
// public void tick() {
// // Server side only, blight fire must have a parent.
// if(world.isRemote) return;
// Entity parent = this.getRidingEntity();
// if (parent == null || !parent.isAlive()) {
// if (ScalingHealth.LOGGER.isDebugEnabled()) {
// ScalingHealth.LOGGER.debug("Removed blight fire (parent missing or dead)");
// }
// remove();
// }
// }
//
// @Override
// public int getBrightnessForRender() {
// return 15728880;
// }
//
// @Override
// protected void readAdditional(CompoundNBT compound) {
//
// }
//
// @Override
// protected void writeAdditional(CompoundNBT compound) {
//
// }
//
// @Override
// public IPacket<?> createSpawnPacket() {
// ScalingHealth.LOGGER.debug("Blight Fire spawned on the SERVER");
// return NetworkHooks.getEntitySpawningPacket(this);
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/network/SpawnBlightFirePacket.java
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.MobEntity;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.fml.network.NetworkDirection;
import net.minecraftforge.fml.network.NetworkEvent;
import net.silentchaos512.scalinghealth.entity.BlightFireEntity;
import javax.annotation.Nullable;
import java.util.function.Supplier;
package net.silentchaos512.scalinghealth.network;
public class SpawnBlightFirePacket {
private int parentId;
public SpawnBlightFirePacket() {
}
public SpawnBlightFirePacket(MobEntity parent) {
this.parentId = parent.getEntityId();
}
public static SpawnBlightFirePacket fromBytes(PacketBuffer buffer) {
SpawnBlightFirePacket packet = new SpawnBlightFirePacket();
packet.parentId = buffer.readVarInt();
return packet;
}
public void toBytes(PacketBuffer buffer) {
buffer.writeVarInt(this.parentId);
}
public static void handle(SpawnBlightFirePacket packet, Supplier<NetworkEvent.Context> context) {
context.get().enqueueWork(() -> {
if(context.get().getDirection() == NetworkDirection.PLAY_TO_SERVER){
Entity entity = getTargetEntity(packet.parentId);
if (entity instanceof MobEntity) { | entity.world.addEntity(new BlightFireEntity((MobEntity) entity)); |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/capability/DifficultySourceCapability.java | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
| import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.INBT;
import net.minecraft.util.Direction;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.common.capabilities.*;
import net.minecraftforge.common.util.LazyOptional;
import net.silentchaos512.scalinghealth.ScalingHealth;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Optional; | package net.silentchaos512.scalinghealth.capability;
public class DifficultySourceCapability implements IDifficultySource, ICapabilitySerializable<CompoundNBT> {
@CapabilityInject(IDifficultySource.class)
public static Capability<IDifficultySource> INSTANCE = null;
| // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/capability/DifficultySourceCapability.java
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.INBT;
import net.minecraft.util.Direction;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.common.capabilities.*;
import net.minecraftforge.common.util.LazyOptional;
import net.silentchaos512.scalinghealth.ScalingHealth;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Optional;
package net.silentchaos512.scalinghealth.capability;
public class DifficultySourceCapability implements IDifficultySource, ICapabilitySerializable<CompoundNBT> {
@CapabilityInject(IDifficultySource.class)
public static Capability<IDifficultySource> INSTANCE = null;
| public static ResourceLocation NAME = ScalingHealth.getId("difficulty_source"); |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/loot/conditions/EntityGroupCondition.java | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/lib/EntityGroup.java
// public enum EntityGroup {
// PEACEFUL,
// HOSTILE,
// BOSS,
// BLIGHT,
// PLAYER;
//
// public static EntityGroup from(String name) {
// for(EntityGroup group : values()){
// if(group.name().equalsIgnoreCase(name)){
// return group;
// }
// }
// throw new RuntimeException("Could not get an entity group from name: " + name);
// }
//
// public static EntityGroup from(LivingEntity entity) {
// return from(entity, false);
// }
//
// public static EntityGroup from(LivingEntity entity, boolean ignoreBlightStatus) {
// if (entity instanceof PlayerEntity)
// return PLAYER;
// if (!entity.isNonBoss())
// return BOSS;
// if (entity instanceof IMob) {
// if (!ignoreBlightStatus && SHMobs.isBlight((MobEntity) entity))
// return BLIGHT;
// return HOSTILE;
// }
// return PEACEFUL;
// }
//
// public double getPotionChance() {
// if (this == PEACEFUL)
// return SHMobs.passivePotionChance();
// return SHMobs.hostilePotionChance();
// }
//
// public MobHealthMode getHealthMode() {
// return SHMobs.healthMode();
// }
//
// public boolean isAffectedByDamageScaling() {
// switch (this) {
// case PLAYER:
// return EnabledFeatures.playerDamageScalingEnabled();
// case PEACEFUL:
// return Config.GENERAL.damageScaling.affectPeacefuls.get();
// default:
// return Config.GENERAL.damageScaling.affectHostiles.get();
// }
// }
// }
| import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.util.JSONUtils;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.storage.loot.LootParameters;
import net.minecraft.world.storage.loot.conditions.ILootCondition;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.lib.EntityGroup; | package net.silentchaos512.scalinghealth.loot.conditions;
public class EntityGroupCondition implements ILootCondition {
public static final Serializer SERIALIZER = new Serializer();
| // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/lib/EntityGroup.java
// public enum EntityGroup {
// PEACEFUL,
// HOSTILE,
// BOSS,
// BLIGHT,
// PLAYER;
//
// public static EntityGroup from(String name) {
// for(EntityGroup group : values()){
// if(group.name().equalsIgnoreCase(name)){
// return group;
// }
// }
// throw new RuntimeException("Could not get an entity group from name: " + name);
// }
//
// public static EntityGroup from(LivingEntity entity) {
// return from(entity, false);
// }
//
// public static EntityGroup from(LivingEntity entity, boolean ignoreBlightStatus) {
// if (entity instanceof PlayerEntity)
// return PLAYER;
// if (!entity.isNonBoss())
// return BOSS;
// if (entity instanceof IMob) {
// if (!ignoreBlightStatus && SHMobs.isBlight((MobEntity) entity))
// return BLIGHT;
// return HOSTILE;
// }
// return PEACEFUL;
// }
//
// public double getPotionChance() {
// if (this == PEACEFUL)
// return SHMobs.passivePotionChance();
// return SHMobs.hostilePotionChance();
// }
//
// public MobHealthMode getHealthMode() {
// return SHMobs.healthMode();
// }
//
// public boolean isAffectedByDamageScaling() {
// switch (this) {
// case PLAYER:
// return EnabledFeatures.playerDamageScalingEnabled();
// case PEACEFUL:
// return Config.GENERAL.damageScaling.affectPeacefuls.get();
// default:
// return Config.GENERAL.damageScaling.affectHostiles.get();
// }
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/loot/conditions/EntityGroupCondition.java
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.util.JSONUtils;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.storage.loot.LootParameters;
import net.minecraft.world.storage.loot.conditions.ILootCondition;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.lib.EntityGroup;
package net.silentchaos512.scalinghealth.loot.conditions;
public class EntityGroupCondition implements ILootCondition {
public static final Serializer SERIALIZER = new Serializer();
| private final EntityGroup group; |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/loot/conditions/EntityGroupCondition.java | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/lib/EntityGroup.java
// public enum EntityGroup {
// PEACEFUL,
// HOSTILE,
// BOSS,
// BLIGHT,
// PLAYER;
//
// public static EntityGroup from(String name) {
// for(EntityGroup group : values()){
// if(group.name().equalsIgnoreCase(name)){
// return group;
// }
// }
// throw new RuntimeException("Could not get an entity group from name: " + name);
// }
//
// public static EntityGroup from(LivingEntity entity) {
// return from(entity, false);
// }
//
// public static EntityGroup from(LivingEntity entity, boolean ignoreBlightStatus) {
// if (entity instanceof PlayerEntity)
// return PLAYER;
// if (!entity.isNonBoss())
// return BOSS;
// if (entity instanceof IMob) {
// if (!ignoreBlightStatus && SHMobs.isBlight((MobEntity) entity))
// return BLIGHT;
// return HOSTILE;
// }
// return PEACEFUL;
// }
//
// public double getPotionChance() {
// if (this == PEACEFUL)
// return SHMobs.passivePotionChance();
// return SHMobs.hostilePotionChance();
// }
//
// public MobHealthMode getHealthMode() {
// return SHMobs.healthMode();
// }
//
// public boolean isAffectedByDamageScaling() {
// switch (this) {
// case PLAYER:
// return EnabledFeatures.playerDamageScalingEnabled();
// case PEACEFUL:
// return Config.GENERAL.damageScaling.affectPeacefuls.get();
// default:
// return Config.GENERAL.damageScaling.affectHostiles.get();
// }
// }
// }
| import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.util.JSONUtils;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.storage.loot.LootParameters;
import net.minecraft.world.storage.loot.conditions.ILootCondition;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.lib.EntityGroup; | package net.silentchaos512.scalinghealth.loot.conditions;
public class EntityGroupCondition implements ILootCondition {
public static final Serializer SERIALIZER = new Serializer();
private final EntityGroup group;
public EntityGroupCondition(EntityGroup group){
this.group = group;
}
@Override
public boolean test(LootContext context) {
Entity entity = context.get(LootParameters.THIS_ENTITY);
if(entity instanceof LivingEntity){
return EntityGroup.from((LivingEntity) entity, true) == this.group;
}
return false;
}
public static class Serializer extends AbstractSerializer<EntityGroupCondition> {
protected Serializer() { | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/lib/EntityGroup.java
// public enum EntityGroup {
// PEACEFUL,
// HOSTILE,
// BOSS,
// BLIGHT,
// PLAYER;
//
// public static EntityGroup from(String name) {
// for(EntityGroup group : values()){
// if(group.name().equalsIgnoreCase(name)){
// return group;
// }
// }
// throw new RuntimeException("Could not get an entity group from name: " + name);
// }
//
// public static EntityGroup from(LivingEntity entity) {
// return from(entity, false);
// }
//
// public static EntityGroup from(LivingEntity entity, boolean ignoreBlightStatus) {
// if (entity instanceof PlayerEntity)
// return PLAYER;
// if (!entity.isNonBoss())
// return BOSS;
// if (entity instanceof IMob) {
// if (!ignoreBlightStatus && SHMobs.isBlight((MobEntity) entity))
// return BLIGHT;
// return HOSTILE;
// }
// return PEACEFUL;
// }
//
// public double getPotionChance() {
// if (this == PEACEFUL)
// return SHMobs.passivePotionChance();
// return SHMobs.hostilePotionChance();
// }
//
// public MobHealthMode getHealthMode() {
// return SHMobs.healthMode();
// }
//
// public boolean isAffectedByDamageScaling() {
// switch (this) {
// case PLAYER:
// return EnabledFeatures.playerDamageScalingEnabled();
// case PEACEFUL:
// return Config.GENERAL.damageScaling.affectPeacefuls.get();
// default:
// return Config.GENERAL.damageScaling.affectHostiles.get();
// }
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/loot/conditions/EntityGroupCondition.java
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.util.JSONUtils;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.storage.loot.LootParameters;
import net.minecraft.world.storage.loot.conditions.ILootCondition;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.lib.EntityGroup;
package net.silentchaos512.scalinghealth.loot.conditions;
public class EntityGroupCondition implements ILootCondition {
public static final Serializer SERIALIZER = new Serializer();
private final EntityGroup group;
public EntityGroupCondition(EntityGroup group){
this.group = group;
}
@Override
public boolean test(LootContext context) {
Entity entity = context.get(LootParameters.THIS_ENTITY);
if(entity instanceof LivingEntity){
return EntityGroup.from((LivingEntity) entity, true) == this.group;
}
return false;
}
public static class Serializer extends AbstractSerializer<EntityGroupCondition> {
protected Serializer() { | super(ScalingHealth.getId("entity_group_condition"), EntityGroupCondition.class); |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/item/HealingItem.java | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModPotions.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModPotions {
// BANDAGED(BandagedEffect::new);
//
// private final Lazy<Effect> potion;
//
// ModPotions(Supplier<Effect> factory) {
// this.potion = Lazy.of(factory);
// }
//
// public Effect get() {
// return potion.get();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Effect> event) {
// for (ModPotions potion : values()) {
// register(potion.getName(), potion.get());
// }
// }
//
// private static void register(String name, Effect potion) {
// ResourceLocation registryName = ScalingHealth.getId(name);
// potion.setRegistryName(registryName);
// ForgeRegistries.POTIONS.register(potion);
// }
// }
| import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.UseAction;
import net.minecraft.potion.EffectInstance;
import net.minecraft.stats.Stats;
import net.minecraft.util.ActionResult;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Hand;
import net.minecraft.util.SoundEvents;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.init.ModPotions;
import javax.annotation.Nullable;
import java.util.List; | /*
* Scaling Health
* Copyright (C) 2018 SilentChaos512
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 3
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.silentchaos512.scalinghealth.item;
public class HealingItem extends Item {
private static final int USE_TIME = 5 * 20;
private final float healAmount;
private final int healSpeed;
private final int effectDuration;
public HealingItem(float healAmount, int healSpeed) { | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModPotions.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModPotions {
// BANDAGED(BandagedEffect::new);
//
// private final Lazy<Effect> potion;
//
// ModPotions(Supplier<Effect> factory) {
// this.potion = Lazy.of(factory);
// }
//
// public Effect get() {
// return potion.get();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Effect> event) {
// for (ModPotions potion : values()) {
// register(potion.getName(), potion.get());
// }
// }
//
// private static void register(String name, Effect potion) {
// ResourceLocation registryName = ScalingHealth.getId(name);
// potion.setRegistryName(registryName);
// ForgeRegistries.POTIONS.register(potion);
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/item/HealingItem.java
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.UseAction;
import net.minecraft.potion.EffectInstance;
import net.minecraft.stats.Stats;
import net.minecraft.util.ActionResult;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Hand;
import net.minecraft.util.SoundEvents;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.init.ModPotions;
import javax.annotation.Nullable;
import java.util.List;
/*
* Scaling Health
* Copyright (C) 2018 SilentChaos512
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 3
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.silentchaos512.scalinghealth.item;
public class HealingItem extends Item {
private static final int USE_TIME = 5 * 20;
private final float healAmount;
private final int healSpeed;
private final int effectDuration;
public HealingItem(float healAmount, int healSpeed) { | super(new Item.Properties().maxStackSize(16).group(ScalingHealth.SH)); |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/datagen/LootTables.java | // Path: src/main/java/net/silentchaos512/scalinghealth/init/ModBlocks.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModBlocks implements IBlockProvider {
// HEART_CRYSTAL_ORE(ShardOreBlock::new),
// POWER_CRYSTAL_ORE(ShardOreBlock::new);
//
// private final Lazy<Block> block;
//
// ModBlocks(Supplier<Block> factory) {
// this.block = Lazy.of(factory);
// }
//
// @Override
// public Block asBlock() {
// return block.get();
// }
//
// @Override
// public Item asItem() {
// return asBlock().asItem();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Block> event) {
// for (ModBlocks block : values()) {
// register(block.getName(), block.asBlock());
// }
// }
//
// private static void register(String name, Block block) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// block.setRegistryName(registryName);
// ForgeRegistries.BLOCKS.register(block);
//
// BlockItem item = new BlockItem(block, new Item.Properties().group(ScalingHealth.SH));
// item.setRegistryName(registryName);
// ModItems.blocksToRegister.add(item);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModItems.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModItems implements IItemProvider {
// HEART_CRYSTAL(HeartCrystal::new),
// HEART_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// HEART_DUST(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// POWER_CRYSTAL(PowerCrystal::new),
// POWER_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// BANDAGES(() -> new HealingItem(0.3f, 1)),
// MEDKIT(() -> new HealingItem(0.7f, 4)),
// CURSED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CURSED)),
// ENCHANTED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.ENCHANTED)),
// CHANCE_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CHANCE));
//
// private final Lazy<Item> item;
//
// ModItems(Supplier<Item> factory) {
// item = Lazy.of(factory);
// }
//
// @Override
// public Item asItem() {
// return item.get();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// static final Collection<BlockItem> blocksToRegister = new ArrayList<>();
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Item> event) {
// blocksToRegister.forEach(ForgeRegistries.ITEMS::register);
//
// for (ModItems item : values()) {
// register(item.getName(), item.asItem());
// }
// }
//
// private static void register(String name, Item item) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// item.setRegistryName(registryName);
// ForgeRegistries.ITEMS.register(item);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/lib/EntityGroup.java
// public enum EntityGroup {
// PEACEFUL,
// HOSTILE,
// BOSS,
// BLIGHT,
// PLAYER;
//
// public static EntityGroup from(String name) {
// for(EntityGroup group : values()){
// if(group.name().equalsIgnoreCase(name)){
// return group;
// }
// }
// throw new RuntimeException("Could not get an entity group from name: " + name);
// }
//
// public static EntityGroup from(LivingEntity entity) {
// return from(entity, false);
// }
//
// public static EntityGroup from(LivingEntity entity, boolean ignoreBlightStatus) {
// if (entity instanceof PlayerEntity)
// return PLAYER;
// if (!entity.isNonBoss())
// return BOSS;
// if (entity instanceof IMob) {
// if (!ignoreBlightStatus && SHMobs.isBlight((MobEntity) entity))
// return BLIGHT;
// return HOSTILE;
// }
// return PEACEFUL;
// }
//
// public double getPotionChance() {
// if (this == PEACEFUL)
// return SHMobs.passivePotionChance();
// return SHMobs.hostilePotionChance();
// }
//
// public MobHealthMode getHealthMode() {
// return SHMobs.healthMode();
// }
//
// public boolean isAffectedByDamageScaling() {
// switch (this) {
// case PLAYER:
// return EnabledFeatures.playerDamageScalingEnabled();
// case PEACEFUL:
// return Config.GENERAL.damageScaling.affectPeacefuls.get();
// default:
// return Config.GENERAL.damageScaling.affectHostiles.get();
// }
// }
// }
| import net.minecraft.data.DataGenerator;
import net.silentchaos512.scalinghealth.init.ModBlocks;
import net.silentchaos512.scalinghealth.init.ModItems;
import net.silentchaos512.scalinghealth.lib.EntityGroup; | package net.silentchaos512.scalinghealth.datagen;
public class LootTables extends BaseLootTable {
public LootTables(DataGenerator generator) {
super(generator);
}
@Override
protected void addTables() { | // Path: src/main/java/net/silentchaos512/scalinghealth/init/ModBlocks.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModBlocks implements IBlockProvider {
// HEART_CRYSTAL_ORE(ShardOreBlock::new),
// POWER_CRYSTAL_ORE(ShardOreBlock::new);
//
// private final Lazy<Block> block;
//
// ModBlocks(Supplier<Block> factory) {
// this.block = Lazy.of(factory);
// }
//
// @Override
// public Block asBlock() {
// return block.get();
// }
//
// @Override
// public Item asItem() {
// return asBlock().asItem();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Block> event) {
// for (ModBlocks block : values()) {
// register(block.getName(), block.asBlock());
// }
// }
//
// private static void register(String name, Block block) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// block.setRegistryName(registryName);
// ForgeRegistries.BLOCKS.register(block);
//
// BlockItem item = new BlockItem(block, new Item.Properties().group(ScalingHealth.SH));
// item.setRegistryName(registryName);
// ModItems.blocksToRegister.add(item);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModItems.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModItems implements IItemProvider {
// HEART_CRYSTAL(HeartCrystal::new),
// HEART_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// HEART_DUST(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// POWER_CRYSTAL(PowerCrystal::new),
// POWER_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// BANDAGES(() -> new HealingItem(0.3f, 1)),
// MEDKIT(() -> new HealingItem(0.7f, 4)),
// CURSED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CURSED)),
// ENCHANTED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.ENCHANTED)),
// CHANCE_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CHANCE));
//
// private final Lazy<Item> item;
//
// ModItems(Supplier<Item> factory) {
// item = Lazy.of(factory);
// }
//
// @Override
// public Item asItem() {
// return item.get();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// static final Collection<BlockItem> blocksToRegister = new ArrayList<>();
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Item> event) {
// blocksToRegister.forEach(ForgeRegistries.ITEMS::register);
//
// for (ModItems item : values()) {
// register(item.getName(), item.asItem());
// }
// }
//
// private static void register(String name, Item item) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// item.setRegistryName(registryName);
// ForgeRegistries.ITEMS.register(item);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/lib/EntityGroup.java
// public enum EntityGroup {
// PEACEFUL,
// HOSTILE,
// BOSS,
// BLIGHT,
// PLAYER;
//
// public static EntityGroup from(String name) {
// for(EntityGroup group : values()){
// if(group.name().equalsIgnoreCase(name)){
// return group;
// }
// }
// throw new RuntimeException("Could not get an entity group from name: " + name);
// }
//
// public static EntityGroup from(LivingEntity entity) {
// return from(entity, false);
// }
//
// public static EntityGroup from(LivingEntity entity, boolean ignoreBlightStatus) {
// if (entity instanceof PlayerEntity)
// return PLAYER;
// if (!entity.isNonBoss())
// return BOSS;
// if (entity instanceof IMob) {
// if (!ignoreBlightStatus && SHMobs.isBlight((MobEntity) entity))
// return BLIGHT;
// return HOSTILE;
// }
// return PEACEFUL;
// }
//
// public double getPotionChance() {
// if (this == PEACEFUL)
// return SHMobs.passivePotionChance();
// return SHMobs.hostilePotionChance();
// }
//
// public MobHealthMode getHealthMode() {
// return SHMobs.healthMode();
// }
//
// public boolean isAffectedByDamageScaling() {
// switch (this) {
// case PLAYER:
// return EnabledFeatures.playerDamageScalingEnabled();
// case PEACEFUL:
// return Config.GENERAL.damageScaling.affectPeacefuls.get();
// default:
// return Config.GENERAL.damageScaling.affectHostiles.get();
// }
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/datagen/LootTables.java
import net.minecraft.data.DataGenerator;
import net.silentchaos512.scalinghealth.init.ModBlocks;
import net.silentchaos512.scalinghealth.init.ModItems;
import net.silentchaos512.scalinghealth.lib.EntityGroup;
package net.silentchaos512.scalinghealth.datagen;
public class LootTables extends BaseLootTable {
public LootTables(DataGenerator generator) {
super(generator);
}
@Override
protected void addTables() { | lootTables.put(ModBlocks.HEART_CRYSTAL_ORE.asBlock(), createSilkTouchTable("heart_crystal_ore", ModBlocks.HEART_CRYSTAL_ORE.asBlock(), ModItems.HEART_CRYSTAL_SHARD.asItem())); |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/datagen/LootTables.java | // Path: src/main/java/net/silentchaos512/scalinghealth/init/ModBlocks.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModBlocks implements IBlockProvider {
// HEART_CRYSTAL_ORE(ShardOreBlock::new),
// POWER_CRYSTAL_ORE(ShardOreBlock::new);
//
// private final Lazy<Block> block;
//
// ModBlocks(Supplier<Block> factory) {
// this.block = Lazy.of(factory);
// }
//
// @Override
// public Block asBlock() {
// return block.get();
// }
//
// @Override
// public Item asItem() {
// return asBlock().asItem();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Block> event) {
// for (ModBlocks block : values()) {
// register(block.getName(), block.asBlock());
// }
// }
//
// private static void register(String name, Block block) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// block.setRegistryName(registryName);
// ForgeRegistries.BLOCKS.register(block);
//
// BlockItem item = new BlockItem(block, new Item.Properties().group(ScalingHealth.SH));
// item.setRegistryName(registryName);
// ModItems.blocksToRegister.add(item);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModItems.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModItems implements IItemProvider {
// HEART_CRYSTAL(HeartCrystal::new),
// HEART_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// HEART_DUST(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// POWER_CRYSTAL(PowerCrystal::new),
// POWER_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// BANDAGES(() -> new HealingItem(0.3f, 1)),
// MEDKIT(() -> new HealingItem(0.7f, 4)),
// CURSED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CURSED)),
// ENCHANTED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.ENCHANTED)),
// CHANCE_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CHANCE));
//
// private final Lazy<Item> item;
//
// ModItems(Supplier<Item> factory) {
// item = Lazy.of(factory);
// }
//
// @Override
// public Item asItem() {
// return item.get();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// static final Collection<BlockItem> blocksToRegister = new ArrayList<>();
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Item> event) {
// blocksToRegister.forEach(ForgeRegistries.ITEMS::register);
//
// for (ModItems item : values()) {
// register(item.getName(), item.asItem());
// }
// }
//
// private static void register(String name, Item item) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// item.setRegistryName(registryName);
// ForgeRegistries.ITEMS.register(item);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/lib/EntityGroup.java
// public enum EntityGroup {
// PEACEFUL,
// HOSTILE,
// BOSS,
// BLIGHT,
// PLAYER;
//
// public static EntityGroup from(String name) {
// for(EntityGroup group : values()){
// if(group.name().equalsIgnoreCase(name)){
// return group;
// }
// }
// throw new RuntimeException("Could not get an entity group from name: " + name);
// }
//
// public static EntityGroup from(LivingEntity entity) {
// return from(entity, false);
// }
//
// public static EntityGroup from(LivingEntity entity, boolean ignoreBlightStatus) {
// if (entity instanceof PlayerEntity)
// return PLAYER;
// if (!entity.isNonBoss())
// return BOSS;
// if (entity instanceof IMob) {
// if (!ignoreBlightStatus && SHMobs.isBlight((MobEntity) entity))
// return BLIGHT;
// return HOSTILE;
// }
// return PEACEFUL;
// }
//
// public double getPotionChance() {
// if (this == PEACEFUL)
// return SHMobs.passivePotionChance();
// return SHMobs.hostilePotionChance();
// }
//
// public MobHealthMode getHealthMode() {
// return SHMobs.healthMode();
// }
//
// public boolean isAffectedByDamageScaling() {
// switch (this) {
// case PLAYER:
// return EnabledFeatures.playerDamageScalingEnabled();
// case PEACEFUL:
// return Config.GENERAL.damageScaling.affectPeacefuls.get();
// default:
// return Config.GENERAL.damageScaling.affectHostiles.get();
// }
// }
// }
| import net.minecraft.data.DataGenerator;
import net.silentchaos512.scalinghealth.init.ModBlocks;
import net.silentchaos512.scalinghealth.init.ModItems;
import net.silentchaos512.scalinghealth.lib.EntityGroup; | package net.silentchaos512.scalinghealth.datagen;
public class LootTables extends BaseLootTable {
public LootTables(DataGenerator generator) {
super(generator);
}
@Override
protected void addTables() { | // Path: src/main/java/net/silentchaos512/scalinghealth/init/ModBlocks.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModBlocks implements IBlockProvider {
// HEART_CRYSTAL_ORE(ShardOreBlock::new),
// POWER_CRYSTAL_ORE(ShardOreBlock::new);
//
// private final Lazy<Block> block;
//
// ModBlocks(Supplier<Block> factory) {
// this.block = Lazy.of(factory);
// }
//
// @Override
// public Block asBlock() {
// return block.get();
// }
//
// @Override
// public Item asItem() {
// return asBlock().asItem();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Block> event) {
// for (ModBlocks block : values()) {
// register(block.getName(), block.asBlock());
// }
// }
//
// private static void register(String name, Block block) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// block.setRegistryName(registryName);
// ForgeRegistries.BLOCKS.register(block);
//
// BlockItem item = new BlockItem(block, new Item.Properties().group(ScalingHealth.SH));
// item.setRegistryName(registryName);
// ModItems.blocksToRegister.add(item);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModItems.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModItems implements IItemProvider {
// HEART_CRYSTAL(HeartCrystal::new),
// HEART_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// HEART_DUST(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// POWER_CRYSTAL(PowerCrystal::new),
// POWER_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// BANDAGES(() -> new HealingItem(0.3f, 1)),
// MEDKIT(() -> new HealingItem(0.7f, 4)),
// CURSED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CURSED)),
// ENCHANTED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.ENCHANTED)),
// CHANCE_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CHANCE));
//
// private final Lazy<Item> item;
//
// ModItems(Supplier<Item> factory) {
// item = Lazy.of(factory);
// }
//
// @Override
// public Item asItem() {
// return item.get();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// static final Collection<BlockItem> blocksToRegister = new ArrayList<>();
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Item> event) {
// blocksToRegister.forEach(ForgeRegistries.ITEMS::register);
//
// for (ModItems item : values()) {
// register(item.getName(), item.asItem());
// }
// }
//
// private static void register(String name, Item item) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// item.setRegistryName(registryName);
// ForgeRegistries.ITEMS.register(item);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/lib/EntityGroup.java
// public enum EntityGroup {
// PEACEFUL,
// HOSTILE,
// BOSS,
// BLIGHT,
// PLAYER;
//
// public static EntityGroup from(String name) {
// for(EntityGroup group : values()){
// if(group.name().equalsIgnoreCase(name)){
// return group;
// }
// }
// throw new RuntimeException("Could not get an entity group from name: " + name);
// }
//
// public static EntityGroup from(LivingEntity entity) {
// return from(entity, false);
// }
//
// public static EntityGroup from(LivingEntity entity, boolean ignoreBlightStatus) {
// if (entity instanceof PlayerEntity)
// return PLAYER;
// if (!entity.isNonBoss())
// return BOSS;
// if (entity instanceof IMob) {
// if (!ignoreBlightStatus && SHMobs.isBlight((MobEntity) entity))
// return BLIGHT;
// return HOSTILE;
// }
// return PEACEFUL;
// }
//
// public double getPotionChance() {
// if (this == PEACEFUL)
// return SHMobs.passivePotionChance();
// return SHMobs.hostilePotionChance();
// }
//
// public MobHealthMode getHealthMode() {
// return SHMobs.healthMode();
// }
//
// public boolean isAffectedByDamageScaling() {
// switch (this) {
// case PLAYER:
// return EnabledFeatures.playerDamageScalingEnabled();
// case PEACEFUL:
// return Config.GENERAL.damageScaling.affectPeacefuls.get();
// default:
// return Config.GENERAL.damageScaling.affectHostiles.get();
// }
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/datagen/LootTables.java
import net.minecraft.data.DataGenerator;
import net.silentchaos512.scalinghealth.init.ModBlocks;
import net.silentchaos512.scalinghealth.init.ModItems;
import net.silentchaos512.scalinghealth.lib.EntityGroup;
package net.silentchaos512.scalinghealth.datagen;
public class LootTables extends BaseLootTable {
public LootTables(DataGenerator generator) {
super(generator);
}
@Override
protected void addTables() { | lootTables.put(ModBlocks.HEART_CRYSTAL_ORE.asBlock(), createSilkTouchTable("heart_crystal_ore", ModBlocks.HEART_CRYSTAL_ORE.asBlock(), ModItems.HEART_CRYSTAL_SHARD.asItem())); |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/datagen/LootTables.java | // Path: src/main/java/net/silentchaos512/scalinghealth/init/ModBlocks.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModBlocks implements IBlockProvider {
// HEART_CRYSTAL_ORE(ShardOreBlock::new),
// POWER_CRYSTAL_ORE(ShardOreBlock::new);
//
// private final Lazy<Block> block;
//
// ModBlocks(Supplier<Block> factory) {
// this.block = Lazy.of(factory);
// }
//
// @Override
// public Block asBlock() {
// return block.get();
// }
//
// @Override
// public Item asItem() {
// return asBlock().asItem();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Block> event) {
// for (ModBlocks block : values()) {
// register(block.getName(), block.asBlock());
// }
// }
//
// private static void register(String name, Block block) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// block.setRegistryName(registryName);
// ForgeRegistries.BLOCKS.register(block);
//
// BlockItem item = new BlockItem(block, new Item.Properties().group(ScalingHealth.SH));
// item.setRegistryName(registryName);
// ModItems.blocksToRegister.add(item);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModItems.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModItems implements IItemProvider {
// HEART_CRYSTAL(HeartCrystal::new),
// HEART_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// HEART_DUST(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// POWER_CRYSTAL(PowerCrystal::new),
// POWER_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// BANDAGES(() -> new HealingItem(0.3f, 1)),
// MEDKIT(() -> new HealingItem(0.7f, 4)),
// CURSED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CURSED)),
// ENCHANTED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.ENCHANTED)),
// CHANCE_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CHANCE));
//
// private final Lazy<Item> item;
//
// ModItems(Supplier<Item> factory) {
// item = Lazy.of(factory);
// }
//
// @Override
// public Item asItem() {
// return item.get();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// static final Collection<BlockItem> blocksToRegister = new ArrayList<>();
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Item> event) {
// blocksToRegister.forEach(ForgeRegistries.ITEMS::register);
//
// for (ModItems item : values()) {
// register(item.getName(), item.asItem());
// }
// }
//
// private static void register(String name, Item item) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// item.setRegistryName(registryName);
// ForgeRegistries.ITEMS.register(item);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/lib/EntityGroup.java
// public enum EntityGroup {
// PEACEFUL,
// HOSTILE,
// BOSS,
// BLIGHT,
// PLAYER;
//
// public static EntityGroup from(String name) {
// for(EntityGroup group : values()){
// if(group.name().equalsIgnoreCase(name)){
// return group;
// }
// }
// throw new RuntimeException("Could not get an entity group from name: " + name);
// }
//
// public static EntityGroup from(LivingEntity entity) {
// return from(entity, false);
// }
//
// public static EntityGroup from(LivingEntity entity, boolean ignoreBlightStatus) {
// if (entity instanceof PlayerEntity)
// return PLAYER;
// if (!entity.isNonBoss())
// return BOSS;
// if (entity instanceof IMob) {
// if (!ignoreBlightStatus && SHMobs.isBlight((MobEntity) entity))
// return BLIGHT;
// return HOSTILE;
// }
// return PEACEFUL;
// }
//
// public double getPotionChance() {
// if (this == PEACEFUL)
// return SHMobs.passivePotionChance();
// return SHMobs.hostilePotionChance();
// }
//
// public MobHealthMode getHealthMode() {
// return SHMobs.healthMode();
// }
//
// public boolean isAffectedByDamageScaling() {
// switch (this) {
// case PLAYER:
// return EnabledFeatures.playerDamageScalingEnabled();
// case PEACEFUL:
// return Config.GENERAL.damageScaling.affectPeacefuls.get();
// default:
// return Config.GENERAL.damageScaling.affectHostiles.get();
// }
// }
// }
| import net.minecraft.data.DataGenerator;
import net.silentchaos512.scalinghealth.init.ModBlocks;
import net.silentchaos512.scalinghealth.init.ModItems;
import net.silentchaos512.scalinghealth.lib.EntityGroup; | package net.silentchaos512.scalinghealth.datagen;
public class LootTables extends BaseLootTable {
public LootTables(DataGenerator generator) {
super(generator);
}
@Override
protected void addTables() {
lootTables.put(ModBlocks.HEART_CRYSTAL_ORE.asBlock(), createSilkTouchTable("heart_crystal_ore", ModBlocks.HEART_CRYSTAL_ORE.asBlock(), ModItems.HEART_CRYSTAL_SHARD.asItem()));
lootTables.put(ModBlocks.POWER_CRYSTAL_ORE.asBlock(), createSilkTouchTable("power_crystal_ore", ModBlocks.POWER_CRYSTAL_ORE.asBlock(), ModItems.POWER_CRYSTAL_SHARD.asItem())); | // Path: src/main/java/net/silentchaos512/scalinghealth/init/ModBlocks.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModBlocks implements IBlockProvider {
// HEART_CRYSTAL_ORE(ShardOreBlock::new),
// POWER_CRYSTAL_ORE(ShardOreBlock::new);
//
// private final Lazy<Block> block;
//
// ModBlocks(Supplier<Block> factory) {
// this.block = Lazy.of(factory);
// }
//
// @Override
// public Block asBlock() {
// return block.get();
// }
//
// @Override
// public Item asItem() {
// return asBlock().asItem();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Block> event) {
// for (ModBlocks block : values()) {
// register(block.getName(), block.asBlock());
// }
// }
//
// private static void register(String name, Block block) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// block.setRegistryName(registryName);
// ForgeRegistries.BLOCKS.register(block);
//
// BlockItem item = new BlockItem(block, new Item.Properties().group(ScalingHealth.SH));
// item.setRegistryName(registryName);
// ModItems.blocksToRegister.add(item);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModItems.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModItems implements IItemProvider {
// HEART_CRYSTAL(HeartCrystal::new),
// HEART_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// HEART_DUST(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// POWER_CRYSTAL(PowerCrystal::new),
// POWER_CRYSTAL_SHARD(() -> new Item(new Item.Properties().group(ScalingHealth.SH))),
// BANDAGES(() -> new HealingItem(0.3f, 1)),
// MEDKIT(() -> new HealingItem(0.7f, 4)),
// CURSED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CURSED)),
// ENCHANTED_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.ENCHANTED)),
// CHANCE_HEART(() -> new DifficultyMutatorItem(DifficultyMutatorItem.Type.CHANCE));
//
// private final Lazy<Item> item;
//
// ModItems(Supplier<Item> factory) {
// item = Lazy.of(factory);
// }
//
// @Override
// public Item asItem() {
// return item.get();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// static final Collection<BlockItem> blocksToRegister = new ArrayList<>();
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Item> event) {
// blocksToRegister.forEach(ForgeRegistries.ITEMS::register);
//
// for (ModItems item : values()) {
// register(item.getName(), item.asItem());
// }
// }
//
// private static void register(String name, Item item) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// item.setRegistryName(registryName);
// ForgeRegistries.ITEMS.register(item);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/lib/EntityGroup.java
// public enum EntityGroup {
// PEACEFUL,
// HOSTILE,
// BOSS,
// BLIGHT,
// PLAYER;
//
// public static EntityGroup from(String name) {
// for(EntityGroup group : values()){
// if(group.name().equalsIgnoreCase(name)){
// return group;
// }
// }
// throw new RuntimeException("Could not get an entity group from name: " + name);
// }
//
// public static EntityGroup from(LivingEntity entity) {
// return from(entity, false);
// }
//
// public static EntityGroup from(LivingEntity entity, boolean ignoreBlightStatus) {
// if (entity instanceof PlayerEntity)
// return PLAYER;
// if (!entity.isNonBoss())
// return BOSS;
// if (entity instanceof IMob) {
// if (!ignoreBlightStatus && SHMobs.isBlight((MobEntity) entity))
// return BLIGHT;
// return HOSTILE;
// }
// return PEACEFUL;
// }
//
// public double getPotionChance() {
// if (this == PEACEFUL)
// return SHMobs.passivePotionChance();
// return SHMobs.hostilePotionChance();
// }
//
// public MobHealthMode getHealthMode() {
// return SHMobs.healthMode();
// }
//
// public boolean isAffectedByDamageScaling() {
// switch (this) {
// case PLAYER:
// return EnabledFeatures.playerDamageScalingEnabled();
// case PEACEFUL:
// return Config.GENERAL.damageScaling.affectPeacefuls.get();
// default:
// return Config.GENERAL.damageScaling.affectHostiles.get();
// }
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/datagen/LootTables.java
import net.minecraft.data.DataGenerator;
import net.silentchaos512.scalinghealth.init.ModBlocks;
import net.silentchaos512.scalinghealth.init.ModItems;
import net.silentchaos512.scalinghealth.lib.EntityGroup;
package net.silentchaos512.scalinghealth.datagen;
public class LootTables extends BaseLootTable {
public LootTables(DataGenerator generator) {
super(generator);
}
@Override
protected void addTables() {
lootTables.put(ModBlocks.HEART_CRYSTAL_ORE.asBlock(), createSilkTouchTable("heart_crystal_ore", ModBlocks.HEART_CRYSTAL_ORE.asBlock(), ModItems.HEART_CRYSTAL_SHARD.asItem()));
lootTables.put(ModBlocks.POWER_CRYSTAL_ORE.asBlock(), createSilkTouchTable("power_crystal_ore", ModBlocks.POWER_CRYSTAL_ORE.asBlock(), ModItems.POWER_CRYSTAL_SHARD.asItem())); | mobLootTable.put(EntityGroup.HOSTILE, |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/init/ModBlocks.java | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/block/ShardOreBlock.java
// public class ShardOreBlock extends OreBlock {
// public ShardOreBlock() {
// super(Block.Properties.create(Material.ROCK).hardnessAndResistance(3, 15));
// }
//
// @Override
// public int getExpDrop(BlockState state, IWorldReader reader, BlockPos pos, int fortune, int silkTouch) {
// return silkTouch == 0 ? MathHelper.nextInt(RANDOM, 1, 5) : 0;
// }
// }
| import java.util.Locale;
import java.util.function.Supplier;
import net.minecraft.block.Block;
import net.minecraft.item.BlockItem;
import net.minecraft.item.Item;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.registries.ForgeRegistries;
import net.silentchaos512.lib.block.IBlockProvider;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.block.ShardOreBlock;
import net.silentchaos512.utils.Lazy; | /*
* Scaling Health
* Copyright (C) 2018 SilentChaos512
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 3
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.silentchaos512.scalinghealth.init;
@Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
public enum ModBlocks implements IBlockProvider { | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/block/ShardOreBlock.java
// public class ShardOreBlock extends OreBlock {
// public ShardOreBlock() {
// super(Block.Properties.create(Material.ROCK).hardnessAndResistance(3, 15));
// }
//
// @Override
// public int getExpDrop(BlockState state, IWorldReader reader, BlockPos pos, int fortune, int silkTouch) {
// return silkTouch == 0 ? MathHelper.nextInt(RANDOM, 1, 5) : 0;
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModBlocks.java
import java.util.Locale;
import java.util.function.Supplier;
import net.minecraft.block.Block;
import net.minecraft.item.BlockItem;
import net.minecraft.item.Item;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.registries.ForgeRegistries;
import net.silentchaos512.lib.block.IBlockProvider;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.block.ShardOreBlock;
import net.silentchaos512.utils.Lazy;
/*
* Scaling Health
* Copyright (C) 2018 SilentChaos512
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 3
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.silentchaos512.scalinghealth.init;
@Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
public enum ModBlocks implements IBlockProvider { | HEART_CRYSTAL_ORE(ShardOreBlock::new), |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/world/SHWorldFeatures.java | // Path: src/main/java/net/silentchaos512/scalinghealth/init/ModBlocks.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModBlocks implements IBlockProvider {
// HEART_CRYSTAL_ORE(ShardOreBlock::new),
// POWER_CRYSTAL_ORE(ShardOreBlock::new);
//
// private final Lazy<Block> block;
//
// ModBlocks(Supplier<Block> factory) {
// this.block = Lazy.of(factory);
// }
//
// @Override
// public Block asBlock() {
// return block.get();
// }
//
// @Override
// public Item asItem() {
// return asBlock().asItem();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Block> event) {
// for (ModBlocks block : values()) {
// register(block.getName(), block.asBlock());
// }
// }
//
// private static void register(String name, Block block) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// block.setRegistryName(registryName);
// ForgeRegistries.BLOCKS.register(block);
//
// BlockItem item = new BlockItem(block, new Item.Properties().group(ScalingHealth.SH));
// item.setRegistryName(registryName);
// ModItems.blocksToRegister.add(item);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/utils/EnabledFeatures.java
// public class EnabledFeatures {
// private static Config.Common common = Config.COMMON;
//
// public static boolean healthCrystalEnabled(){
// return common.crystalsAddHealth.get() && SHItems.heartCrystalIncreaseAmount() > 0;
// }
//
// public static boolean healthCrystalRegenEnabled() {
// return common.crystalsRegenHealth.get() && SHItems.heartCrystalHpBonusRegen() > 0;
// }
//
// public static boolean healthXpEnabled(){
// return common.xpAddHealth.get();
// }
//
// public static boolean petBonusHpEnabled(){
// return common.crystalsAddPetHealth.get();
// }
//
// public static boolean powerCrystalEnabled(){
// return common.crystalsAddDamage.get() && SHItems.powerCrystalIncreaseAmount() > 0;
// }
//
// public static boolean hpCrystalsOreGenEnabled(){
// return common.hpCrystalsOreGen.get();
// }
//
// public static boolean powerCrystalsOreGenEnabled(){
// return common.powerCrystalsOreGen.get() && powerCrystalEnabled();
// }
//
// public static boolean mobHpIncreaseEnabled(){
// return common.mobHpIncrease.get() &&
// (SHMobs.healthHostileMultiplier() > 0 || SHMobs.healthPassiveMultiplier() > 0);
// }
//
// public static boolean mobDamageIncreaseEnabled(){
// return common.mobDamageIncrease.get() && SHMobs.maxDamageBoost() > 0;
// }
//
// public static boolean playerDamageScalingEnabled(){
// GameConfig.DamageScaling cfg = Config.GENERAL.damageScaling;
// return common.playerDamageScaling.get() &&
// (cfg.difficultyWeight.get() > 0 || cfg.mode.get() == DamageScaling.Mode.MAX_HEALTH); //If in max hp, dont care about diffWeight. If diffWeight is non zero. Dont care about mode.
// }
//
// public static boolean mobDamageScalingEnabled(){
// GameConfig.DamageScaling cfg = Config.GENERAL.damageScaling;
// return common.mobDamageScaling.get() &&
// (cfg.affectHostiles.get() || cfg.affectPeacefuls.get()) && //if both are false, no damage scaling occurs
// (cfg.difficultyWeight.get() > 0 || cfg.mode.get() == DamageScaling.Mode.MAX_HEALTH); //If in max hp, dont care about diffWeight. If diffWeight is non zero. Dont care about mode.
// }
//
// public static boolean difficultyEnabled(){
// return common.enableDifficulty.get() && SHDifficulty.maxValue() > 0;
// }
//
// public static boolean blightsEnabled(){
// return common.enableBlights.get() && SHMobs.blightChance() > 0;
// }
// }
| import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.GenerationStage;
import net.minecraft.world.gen.feature.Feature;
import net.minecraft.world.gen.feature.OreFeatureConfig;
import net.minecraft.world.gen.placement.CountRangeConfig;
import net.minecraft.world.gen.placement.Placement;
import net.minecraftforge.registries.ForgeRegistries;
import net.silentchaos512.lib.block.IBlockProvider;
import net.silentchaos512.scalinghealth.init.ModBlocks;
import net.silentchaos512.scalinghealth.utils.EnabledFeatures; | package net.silentchaos512.scalinghealth.world;
public class SHWorldFeatures {
public static void addFeaturesToBiomes() {
for (Biome biome : ForgeRegistries.BIOMES) { | // Path: src/main/java/net/silentchaos512/scalinghealth/init/ModBlocks.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModBlocks implements IBlockProvider {
// HEART_CRYSTAL_ORE(ShardOreBlock::new),
// POWER_CRYSTAL_ORE(ShardOreBlock::new);
//
// private final Lazy<Block> block;
//
// ModBlocks(Supplier<Block> factory) {
// this.block = Lazy.of(factory);
// }
//
// @Override
// public Block asBlock() {
// return block.get();
// }
//
// @Override
// public Item asItem() {
// return asBlock().asItem();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Block> event) {
// for (ModBlocks block : values()) {
// register(block.getName(), block.asBlock());
// }
// }
//
// private static void register(String name, Block block) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// block.setRegistryName(registryName);
// ForgeRegistries.BLOCKS.register(block);
//
// BlockItem item = new BlockItem(block, new Item.Properties().group(ScalingHealth.SH));
// item.setRegistryName(registryName);
// ModItems.blocksToRegister.add(item);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/utils/EnabledFeatures.java
// public class EnabledFeatures {
// private static Config.Common common = Config.COMMON;
//
// public static boolean healthCrystalEnabled(){
// return common.crystalsAddHealth.get() && SHItems.heartCrystalIncreaseAmount() > 0;
// }
//
// public static boolean healthCrystalRegenEnabled() {
// return common.crystalsRegenHealth.get() && SHItems.heartCrystalHpBonusRegen() > 0;
// }
//
// public static boolean healthXpEnabled(){
// return common.xpAddHealth.get();
// }
//
// public static boolean petBonusHpEnabled(){
// return common.crystalsAddPetHealth.get();
// }
//
// public static boolean powerCrystalEnabled(){
// return common.crystalsAddDamage.get() && SHItems.powerCrystalIncreaseAmount() > 0;
// }
//
// public static boolean hpCrystalsOreGenEnabled(){
// return common.hpCrystalsOreGen.get();
// }
//
// public static boolean powerCrystalsOreGenEnabled(){
// return common.powerCrystalsOreGen.get() && powerCrystalEnabled();
// }
//
// public static boolean mobHpIncreaseEnabled(){
// return common.mobHpIncrease.get() &&
// (SHMobs.healthHostileMultiplier() > 0 || SHMobs.healthPassiveMultiplier() > 0);
// }
//
// public static boolean mobDamageIncreaseEnabled(){
// return common.mobDamageIncrease.get() && SHMobs.maxDamageBoost() > 0;
// }
//
// public static boolean playerDamageScalingEnabled(){
// GameConfig.DamageScaling cfg = Config.GENERAL.damageScaling;
// return common.playerDamageScaling.get() &&
// (cfg.difficultyWeight.get() > 0 || cfg.mode.get() == DamageScaling.Mode.MAX_HEALTH); //If in max hp, dont care about diffWeight. If diffWeight is non zero. Dont care about mode.
// }
//
// public static boolean mobDamageScalingEnabled(){
// GameConfig.DamageScaling cfg = Config.GENERAL.damageScaling;
// return common.mobDamageScaling.get() &&
// (cfg.affectHostiles.get() || cfg.affectPeacefuls.get()) && //if both are false, no damage scaling occurs
// (cfg.difficultyWeight.get() > 0 || cfg.mode.get() == DamageScaling.Mode.MAX_HEALTH); //If in max hp, dont care about diffWeight. If diffWeight is non zero. Dont care about mode.
// }
//
// public static boolean difficultyEnabled(){
// return common.enableDifficulty.get() && SHDifficulty.maxValue() > 0;
// }
//
// public static boolean blightsEnabled(){
// return common.enableBlights.get() && SHMobs.blightChance() > 0;
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/world/SHWorldFeatures.java
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.GenerationStage;
import net.minecraft.world.gen.feature.Feature;
import net.minecraft.world.gen.feature.OreFeatureConfig;
import net.minecraft.world.gen.placement.CountRangeConfig;
import net.minecraft.world.gen.placement.Placement;
import net.minecraftforge.registries.ForgeRegistries;
import net.silentchaos512.lib.block.IBlockProvider;
import net.silentchaos512.scalinghealth.init.ModBlocks;
import net.silentchaos512.scalinghealth.utils.EnabledFeatures;
package net.silentchaos512.scalinghealth.world;
public class SHWorldFeatures {
public static void addFeaturesToBiomes() {
for (Biome biome : ForgeRegistries.BIOMES) { | if(EnabledFeatures.hpCrystalsOreGenEnabled()) |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/world/SHWorldFeatures.java | // Path: src/main/java/net/silentchaos512/scalinghealth/init/ModBlocks.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModBlocks implements IBlockProvider {
// HEART_CRYSTAL_ORE(ShardOreBlock::new),
// POWER_CRYSTAL_ORE(ShardOreBlock::new);
//
// private final Lazy<Block> block;
//
// ModBlocks(Supplier<Block> factory) {
// this.block = Lazy.of(factory);
// }
//
// @Override
// public Block asBlock() {
// return block.get();
// }
//
// @Override
// public Item asItem() {
// return asBlock().asItem();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Block> event) {
// for (ModBlocks block : values()) {
// register(block.getName(), block.asBlock());
// }
// }
//
// private static void register(String name, Block block) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// block.setRegistryName(registryName);
// ForgeRegistries.BLOCKS.register(block);
//
// BlockItem item = new BlockItem(block, new Item.Properties().group(ScalingHealth.SH));
// item.setRegistryName(registryName);
// ModItems.blocksToRegister.add(item);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/utils/EnabledFeatures.java
// public class EnabledFeatures {
// private static Config.Common common = Config.COMMON;
//
// public static boolean healthCrystalEnabled(){
// return common.crystalsAddHealth.get() && SHItems.heartCrystalIncreaseAmount() > 0;
// }
//
// public static boolean healthCrystalRegenEnabled() {
// return common.crystalsRegenHealth.get() && SHItems.heartCrystalHpBonusRegen() > 0;
// }
//
// public static boolean healthXpEnabled(){
// return common.xpAddHealth.get();
// }
//
// public static boolean petBonusHpEnabled(){
// return common.crystalsAddPetHealth.get();
// }
//
// public static boolean powerCrystalEnabled(){
// return common.crystalsAddDamage.get() && SHItems.powerCrystalIncreaseAmount() > 0;
// }
//
// public static boolean hpCrystalsOreGenEnabled(){
// return common.hpCrystalsOreGen.get();
// }
//
// public static boolean powerCrystalsOreGenEnabled(){
// return common.powerCrystalsOreGen.get() && powerCrystalEnabled();
// }
//
// public static boolean mobHpIncreaseEnabled(){
// return common.mobHpIncrease.get() &&
// (SHMobs.healthHostileMultiplier() > 0 || SHMobs.healthPassiveMultiplier() > 0);
// }
//
// public static boolean mobDamageIncreaseEnabled(){
// return common.mobDamageIncrease.get() && SHMobs.maxDamageBoost() > 0;
// }
//
// public static boolean playerDamageScalingEnabled(){
// GameConfig.DamageScaling cfg = Config.GENERAL.damageScaling;
// return common.playerDamageScaling.get() &&
// (cfg.difficultyWeight.get() > 0 || cfg.mode.get() == DamageScaling.Mode.MAX_HEALTH); //If in max hp, dont care about diffWeight. If diffWeight is non zero. Dont care about mode.
// }
//
// public static boolean mobDamageScalingEnabled(){
// GameConfig.DamageScaling cfg = Config.GENERAL.damageScaling;
// return common.mobDamageScaling.get() &&
// (cfg.affectHostiles.get() || cfg.affectPeacefuls.get()) && //if both are false, no damage scaling occurs
// (cfg.difficultyWeight.get() > 0 || cfg.mode.get() == DamageScaling.Mode.MAX_HEALTH); //If in max hp, dont care about diffWeight. If diffWeight is non zero. Dont care about mode.
// }
//
// public static boolean difficultyEnabled(){
// return common.enableDifficulty.get() && SHDifficulty.maxValue() > 0;
// }
//
// public static boolean blightsEnabled(){
// return common.enableBlights.get() && SHMobs.blightChance() > 0;
// }
// }
| import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.GenerationStage;
import net.minecraft.world.gen.feature.Feature;
import net.minecraft.world.gen.feature.OreFeatureConfig;
import net.minecraft.world.gen.placement.CountRangeConfig;
import net.minecraft.world.gen.placement.Placement;
import net.minecraftforge.registries.ForgeRegistries;
import net.silentchaos512.lib.block.IBlockProvider;
import net.silentchaos512.scalinghealth.init.ModBlocks;
import net.silentchaos512.scalinghealth.utils.EnabledFeatures; | package net.silentchaos512.scalinghealth.world;
public class SHWorldFeatures {
public static void addFeaturesToBiomes() {
for (Biome biome : ForgeRegistries.BIOMES) {
if(EnabledFeatures.hpCrystalsOreGenEnabled()) | // Path: src/main/java/net/silentchaos512/scalinghealth/init/ModBlocks.java
// @Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
// public enum ModBlocks implements IBlockProvider {
// HEART_CRYSTAL_ORE(ShardOreBlock::new),
// POWER_CRYSTAL_ORE(ShardOreBlock::new);
//
// private final Lazy<Block> block;
//
// ModBlocks(Supplier<Block> factory) {
// this.block = Lazy.of(factory);
// }
//
// @Override
// public Block asBlock() {
// return block.get();
// }
//
// @Override
// public Item asItem() {
// return asBlock().asItem();
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// @SubscribeEvent
// public static void registerAll(RegistryEvent.Register<Block> event) {
// for (ModBlocks block : values()) {
// register(block.getName(), block.asBlock());
// }
// }
//
// private static void register(String name, Block block) {
// ResourceLocation registryName = new ResourceLocation(ScalingHealth.MOD_ID, name);
// block.setRegistryName(registryName);
// ForgeRegistries.BLOCKS.register(block);
//
// BlockItem item = new BlockItem(block, new Item.Properties().group(ScalingHealth.SH));
// item.setRegistryName(registryName);
// ModItems.blocksToRegister.add(item);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/utils/EnabledFeatures.java
// public class EnabledFeatures {
// private static Config.Common common = Config.COMMON;
//
// public static boolean healthCrystalEnabled(){
// return common.crystalsAddHealth.get() && SHItems.heartCrystalIncreaseAmount() > 0;
// }
//
// public static boolean healthCrystalRegenEnabled() {
// return common.crystalsRegenHealth.get() && SHItems.heartCrystalHpBonusRegen() > 0;
// }
//
// public static boolean healthXpEnabled(){
// return common.xpAddHealth.get();
// }
//
// public static boolean petBonusHpEnabled(){
// return common.crystalsAddPetHealth.get();
// }
//
// public static boolean powerCrystalEnabled(){
// return common.crystalsAddDamage.get() && SHItems.powerCrystalIncreaseAmount() > 0;
// }
//
// public static boolean hpCrystalsOreGenEnabled(){
// return common.hpCrystalsOreGen.get();
// }
//
// public static boolean powerCrystalsOreGenEnabled(){
// return common.powerCrystalsOreGen.get() && powerCrystalEnabled();
// }
//
// public static boolean mobHpIncreaseEnabled(){
// return common.mobHpIncrease.get() &&
// (SHMobs.healthHostileMultiplier() > 0 || SHMobs.healthPassiveMultiplier() > 0);
// }
//
// public static boolean mobDamageIncreaseEnabled(){
// return common.mobDamageIncrease.get() && SHMobs.maxDamageBoost() > 0;
// }
//
// public static boolean playerDamageScalingEnabled(){
// GameConfig.DamageScaling cfg = Config.GENERAL.damageScaling;
// return common.playerDamageScaling.get() &&
// (cfg.difficultyWeight.get() > 0 || cfg.mode.get() == DamageScaling.Mode.MAX_HEALTH); //If in max hp, dont care about diffWeight. If diffWeight is non zero. Dont care about mode.
// }
//
// public static boolean mobDamageScalingEnabled(){
// GameConfig.DamageScaling cfg = Config.GENERAL.damageScaling;
// return common.mobDamageScaling.get() &&
// (cfg.affectHostiles.get() || cfg.affectPeacefuls.get()) && //if both are false, no damage scaling occurs
// (cfg.difficultyWeight.get() > 0 || cfg.mode.get() == DamageScaling.Mode.MAX_HEALTH); //If in max hp, dont care about diffWeight. If diffWeight is non zero. Dont care about mode.
// }
//
// public static boolean difficultyEnabled(){
// return common.enableDifficulty.get() && SHDifficulty.maxValue() > 0;
// }
//
// public static boolean blightsEnabled(){
// return common.enableBlights.get() && SHMobs.blightChance() > 0;
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/world/SHWorldFeatures.java
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.GenerationStage;
import net.minecraft.world.gen.feature.Feature;
import net.minecraft.world.gen.feature.OreFeatureConfig;
import net.minecraft.world.gen.placement.CountRangeConfig;
import net.minecraft.world.gen.placement.Placement;
import net.minecraftforge.registries.ForgeRegistries;
import net.silentchaos512.lib.block.IBlockProvider;
import net.silentchaos512.scalinghealth.init.ModBlocks;
import net.silentchaos512.scalinghealth.utils.EnabledFeatures;
package net.silentchaos512.scalinghealth.world;
public class SHWorldFeatures {
public static void addFeaturesToBiomes() {
for (Biome biome : ForgeRegistries.BIOMES) {
if(EnabledFeatures.hpCrystalsOreGenEnabled()) | addOre(biome, ModBlocks.HEART_CRYSTAL_ORE, 6, 1, 0, 28); |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/init/ModPotions.java | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/potion/BandagedEffect.java
// public class BandagedEffect extends Effect {
// private static final float BASE_HEAL_RATE = 0.005f;
// private static final double SPEED_MODIFIER = -0.25;
// public static final String MOD_UUID = "732486d8-f730-41a2-868f-eb988738986f";
//
// public BandagedEffect() {
// super(EffectType.NEUTRAL, 0xf7dcad);
// this.addAttributesModifier(SharedMonsterAttributes.MOVEMENT_SPEED, MOD_UUID, SPEED_MODIFIER, AttributeModifier.Operation.MULTIPLY_TOTAL);
// }
//
// @Override
// public void performEffect(LivingEntity entityLiving, int amplifier) {
// // Remove effect if fully healed.
// if (entityLiving.getHealth() >= entityLiving.getMaxHealth()) {
// entityLiving.removePotionEffect(this);
// }
//
// float healAmount = BASE_HEAL_RATE * entityLiving.getMaxHealth() * (amplifier + 1);
// // Using Entity#heal allows us to prevent the cancelable LivingHealEvent from being fired.
// EntityHelper.heal(entityLiving, healAmount, true);
// }
//
// @Override
// public boolean isReady(int duration, int amplifier) {
// // Heal every second.
// return duration % 20 == 0;
// }
//
// @Override
// public List<ItemStack> getCurativeItems() {
// // Milk doesn't melt bandages off... right?
// return ImmutableList.of();
// }
//
// @Override
// public double getAttributeModifierAmount(int amplifier, AttributeModifier modifier) {
// // I don't want to consider the amplifier.
// return modifier.getAmount();
// }
// }
| import net.minecraft.potion.Effect;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.registries.ForgeRegistries;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.potion.BandagedEffect;
import net.silentchaos512.utils.Lazy;
import java.util.Locale;
import java.util.function.Supplier; | /*
* Scaling Health
* Copyright (C) 2018 SilentChaos512
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 3
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.silentchaos512.scalinghealth.init;
@Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
public enum ModPotions { | // Path: src/main/java/net/silentchaos512/scalinghealth/ScalingHealth.java
// @Mod(ScalingHealth.MOD_ID)
// public class ScalingHealth {
// public static final String MOD_ID = "scalinghealth";
// public static final String MOD_NAME = "Scaling Health";
// public static final String VERSION = "2.5.3";
//
// public static final Random random = new Random();
//
// public static final ItemGroup SH = new ItemGroup(MOD_ID) {
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ModItems.HEART_CRYSTAL.asItem());
// }
// };
//
// public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);
//
// public ScalingHealth() {
// Config.init();
// Network.init();
// ModLoot.init();
//
// FMLJavaModLoadingContext.get().getModEventBus().addListener(this::commonSetup);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(GlobalLootModifierSerializer.class, this::registerLootModSerializers);
//
// MinecraftForge.EVENT_BUS.addListener(this::serverAboutToStart);
// MinecraftForge.EVENT_BUS.register(PetEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DamageScaling.INSTANCE);
// }
//
// private void registerLootModSerializers(RegistryEvent.Register<GlobalLootModifierSerializer<?>> event) {
// event.getRegistry().register(new TableGlobalModifier.Serializer().setRegistryName(getId("table_loot_mod")));
// }
//
// private void commonSetup(FMLCommonSetupEvent event) {
// DifficultyAffectedCapability.register();
// DifficultySourceCapability.register();
// PlayerDataCapability.register();
// PetHealthCapability.register();
// DeferredWorkQueue.runLater(SHWorldFeatures::addFeaturesToBiomes);
// }
//
// private void serverAboutToStart(FMLServerAboutToStartEvent event) {
// ModCommands.registerAll(event.getServer().getCommandManager().getDispatcher());
// }
//
// @Mod.EventBusSubscriber(modid = MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
// public static class ClientForge {
// static {
// MinecraftForge.EVENT_BUS.register(HeartDisplayHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(DifficultyMeter.INSTANCE);
//
// DebugOverlay.init();
// }
//
// @SubscribeEvent
// public static void clientSetup(FMLClientSetupEvent event) {
// KeyManager.registerBindings();
// }
// }
//
// public static String getVersion() {
// return getVersion(false);
// }
//
// public static String getVersion(boolean correctInDev) {
// Optional<? extends ModContainer> o = ModList.get().getModContainerById(MOD_ID);
// if (o.isPresent()) {
// String str = o.get().getModInfo().getVersion().toString();
// if (correctInDev && "NONE".equals(str))
// return VERSION;
// return str;
// }
// return "0.0.0";
// }
//
// public static ResourceLocation getId(String path) {
// return new ResourceLocation(MOD_ID, path);
// }
// }
//
// Path: src/main/java/net/silentchaos512/scalinghealth/potion/BandagedEffect.java
// public class BandagedEffect extends Effect {
// private static final float BASE_HEAL_RATE = 0.005f;
// private static final double SPEED_MODIFIER = -0.25;
// public static final String MOD_UUID = "732486d8-f730-41a2-868f-eb988738986f";
//
// public BandagedEffect() {
// super(EffectType.NEUTRAL, 0xf7dcad);
// this.addAttributesModifier(SharedMonsterAttributes.MOVEMENT_SPEED, MOD_UUID, SPEED_MODIFIER, AttributeModifier.Operation.MULTIPLY_TOTAL);
// }
//
// @Override
// public void performEffect(LivingEntity entityLiving, int amplifier) {
// // Remove effect if fully healed.
// if (entityLiving.getHealth() >= entityLiving.getMaxHealth()) {
// entityLiving.removePotionEffect(this);
// }
//
// float healAmount = BASE_HEAL_RATE * entityLiving.getMaxHealth() * (amplifier + 1);
// // Using Entity#heal allows us to prevent the cancelable LivingHealEvent from being fired.
// EntityHelper.heal(entityLiving, healAmount, true);
// }
//
// @Override
// public boolean isReady(int duration, int amplifier) {
// // Heal every second.
// return duration % 20 == 0;
// }
//
// @Override
// public List<ItemStack> getCurativeItems() {
// // Milk doesn't melt bandages off... right?
// return ImmutableList.of();
// }
//
// @Override
// public double getAttributeModifierAmount(int amplifier, AttributeModifier modifier) {
// // I don't want to consider the amplifier.
// return modifier.getAmount();
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/init/ModPotions.java
import net.minecraft.potion.Effect;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.registries.ForgeRegistries;
import net.silentchaos512.scalinghealth.ScalingHealth;
import net.silentchaos512.scalinghealth.potion.BandagedEffect;
import net.silentchaos512.utils.Lazy;
import java.util.Locale;
import java.util.function.Supplier;
/*
* Scaling Health
* Copyright (C) 2018 SilentChaos512
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 3
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.silentchaos512.scalinghealth.init;
@Mod.EventBusSubscriber(modid = ScalingHealth.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
public enum ModPotions { | BANDAGED(BandagedEffect::new); |
SilentChaos512/ScalingHealth | src/main/java/net/silentchaos512/scalinghealth/capability/IDifficultyAffected.java | // Path: src/main/java/net/silentchaos512/scalinghealth/utils/SHMobs.java
// public final class SHMobs {
// private SHMobs() { throw new IllegalAccessError("Utility class"); }
//
// public static boolean allowsDifficultyChanges(MobEntity entity) {
// return !EntityTags.DIFFICULTY_EXEMPT.contains(entity.getType());
// }
//
// public static double blightChance() {
// return Config.GENERAL.mobs.blightChance.get();
// }
//
// public static boolean canBecomeBlight(MobEntity entity) {
// return EnabledFeatures.blightsEnabled() && !EntityTags.BLIGHT_EXEMPT.contains(entity.getType());
// }
//
// public static boolean isBlight(MobEntity entity) {
// return SHDifficulty.affected(entity).isBlight();
// }
//
// public static double getBlightDifficultyMultiplier() {
// return Config.GENERAL.mobs.blightDiffModifier.get();
// }
//
// public static boolean notifyOnDeath(){
// return Config.GENERAL.mobs.notifyOnBlightDeath.get();
// }
//
// public static double healthPassiveMultiplier(){
// return Config.GENERAL.mobs.passiveMultiplier.get();
// }
//
// public static double healthHostileMultiplier(){
// return Config.GENERAL.mobs.hostileMultiplier.get();
// }
//
// public static MobPotionConfig getMobPotionConfig(){
// return Config.GENERAL.mobs.randomPotions;
// }
//
// public static double passivePotionChance(){
// return Config.GENERAL.mobs.peacefulPotionChance.get();
// }
//
// public static double hostilePotionChance(){
// return Config.GENERAL.mobs.hostilePotionChance.get();
// }
//
// public static MobHealthMode healthMode(){
// return Config.GENERAL.mobs.healthMode.get();
// }
//
// public static double spawnerHealth(){
// return Config.GENERAL.mobs.spawnerModifier.get();
// }
//
// public static double xpBoost(){
// return Config.GENERAL.mobs.xpBoost.get();
// }
//
// public static double xpBlightBoost(){
// return Config.GENERAL.mobs.xpBlightBoost.get();
// }
//
// public static double damageBoostScale() {
// return Config.GENERAL.mobs.damageBoostScale.get();
// }
//
// public static double maxDamageBoost() {
// return Config.GENERAL.mobs.maxDamageBoost.get();
// }
// }
| import net.minecraft.entity.MobEntity;
import net.silentchaos512.scalinghealth.utils.SHMobs; | package net.silentchaos512.scalinghealth.capability;
public interface IDifficultyAffected {
float getDifficulty();
void setDifficulty(MobEntity mob);
void forceDifficulty(float diff);
boolean isBlight();
void setIsBlight(boolean value);
void setProcessed(boolean value);
void tick(MobEntity entity);
default float affectiveDifficulty() { | // Path: src/main/java/net/silentchaos512/scalinghealth/utils/SHMobs.java
// public final class SHMobs {
// private SHMobs() { throw new IllegalAccessError("Utility class"); }
//
// public static boolean allowsDifficultyChanges(MobEntity entity) {
// return !EntityTags.DIFFICULTY_EXEMPT.contains(entity.getType());
// }
//
// public static double blightChance() {
// return Config.GENERAL.mobs.blightChance.get();
// }
//
// public static boolean canBecomeBlight(MobEntity entity) {
// return EnabledFeatures.blightsEnabled() && !EntityTags.BLIGHT_EXEMPT.contains(entity.getType());
// }
//
// public static boolean isBlight(MobEntity entity) {
// return SHDifficulty.affected(entity).isBlight();
// }
//
// public static double getBlightDifficultyMultiplier() {
// return Config.GENERAL.mobs.blightDiffModifier.get();
// }
//
// public static boolean notifyOnDeath(){
// return Config.GENERAL.mobs.notifyOnBlightDeath.get();
// }
//
// public static double healthPassiveMultiplier(){
// return Config.GENERAL.mobs.passiveMultiplier.get();
// }
//
// public static double healthHostileMultiplier(){
// return Config.GENERAL.mobs.hostileMultiplier.get();
// }
//
// public static MobPotionConfig getMobPotionConfig(){
// return Config.GENERAL.mobs.randomPotions;
// }
//
// public static double passivePotionChance(){
// return Config.GENERAL.mobs.peacefulPotionChance.get();
// }
//
// public static double hostilePotionChance(){
// return Config.GENERAL.mobs.hostilePotionChance.get();
// }
//
// public static MobHealthMode healthMode(){
// return Config.GENERAL.mobs.healthMode.get();
// }
//
// public static double spawnerHealth(){
// return Config.GENERAL.mobs.spawnerModifier.get();
// }
//
// public static double xpBoost(){
// return Config.GENERAL.mobs.xpBoost.get();
// }
//
// public static double xpBlightBoost(){
// return Config.GENERAL.mobs.xpBlightBoost.get();
// }
//
// public static double damageBoostScale() {
// return Config.GENERAL.mobs.damageBoostScale.get();
// }
//
// public static double maxDamageBoost() {
// return Config.GENERAL.mobs.maxDamageBoost.get();
// }
// }
// Path: src/main/java/net/silentchaos512/scalinghealth/capability/IDifficultyAffected.java
import net.minecraft.entity.MobEntity;
import net.silentchaos512.scalinghealth.utils.SHMobs;
package net.silentchaos512.scalinghealth.capability;
public interface IDifficultyAffected {
float getDifficulty();
void setDifficulty(MobEntity mob);
void forceDifficulty(float diff);
boolean isBlight();
void setIsBlight(boolean value);
void setProcessed(boolean value);
void tick(MobEntity entity);
default float affectiveDifficulty() { | return isBlight() ? (float) SHMobs.getBlightDifficultyMultiplier() * getDifficulty() : getDifficulty(); |
jandy-team/jandy | jandy-server/src/main/java/io/jandy/util/sql/conditional/Where.java | // Path: jandy-server/src/main/java/io/jandy/util/sql/SubQuery.java
// public class SubQuery {
//
// private SelectQueryBuilder q;
//
// public SubQuery(SelectQueryBuilder q) {
// this.q = q;
// }
//
// public String toSql() {
// return "(" + this.q.toSql() + ")";
// }
// }
| import io.jandy.util.sql.SubQuery; | package io.jandy.util.sql.conditional;
public class Where {
private WhereType type;
private String key;
private Object value;
private Where and;
public static Where eq(String key, Object value) {
Where w = new Where();
w.type = WhereType.EQUALS;
w.key = key;
w.value = value;
return w;
}
public Where and(Where where) {
this.and = where;
return this;
}
public String toSql() {
String q = null;
switch (type) {
case EQUALS:
if (value instanceof String) {
q = key + " = " + "'" + value.toString() + "'"; | // Path: jandy-server/src/main/java/io/jandy/util/sql/SubQuery.java
// public class SubQuery {
//
// private SelectQueryBuilder q;
//
// public SubQuery(SelectQueryBuilder q) {
// this.q = q;
// }
//
// public String toSql() {
// return "(" + this.q.toSql() + ")";
// }
// }
// Path: jandy-server/src/main/java/io/jandy/util/sql/conditional/Where.java
import io.jandy.util.sql.SubQuery;
package io.jandy.util.sql.conditional;
public class Where {
private WhereType type;
private String key;
private Object value;
private Where and;
public static Where eq(String key, Object value) {
Where w = new Where();
w.type = WhereType.EQUALS;
w.key = key;
w.value = value;
return w;
}
public Where and(Where where) {
this.and = where;
return this;
}
public String toSql() {
String q = null;
switch (type) {
case EQUALS:
if (value instanceof String) {
q = key + " = " + "'" + value.toString() + "'"; | } else if (value instanceof SubQuery) { |
jandy-team/jandy | jandy-java-profiler/src/main/java/io/jandy/java/JandyProfilingContext.java | // Path: jandy-java-profiler/src/main/java/io/jandy/java/data/ThreadObject.java
// public class ThreadObject {
// private long threadId;
// private String threadName;
// private String rootId;
//
// public String getThreadName() {
// return threadName;
// }
//
// public ThreadObject setThreadName(String threadName) {
// this.threadName = threadName;
// return this;
// }
//
// public long getThreadId() {
// return threadId;
// }
//
// public ThreadObject setThreadId(long threadId) {
// this.threadId = threadId;
// return this;
// }
//
// public String getRootId() {
// return rootId;
// }
//
// public ThreadObject setRootId(String rootId) {
// this.rootId = rootId;
// return this;
// }
//
// }
//
// Path: jandy-java-profiler/src/main/java/io/jandy/java/profiler/ThreadContext.java
// public class ThreadContext {
// private final DataObjectBuilder builder;
// private TreeNode latest, root;
// private ArrayCallStack treeNodes = new ArrayCallStack(128);
// private ThreadObject thread = new ThreadObject();
//
// public ThreadContext(long threadId, String threadName, DataObjectBuilder builder) throws IOException {
// this.thread.setThreadId(threadId);
// this.thread.setThreadName(threadName);
// this.builder = builder;
//
// this.latest = builder.getRootTreeNode();
// this.root = this.latest;
// this.thread.setRootId(this.root.getId());
//
// builder.save(this.latest);
// }
//
// public void onMethodEnter(String className, int access, String methodName, String desc) {
// treeNodes.push(latest);
//
// latest = this.builder.getTreeNode(className.replace('/', '.'), access, methodName, desc, latest.getId());
//
// latest.getAcc().setStartTime(System.nanoTime());
// }
//
// public void onMethodExit(Throwable throwable) {
// // assert(latest.method.getName().equals(method.getName()));
// // assert(latest.method.getDescriptor().equals(method.getDescriptor()));
// // assert(latest.method.getAccess() == method.getAccess());
// // assert(latest.method.getOwner().getName().equals(owner.getName()));
// // assert(latest.method.getOwner().getPackageName().equals(owner.getPackageName()));
//
// long elapsedTime = System.nanoTime() - latest.getAcc().getStartTime();
// latest.getAcc().setElapsedTime(latest.getAcc().getElapsedTime() + elapsedTime);
// if (throwable != null)
// latest.getAcc().setException(builder.getExceptionObject(throwable));
//
// long time = System.nanoTime();
// builder.save(latest);
// time = System.nanoTime() - time;
//
// latest = treeNodes.pop();
// if (latest.getAcc() != null) {
// latest.getAcc().setElapsedTime(latest.getAcc().getElapsedTime() - time);
// }
// }
//
// public void onExit() {
// while (latest != root)
// onMethodExit(null);
// }
//
// public TreeNode getRoot() {
// return root;
// }
//
// public ThreadObject getThreadObject() {
// return thread;
// }
// }
| import io.jandy.java.data.ThreadObject;
import io.jandy.java.data.TreeNode;
import io.jandy.java.profiler.ThreadContext;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | package io.jandy.java;
/**
* @author JCooky
* @since 2016-06-07
*/
public class JandyProfilingContext {
private ProfilingLogCollector collector;
private long profId;
public void start() throws IOException {
String baseUrl = System.getProperty("jandy.base.url") + "/rest/travis";
String sampleName = System.getProperty("jandy.sample.name");
long batchSize = toBytes(System.getProperty("jandy.batch.size"));
String repoSlug = System.getenv("TRAVIS_REPO_SLUG");
long buildId = Long.parseLong(System.getenv("TRAVIS_BUILD_ID"));
long buildNum = Long.parseLong(System.getenv("TRAVIS_BUILD_NUMBER"));
String branchName = System.getenv("TRAVIS_BRANCH");
collector = new ProfilingLogCollector(baseUrl, batchSize);
this.profId = collector.start(sampleName, repoSlug, branchName, buildId, buildNum, "java");
}
| // Path: jandy-java-profiler/src/main/java/io/jandy/java/data/ThreadObject.java
// public class ThreadObject {
// private long threadId;
// private String threadName;
// private String rootId;
//
// public String getThreadName() {
// return threadName;
// }
//
// public ThreadObject setThreadName(String threadName) {
// this.threadName = threadName;
// return this;
// }
//
// public long getThreadId() {
// return threadId;
// }
//
// public ThreadObject setThreadId(long threadId) {
// this.threadId = threadId;
// return this;
// }
//
// public String getRootId() {
// return rootId;
// }
//
// public ThreadObject setRootId(String rootId) {
// this.rootId = rootId;
// return this;
// }
//
// }
//
// Path: jandy-java-profiler/src/main/java/io/jandy/java/profiler/ThreadContext.java
// public class ThreadContext {
// private final DataObjectBuilder builder;
// private TreeNode latest, root;
// private ArrayCallStack treeNodes = new ArrayCallStack(128);
// private ThreadObject thread = new ThreadObject();
//
// public ThreadContext(long threadId, String threadName, DataObjectBuilder builder) throws IOException {
// this.thread.setThreadId(threadId);
// this.thread.setThreadName(threadName);
// this.builder = builder;
//
// this.latest = builder.getRootTreeNode();
// this.root = this.latest;
// this.thread.setRootId(this.root.getId());
//
// builder.save(this.latest);
// }
//
// public void onMethodEnter(String className, int access, String methodName, String desc) {
// treeNodes.push(latest);
//
// latest = this.builder.getTreeNode(className.replace('/', '.'), access, methodName, desc, latest.getId());
//
// latest.getAcc().setStartTime(System.nanoTime());
// }
//
// public void onMethodExit(Throwable throwable) {
// // assert(latest.method.getName().equals(method.getName()));
// // assert(latest.method.getDescriptor().equals(method.getDescriptor()));
// // assert(latest.method.getAccess() == method.getAccess());
// // assert(latest.method.getOwner().getName().equals(owner.getName()));
// // assert(latest.method.getOwner().getPackageName().equals(owner.getPackageName()));
//
// long elapsedTime = System.nanoTime() - latest.getAcc().getStartTime();
// latest.getAcc().setElapsedTime(latest.getAcc().getElapsedTime() + elapsedTime);
// if (throwable != null)
// latest.getAcc().setException(builder.getExceptionObject(throwable));
//
// long time = System.nanoTime();
// builder.save(latest);
// time = System.nanoTime() - time;
//
// latest = treeNodes.pop();
// if (latest.getAcc() != null) {
// latest.getAcc().setElapsedTime(latest.getAcc().getElapsedTime() - time);
// }
// }
//
// public void onExit() {
// while (latest != root)
// onMethodExit(null);
// }
//
// public TreeNode getRoot() {
// return root;
// }
//
// public ThreadObject getThreadObject() {
// return thread;
// }
// }
// Path: jandy-java-profiler/src/main/java/io/jandy/java/JandyProfilingContext.java
import io.jandy.java.data.ThreadObject;
import io.jandy.java.data.TreeNode;
import io.jandy.java.profiler.ThreadContext;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package io.jandy.java;
/**
* @author JCooky
* @since 2016-06-07
*/
public class JandyProfilingContext {
private ProfilingLogCollector collector;
private long profId;
public void start() throws IOException {
String baseUrl = System.getProperty("jandy.base.url") + "/rest/travis";
String sampleName = System.getProperty("jandy.sample.name");
long batchSize = toBytes(System.getProperty("jandy.batch.size"));
String repoSlug = System.getenv("TRAVIS_REPO_SLUG");
long buildId = Long.parseLong(System.getenv("TRAVIS_BUILD_ID"));
long buildNum = Long.parseLong(System.getenv("TRAVIS_BUILD_NUMBER"));
String branchName = System.getenv("TRAVIS_BRANCH");
collector = new ProfilingLogCollector(baseUrl, batchSize);
this.profId = collector.start(sampleName, repoSlug, branchName, buildId, buildNum, "java");
}
| public void end(List<ThreadContext> threadContexts) { |
jandy-team/jandy | jandy-java-profiler/src/main/java/io/jandy/java/JandyProfilingContext.java | // Path: jandy-java-profiler/src/main/java/io/jandy/java/data/ThreadObject.java
// public class ThreadObject {
// private long threadId;
// private String threadName;
// private String rootId;
//
// public String getThreadName() {
// return threadName;
// }
//
// public ThreadObject setThreadName(String threadName) {
// this.threadName = threadName;
// return this;
// }
//
// public long getThreadId() {
// return threadId;
// }
//
// public ThreadObject setThreadId(long threadId) {
// this.threadId = threadId;
// return this;
// }
//
// public String getRootId() {
// return rootId;
// }
//
// public ThreadObject setRootId(String rootId) {
// this.rootId = rootId;
// return this;
// }
//
// }
//
// Path: jandy-java-profiler/src/main/java/io/jandy/java/profiler/ThreadContext.java
// public class ThreadContext {
// private final DataObjectBuilder builder;
// private TreeNode latest, root;
// private ArrayCallStack treeNodes = new ArrayCallStack(128);
// private ThreadObject thread = new ThreadObject();
//
// public ThreadContext(long threadId, String threadName, DataObjectBuilder builder) throws IOException {
// this.thread.setThreadId(threadId);
// this.thread.setThreadName(threadName);
// this.builder = builder;
//
// this.latest = builder.getRootTreeNode();
// this.root = this.latest;
// this.thread.setRootId(this.root.getId());
//
// builder.save(this.latest);
// }
//
// public void onMethodEnter(String className, int access, String methodName, String desc) {
// treeNodes.push(latest);
//
// latest = this.builder.getTreeNode(className.replace('/', '.'), access, methodName, desc, latest.getId());
//
// latest.getAcc().setStartTime(System.nanoTime());
// }
//
// public void onMethodExit(Throwable throwable) {
// // assert(latest.method.getName().equals(method.getName()));
// // assert(latest.method.getDescriptor().equals(method.getDescriptor()));
// // assert(latest.method.getAccess() == method.getAccess());
// // assert(latest.method.getOwner().getName().equals(owner.getName()));
// // assert(latest.method.getOwner().getPackageName().equals(owner.getPackageName()));
//
// long elapsedTime = System.nanoTime() - latest.getAcc().getStartTime();
// latest.getAcc().setElapsedTime(latest.getAcc().getElapsedTime() + elapsedTime);
// if (throwable != null)
// latest.getAcc().setException(builder.getExceptionObject(throwable));
//
// long time = System.nanoTime();
// builder.save(latest);
// time = System.nanoTime() - time;
//
// latest = treeNodes.pop();
// if (latest.getAcc() != null) {
// latest.getAcc().setElapsedTime(latest.getAcc().getElapsedTime() - time);
// }
// }
//
// public void onExit() {
// while (latest != root)
// onMethodExit(null);
// }
//
// public TreeNode getRoot() {
// return root;
// }
//
// public ThreadObject getThreadObject() {
// return thread;
// }
// }
| import io.jandy.java.data.ThreadObject;
import io.jandy.java.data.TreeNode;
import io.jandy.java.profiler.ThreadContext;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | package io.jandy.java;
/**
* @author JCooky
* @since 2016-06-07
*/
public class JandyProfilingContext {
private ProfilingLogCollector collector;
private long profId;
public void start() throws IOException {
String baseUrl = System.getProperty("jandy.base.url") + "/rest/travis";
String sampleName = System.getProperty("jandy.sample.name");
long batchSize = toBytes(System.getProperty("jandy.batch.size"));
String repoSlug = System.getenv("TRAVIS_REPO_SLUG");
long buildId = Long.parseLong(System.getenv("TRAVIS_BUILD_ID"));
long buildNum = Long.parseLong(System.getenv("TRAVIS_BUILD_NUMBER"));
String branchName = System.getenv("TRAVIS_BRANCH");
collector = new ProfilingLogCollector(baseUrl, batchSize);
this.profId = collector.start(sampleName, repoSlug, branchName, buildId, buildNum, "java");
}
public void end(List<ThreadContext> threadContexts) { | // Path: jandy-java-profiler/src/main/java/io/jandy/java/data/ThreadObject.java
// public class ThreadObject {
// private long threadId;
// private String threadName;
// private String rootId;
//
// public String getThreadName() {
// return threadName;
// }
//
// public ThreadObject setThreadName(String threadName) {
// this.threadName = threadName;
// return this;
// }
//
// public long getThreadId() {
// return threadId;
// }
//
// public ThreadObject setThreadId(long threadId) {
// this.threadId = threadId;
// return this;
// }
//
// public String getRootId() {
// return rootId;
// }
//
// public ThreadObject setRootId(String rootId) {
// this.rootId = rootId;
// return this;
// }
//
// }
//
// Path: jandy-java-profiler/src/main/java/io/jandy/java/profiler/ThreadContext.java
// public class ThreadContext {
// private final DataObjectBuilder builder;
// private TreeNode latest, root;
// private ArrayCallStack treeNodes = new ArrayCallStack(128);
// private ThreadObject thread = new ThreadObject();
//
// public ThreadContext(long threadId, String threadName, DataObjectBuilder builder) throws IOException {
// this.thread.setThreadId(threadId);
// this.thread.setThreadName(threadName);
// this.builder = builder;
//
// this.latest = builder.getRootTreeNode();
// this.root = this.latest;
// this.thread.setRootId(this.root.getId());
//
// builder.save(this.latest);
// }
//
// public void onMethodEnter(String className, int access, String methodName, String desc) {
// treeNodes.push(latest);
//
// latest = this.builder.getTreeNode(className.replace('/', '.'), access, methodName, desc, latest.getId());
//
// latest.getAcc().setStartTime(System.nanoTime());
// }
//
// public void onMethodExit(Throwable throwable) {
// // assert(latest.method.getName().equals(method.getName()));
// // assert(latest.method.getDescriptor().equals(method.getDescriptor()));
// // assert(latest.method.getAccess() == method.getAccess());
// // assert(latest.method.getOwner().getName().equals(owner.getName()));
// // assert(latest.method.getOwner().getPackageName().equals(owner.getPackageName()));
//
// long elapsedTime = System.nanoTime() - latest.getAcc().getStartTime();
// latest.getAcc().setElapsedTime(latest.getAcc().getElapsedTime() + elapsedTime);
// if (throwable != null)
// latest.getAcc().setException(builder.getExceptionObject(throwable));
//
// long time = System.nanoTime();
// builder.save(latest);
// time = System.nanoTime() - time;
//
// latest = treeNodes.pop();
// if (latest.getAcc() != null) {
// latest.getAcc().setElapsedTime(latest.getAcc().getElapsedTime() - time);
// }
// }
//
// public void onExit() {
// while (latest != root)
// onMethodExit(null);
// }
//
// public TreeNode getRoot() {
// return root;
// }
//
// public ThreadObject getThreadObject() {
// return thread;
// }
// }
// Path: jandy-java-profiler/src/main/java/io/jandy/java/JandyProfilingContext.java
import io.jandy.java.data.ThreadObject;
import io.jandy.java.data.TreeNode;
import io.jandy.java.profiler.ThreadContext;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package io.jandy.java;
/**
* @author JCooky
* @since 2016-06-07
*/
public class JandyProfilingContext {
private ProfilingLogCollector collector;
private long profId;
public void start() throws IOException {
String baseUrl = System.getProperty("jandy.base.url") + "/rest/travis";
String sampleName = System.getProperty("jandy.sample.name");
long batchSize = toBytes(System.getProperty("jandy.batch.size"));
String repoSlug = System.getenv("TRAVIS_REPO_SLUG");
long buildId = Long.parseLong(System.getenv("TRAVIS_BUILD_ID"));
long buildNum = Long.parseLong(System.getenv("TRAVIS_BUILD_NUMBER"));
String branchName = System.getenv("TRAVIS_BRANCH");
collector = new ProfilingLogCollector(baseUrl, batchSize);
this.profId = collector.start(sampleName, repoSlug, branchName, buildId, buildNum, "java");
}
public void end(List<ThreadContext> threadContexts) { | List<ThreadObject> threadObjects = new ArrayList<ThreadObject>(); |
jandy-team/jandy | jandy-java-profiler/src/main/java/io/jandy/java/profiler/ThreadContext.java | // Path: jandy-java-profiler/src/main/java/io/jandy/java/DataObjectBuilder.java
// public abstract class DataObjectBuilder {
//
// public abstract void save(TreeNode node);
//
// public TreeNode getRootTreeNode() {
// TreeNode n = new TreeNode();
// n.setId(UUID.randomUUID().toString());
// n.setMethod(null);
// n.setRoot(true);
// n.setAcc(null);
//
// return n;
// }
//
// public TreeNode getTreeNode(String className, int access, String methodName, String desc, String parentId) {
// TreeNode n = new TreeNode();
// n.setId(UUID.randomUUID().toString());
// n.setMethod(getMethodObject(className, access, methodName, desc));
// n.setAcc(new Accumulator());
// n.setRoot(false);
// n.setParentId(parentId);
//
// return n;
// }
//
// public MethodObject getMethodObject(String className, int access, String methodName, String desc) {
// MethodObject m = new MethodObject();
// m.setId(UUID.randomUUID().toString());
// m.setOwner(getClassObject(className));
// m.setName(methodName);
// m.setAccess(access);
// m.setDescriptor(desc);
//
// return m;
// }
//
// public ClassObject getClassObject(String className) {
//
// ClassKey key = new ClassKey(className);
// ClassObject c = new ClassObject();
// c.setId(UUID.randomUUID().toString());
// c.setName(key.getClassName());
// c.setPackageName(key.getPackageName());
//
// return c;
// }
//
// public ExceptionObject getExceptionObject(Throwable throwable) {
// ExceptionObject e = new ExceptionObject();
// e.setId(UUID.randomUUID().toString());
// e.setKlass(getClassObject(throwable.getClass().getName()));
// e.setMessage(throwable.getMessage());
//
// return e;
// }
//
// // public static ProfilingContext merge(Iterable<ProfilingContext> contexts) {
// // TreeNode root = new TreeNode();
// // root.setId(UUID.randomUUID().toString());
// // root.setRoot(true);
// // for (ProfilingContext context : contexts) {
// // assert (context.getRootId().equals(context.getNodes().get(0).getId()));
// // context.getNodes().get(0).setParentId(root.getId());
// // }
// //
// // List<TreeNode> nodes = new ArrayList<TreeNode>();
// // Set<MethodObject> methods = new HashSet<MethodObject>();
// // Set<ClassObject> classes = new HashSet<ClassObject>();
// // List<ExceptionObject> exceptions = new ArrayList<ExceptionObject>();
// //
// // nodes.add(0, root);
// // for (ProfilingContext context : contexts) {
// // nodes.addAll(context.getNodes());
// // methods.addAll(context.getMethods());
// // classes.addAll(context.getClasses());
// // exceptions.addAll(context.getExceptions());
// // }
// //
// // ProfilingContext m = new ProfilingContext();
// // m.setNodes(nodes);
// // m.setMethods(new ArrayList<MethodObject>(methods));
// // m.setClasses(new ArrayList<ClassObject>(classes));
// // m.setExceptions(exceptions);
// //
// // m.setRootId(root.getId());
// //
// // return m;
// // }
// }
//
// Path: jandy-java-profiler/src/main/java/io/jandy/java/data/ThreadObject.java
// public class ThreadObject {
// private long threadId;
// private String threadName;
// private String rootId;
//
// public String getThreadName() {
// return threadName;
// }
//
// public ThreadObject setThreadName(String threadName) {
// this.threadName = threadName;
// return this;
// }
//
// public long getThreadId() {
// return threadId;
// }
//
// public ThreadObject setThreadId(long threadId) {
// this.threadId = threadId;
// return this;
// }
//
// public String getRootId() {
// return rootId;
// }
//
// public ThreadObject setRootId(String rootId) {
// this.rootId = rootId;
// return this;
// }
//
// }
| import io.jandy.java.DataObjectBuilder;
import io.jandy.java.data.ThreadObject;
import io.jandy.java.data.TreeNode;
import io.jandy.java.util.ArrayCallStack;
import java.io.IOException; | package io.jandy.java.profiler;
/**
* @author JCooky
* @since 2016-05-23
*/
public class ThreadContext {
private final DataObjectBuilder builder;
private TreeNode latest, root;
private ArrayCallStack treeNodes = new ArrayCallStack(128); | // Path: jandy-java-profiler/src/main/java/io/jandy/java/DataObjectBuilder.java
// public abstract class DataObjectBuilder {
//
// public abstract void save(TreeNode node);
//
// public TreeNode getRootTreeNode() {
// TreeNode n = new TreeNode();
// n.setId(UUID.randomUUID().toString());
// n.setMethod(null);
// n.setRoot(true);
// n.setAcc(null);
//
// return n;
// }
//
// public TreeNode getTreeNode(String className, int access, String methodName, String desc, String parentId) {
// TreeNode n = new TreeNode();
// n.setId(UUID.randomUUID().toString());
// n.setMethod(getMethodObject(className, access, methodName, desc));
// n.setAcc(new Accumulator());
// n.setRoot(false);
// n.setParentId(parentId);
//
// return n;
// }
//
// public MethodObject getMethodObject(String className, int access, String methodName, String desc) {
// MethodObject m = new MethodObject();
// m.setId(UUID.randomUUID().toString());
// m.setOwner(getClassObject(className));
// m.setName(methodName);
// m.setAccess(access);
// m.setDescriptor(desc);
//
// return m;
// }
//
// public ClassObject getClassObject(String className) {
//
// ClassKey key = new ClassKey(className);
// ClassObject c = new ClassObject();
// c.setId(UUID.randomUUID().toString());
// c.setName(key.getClassName());
// c.setPackageName(key.getPackageName());
//
// return c;
// }
//
// public ExceptionObject getExceptionObject(Throwable throwable) {
// ExceptionObject e = new ExceptionObject();
// e.setId(UUID.randomUUID().toString());
// e.setKlass(getClassObject(throwable.getClass().getName()));
// e.setMessage(throwable.getMessage());
//
// return e;
// }
//
// // public static ProfilingContext merge(Iterable<ProfilingContext> contexts) {
// // TreeNode root = new TreeNode();
// // root.setId(UUID.randomUUID().toString());
// // root.setRoot(true);
// // for (ProfilingContext context : contexts) {
// // assert (context.getRootId().equals(context.getNodes().get(0).getId()));
// // context.getNodes().get(0).setParentId(root.getId());
// // }
// //
// // List<TreeNode> nodes = new ArrayList<TreeNode>();
// // Set<MethodObject> methods = new HashSet<MethodObject>();
// // Set<ClassObject> classes = new HashSet<ClassObject>();
// // List<ExceptionObject> exceptions = new ArrayList<ExceptionObject>();
// //
// // nodes.add(0, root);
// // for (ProfilingContext context : contexts) {
// // nodes.addAll(context.getNodes());
// // methods.addAll(context.getMethods());
// // classes.addAll(context.getClasses());
// // exceptions.addAll(context.getExceptions());
// // }
// //
// // ProfilingContext m = new ProfilingContext();
// // m.setNodes(nodes);
// // m.setMethods(new ArrayList<MethodObject>(methods));
// // m.setClasses(new ArrayList<ClassObject>(classes));
// // m.setExceptions(exceptions);
// //
// // m.setRootId(root.getId());
// //
// // return m;
// // }
// }
//
// Path: jandy-java-profiler/src/main/java/io/jandy/java/data/ThreadObject.java
// public class ThreadObject {
// private long threadId;
// private String threadName;
// private String rootId;
//
// public String getThreadName() {
// return threadName;
// }
//
// public ThreadObject setThreadName(String threadName) {
// this.threadName = threadName;
// return this;
// }
//
// public long getThreadId() {
// return threadId;
// }
//
// public ThreadObject setThreadId(long threadId) {
// this.threadId = threadId;
// return this;
// }
//
// public String getRootId() {
// return rootId;
// }
//
// public ThreadObject setRootId(String rootId) {
// this.rootId = rootId;
// return this;
// }
//
// }
// Path: jandy-java-profiler/src/main/java/io/jandy/java/profiler/ThreadContext.java
import io.jandy.java.DataObjectBuilder;
import io.jandy.java.data.ThreadObject;
import io.jandy.java.data.TreeNode;
import io.jandy.java.util.ArrayCallStack;
import java.io.IOException;
package io.jandy.java.profiler;
/**
* @author JCooky
* @since 2016-05-23
*/
public class ThreadContext {
private final DataObjectBuilder builder;
private TreeNode latest, root;
private ArrayCallStack treeNodes = new ArrayCallStack(128); | private ThreadObject thread = new ThreadObject(); |
jandy-team/jandy | jandy-server/src/main/java/io/jandy/service/impl/ProfServiceForMySQL.java | // Path: jandy-server/src/main/java/io/jandy/domain/data/ClassObject.java
// @Data
// @Accessors(chain = true)
// public class ClassObject implements Serializable {
// private String id;
// private String name;
// private String packageName;
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// ClassObject that = (ClassObject) o;
// return Objects.equals(name, that.name) &&
// Objects.equals(packageName, that.packageName);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name, packageName);
// }
// }
//
// Path: jandy-server/src/main/java/io/jandy/domain/data/ExceptionObject.java
// @Data
// @Accessors(chain = true)
// public class ExceptionObject implements Serializable {
//
// private String id;
// private ClassObject klass;
// private String message;
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/sql/conditional/Where.java
// public static Where eq(String key, Object value) {
// Where w = new Where();
// w.type = WhereType.EQUALS;
// w.key = key;
// w.value = value;
//
// return w;
// }
| import io.jandy.domain.data.ClassObject;
import io.jandy.domain.data.ExceptionObject;
import io.jandy.domain.data.MethodObject;
import io.jandy.domain.data.TreeNode;
import io.jandy.service.ProfService;
import io.jandy.util.sql.BatchUpdateQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static io.jandy.util.sql.Query.*;
import static io.jandy.util.sql.Query.select;
import static io.jandy.util.sql.Query.subQuery;
import static io.jandy.util.sql.conditional.Where.eq; | package io.jandy.service.impl;
/**
* Created by naver on 2017. 3. 20..
*/
@Service
@Profile("mysql")
public class ProfServiceForMySQL extends ProfService {
@Autowired
private JdbcTemplate jdbc;
@Transactional
protected void doUpdateTreeNodes0(List<TreeNode> treeNodes) {
Set<MethodObject> methodObjects = treeNodes.stream().map(TreeNode::getMethod).filter(Objects::nonNull).collect(Collectors.toSet()); | // Path: jandy-server/src/main/java/io/jandy/domain/data/ClassObject.java
// @Data
// @Accessors(chain = true)
// public class ClassObject implements Serializable {
// private String id;
// private String name;
// private String packageName;
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// ClassObject that = (ClassObject) o;
// return Objects.equals(name, that.name) &&
// Objects.equals(packageName, that.packageName);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name, packageName);
// }
// }
//
// Path: jandy-server/src/main/java/io/jandy/domain/data/ExceptionObject.java
// @Data
// @Accessors(chain = true)
// public class ExceptionObject implements Serializable {
//
// private String id;
// private ClassObject klass;
// private String message;
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/sql/conditional/Where.java
// public static Where eq(String key, Object value) {
// Where w = new Where();
// w.type = WhereType.EQUALS;
// w.key = key;
// w.value = value;
//
// return w;
// }
// Path: jandy-server/src/main/java/io/jandy/service/impl/ProfServiceForMySQL.java
import io.jandy.domain.data.ClassObject;
import io.jandy.domain.data.ExceptionObject;
import io.jandy.domain.data.MethodObject;
import io.jandy.domain.data.TreeNode;
import io.jandy.service.ProfService;
import io.jandy.util.sql.BatchUpdateQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static io.jandy.util.sql.Query.*;
import static io.jandy.util.sql.Query.select;
import static io.jandy.util.sql.Query.subQuery;
import static io.jandy.util.sql.conditional.Where.eq;
package io.jandy.service.impl;
/**
* Created by naver on 2017. 3. 20..
*/
@Service
@Profile("mysql")
public class ProfServiceForMySQL extends ProfService {
@Autowired
private JdbcTemplate jdbc;
@Transactional
protected void doUpdateTreeNodes0(List<TreeNode> treeNodes) {
Set<MethodObject> methodObjects = treeNodes.stream().map(TreeNode::getMethod).filter(Objects::nonNull).collect(Collectors.toSet()); | Set<ClassObject> classObjects = treeNodes.stream().map(TreeNode::getMethod).filter(Objects::nonNull).map(MethodObject::getOwner).filter(Objects::nonNull).collect(Collectors.toSet()); |
jandy-team/jandy | jandy-server/src/main/java/io/jandy/service/impl/ProfServiceForMySQL.java | // Path: jandy-server/src/main/java/io/jandy/domain/data/ClassObject.java
// @Data
// @Accessors(chain = true)
// public class ClassObject implements Serializable {
// private String id;
// private String name;
// private String packageName;
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// ClassObject that = (ClassObject) o;
// return Objects.equals(name, that.name) &&
// Objects.equals(packageName, that.packageName);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name, packageName);
// }
// }
//
// Path: jandy-server/src/main/java/io/jandy/domain/data/ExceptionObject.java
// @Data
// @Accessors(chain = true)
// public class ExceptionObject implements Serializable {
//
// private String id;
// private ClassObject klass;
// private String message;
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/sql/conditional/Where.java
// public static Where eq(String key, Object value) {
// Where w = new Where();
// w.type = WhereType.EQUALS;
// w.key = key;
// w.value = value;
//
// return w;
// }
| import io.jandy.domain.data.ClassObject;
import io.jandy.domain.data.ExceptionObject;
import io.jandy.domain.data.MethodObject;
import io.jandy.domain.data.TreeNode;
import io.jandy.service.ProfService;
import io.jandy.util.sql.BatchUpdateQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static io.jandy.util.sql.Query.*;
import static io.jandy.util.sql.Query.select;
import static io.jandy.util.sql.Query.subQuery;
import static io.jandy.util.sql.conditional.Where.eq; | package io.jandy.service.impl;
/**
* Created by naver on 2017. 3. 20..
*/
@Service
@Profile("mysql")
public class ProfServiceForMySQL extends ProfService {
@Autowired
private JdbcTemplate jdbc;
@Transactional
protected void doUpdateTreeNodes0(List<TreeNode> treeNodes) {
Set<MethodObject> methodObjects = treeNodes.stream().map(TreeNode::getMethod).filter(Objects::nonNull).collect(Collectors.toSet());
Set<ClassObject> classObjects = treeNodes.stream().map(TreeNode::getMethod).filter(Objects::nonNull).map(MethodObject::getOwner).filter(Objects::nonNull).collect(Collectors.toSet()); | // Path: jandy-server/src/main/java/io/jandy/domain/data/ClassObject.java
// @Data
// @Accessors(chain = true)
// public class ClassObject implements Serializable {
// private String id;
// private String name;
// private String packageName;
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// ClassObject that = (ClassObject) o;
// return Objects.equals(name, that.name) &&
// Objects.equals(packageName, that.packageName);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name, packageName);
// }
// }
//
// Path: jandy-server/src/main/java/io/jandy/domain/data/ExceptionObject.java
// @Data
// @Accessors(chain = true)
// public class ExceptionObject implements Serializable {
//
// private String id;
// private ClassObject klass;
// private String message;
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/sql/conditional/Where.java
// public static Where eq(String key, Object value) {
// Where w = new Where();
// w.type = WhereType.EQUALS;
// w.key = key;
// w.value = value;
//
// return w;
// }
// Path: jandy-server/src/main/java/io/jandy/service/impl/ProfServiceForMySQL.java
import io.jandy.domain.data.ClassObject;
import io.jandy.domain.data.ExceptionObject;
import io.jandy.domain.data.MethodObject;
import io.jandy.domain.data.TreeNode;
import io.jandy.service.ProfService;
import io.jandy.util.sql.BatchUpdateQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static io.jandy.util.sql.Query.*;
import static io.jandy.util.sql.Query.select;
import static io.jandy.util.sql.Query.subQuery;
import static io.jandy.util.sql.conditional.Where.eq;
package io.jandy.service.impl;
/**
* Created by naver on 2017. 3. 20..
*/
@Service
@Profile("mysql")
public class ProfServiceForMySQL extends ProfService {
@Autowired
private JdbcTemplate jdbc;
@Transactional
protected void doUpdateTreeNodes0(List<TreeNode> treeNodes) {
Set<MethodObject> methodObjects = treeNodes.stream().map(TreeNode::getMethod).filter(Objects::nonNull).collect(Collectors.toSet());
Set<ClassObject> classObjects = treeNodes.stream().map(TreeNode::getMethod).filter(Objects::nonNull).map(MethodObject::getOwner).filter(Objects::nonNull).collect(Collectors.toSet()); | List<ExceptionObject> exceptionObjects = treeNodes.stream().map(n -> n.getAcc() == null ? null : n.getAcc().getException()).filter(Objects::nonNull).collect(Collectors.toList()); |
jandy-team/jandy | jandy-server/src/main/java/io/jandy/service/impl/ProfServiceForMySQL.java | // Path: jandy-server/src/main/java/io/jandy/domain/data/ClassObject.java
// @Data
// @Accessors(chain = true)
// public class ClassObject implements Serializable {
// private String id;
// private String name;
// private String packageName;
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// ClassObject that = (ClassObject) o;
// return Objects.equals(name, that.name) &&
// Objects.equals(packageName, that.packageName);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name, packageName);
// }
// }
//
// Path: jandy-server/src/main/java/io/jandy/domain/data/ExceptionObject.java
// @Data
// @Accessors(chain = true)
// public class ExceptionObject implements Serializable {
//
// private String id;
// private ClassObject klass;
// private String message;
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/sql/conditional/Where.java
// public static Where eq(String key, Object value) {
// Where w = new Where();
// w.type = WhereType.EQUALS;
// w.key = key;
// w.value = value;
//
// return w;
// }
| import io.jandy.domain.data.ClassObject;
import io.jandy.domain.data.ExceptionObject;
import io.jandy.domain.data.MethodObject;
import io.jandy.domain.data.TreeNode;
import io.jandy.service.ProfService;
import io.jandy.util.sql.BatchUpdateQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static io.jandy.util.sql.Query.*;
import static io.jandy.util.sql.Query.select;
import static io.jandy.util.sql.Query.subQuery;
import static io.jandy.util.sql.conditional.Where.eq; | package io.jandy.service.impl;
/**
* Created by naver on 2017. 3. 20..
*/
@Service
@Profile("mysql")
public class ProfServiceForMySQL extends ProfService {
@Autowired
private JdbcTemplate jdbc;
@Transactional
protected void doUpdateTreeNodes0(List<TreeNode> treeNodes) {
Set<MethodObject> methodObjects = treeNodes.stream().map(TreeNode::getMethod).filter(Objects::nonNull).collect(Collectors.toSet());
Set<ClassObject> classObjects = treeNodes.stream().map(TreeNode::getMethod).filter(Objects::nonNull).map(MethodObject::getOwner).filter(Objects::nonNull).collect(Collectors.toSet());
List<ExceptionObject> exceptionObjects = treeNodes.stream().map(n -> n.getAcc() == null ? null : n.getAcc().getException()).filter(Objects::nonNull).collect(Collectors.toList());
if (classObjects.size() > 0) {
insert().ignore().into("prof_class")
.columns("name", "package_name")
.values(classObjects.stream().map(co -> new Object[] {co.getName(), co.getPackageName()}))
.execute(jdbc);
}
if (methodObjects.size() > 0) {
insert().ignore().into("prof_method")
.columns("name", "access", "descriptor", "owner_id")
.values(methodObjects.stream().map(mo -> new Object[]{
mo.getName(), mo.getAccess(), mo.getDescriptor(),
mo.getOwner() == null ? null : subQuery(
select().columns("id").from("prof_class").where( | // Path: jandy-server/src/main/java/io/jandy/domain/data/ClassObject.java
// @Data
// @Accessors(chain = true)
// public class ClassObject implements Serializable {
// private String id;
// private String name;
// private String packageName;
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// ClassObject that = (ClassObject) o;
// return Objects.equals(name, that.name) &&
// Objects.equals(packageName, that.packageName);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name, packageName);
// }
// }
//
// Path: jandy-server/src/main/java/io/jandy/domain/data/ExceptionObject.java
// @Data
// @Accessors(chain = true)
// public class ExceptionObject implements Serializable {
//
// private String id;
// private ClassObject klass;
// private String message;
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/sql/conditional/Where.java
// public static Where eq(String key, Object value) {
// Where w = new Where();
// w.type = WhereType.EQUALS;
// w.key = key;
// w.value = value;
//
// return w;
// }
// Path: jandy-server/src/main/java/io/jandy/service/impl/ProfServiceForMySQL.java
import io.jandy.domain.data.ClassObject;
import io.jandy.domain.data.ExceptionObject;
import io.jandy.domain.data.MethodObject;
import io.jandy.domain.data.TreeNode;
import io.jandy.service.ProfService;
import io.jandy.util.sql.BatchUpdateQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static io.jandy.util.sql.Query.*;
import static io.jandy.util.sql.Query.select;
import static io.jandy.util.sql.Query.subQuery;
import static io.jandy.util.sql.conditional.Where.eq;
package io.jandy.service.impl;
/**
* Created by naver on 2017. 3. 20..
*/
@Service
@Profile("mysql")
public class ProfServiceForMySQL extends ProfService {
@Autowired
private JdbcTemplate jdbc;
@Transactional
protected void doUpdateTreeNodes0(List<TreeNode> treeNodes) {
Set<MethodObject> methodObjects = treeNodes.stream().map(TreeNode::getMethod).filter(Objects::nonNull).collect(Collectors.toSet());
Set<ClassObject> classObjects = treeNodes.stream().map(TreeNode::getMethod).filter(Objects::nonNull).map(MethodObject::getOwner).filter(Objects::nonNull).collect(Collectors.toSet());
List<ExceptionObject> exceptionObjects = treeNodes.stream().map(n -> n.getAcc() == null ? null : n.getAcc().getException()).filter(Objects::nonNull).collect(Collectors.toList());
if (classObjects.size() > 0) {
insert().ignore().into("prof_class")
.columns("name", "package_name")
.values(classObjects.stream().map(co -> new Object[] {co.getName(), co.getPackageName()}))
.execute(jdbc);
}
if (methodObjects.size() > 0) {
insert().ignore().into("prof_method")
.columns("name", "access", "descriptor", "owner_id")
.values(methodObjects.stream().map(mo -> new Object[]{
mo.getName(), mo.getAccess(), mo.getDescriptor(),
mo.getOwner() == null ? null : subQuery(
select().columns("id").from("prof_class").where( | eq("name", mo.getOwner().getName()).and(eq("package_name", mo.getOwner().getPackageName())) |
jandy-team/jandy | jandy-server/src/test/java/io/jandy/service/TravisRestServiceTest.java | // Path: jandy-server/src/main/java/io/jandy/domain/data/BuildInfo.java
// @Data
// @Accessors(chain = true)
// public class BuildInfo {
// private long buildId;
// private long buildNum;
// private String ownerName, repoName;
// private String branchName;
// private String lang;
// private int numSamples;
// }
//
// Path: jandy-server/src/main/java/io/jandy/domain/data/ProfilingContext.java
// @Data
// @Accessors(chain = true)
// public class ProfilingContext implements Serializable {
// private long profId;
// private List<ThreadObject> threadObjects;
//
// }
| import com.google.gson.Gson;
import io.jandy.domain.*;
import io.jandy.domain.data.BuildInfo;
import io.jandy.domain.data.ProfilingContext;
import io.jandy.domain.data.ProfilingInfo;
import io.jandy.domain.data.TreeNode;
import io.jandy.util.worker.JandyTask;
import io.jandy.util.worker.JandyWorker;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*; | package io.jandy.service;
/**
* @author JCooky
* @since 2016-11-19
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class TravisRestServiceTest {
@Autowired
private TravisRestService travisRestService;
@MockBean
private ProfContextDumpRepository profContextDumpRepository;
@MockBean
private ProjectRepository projectRepository;
@MockBean
private BranchRepository branchRepository;
@MockBean
private BuildRepository buildRepository;
@MockBean
private JandyWorker jandyWorker;
@MockBean
private SampleRepository sampleRepository;
| // Path: jandy-server/src/main/java/io/jandy/domain/data/BuildInfo.java
// @Data
// @Accessors(chain = true)
// public class BuildInfo {
// private long buildId;
// private long buildNum;
// private String ownerName, repoName;
// private String branchName;
// private String lang;
// private int numSamples;
// }
//
// Path: jandy-server/src/main/java/io/jandy/domain/data/ProfilingContext.java
// @Data
// @Accessors(chain = true)
// public class ProfilingContext implements Serializable {
// private long profId;
// private List<ThreadObject> threadObjects;
//
// }
// Path: jandy-server/src/test/java/io/jandy/service/TravisRestServiceTest.java
import com.google.gson.Gson;
import io.jandy.domain.*;
import io.jandy.domain.data.BuildInfo;
import io.jandy.domain.data.ProfilingContext;
import io.jandy.domain.data.ProfilingInfo;
import io.jandy.domain.data.TreeNode;
import io.jandy.util.worker.JandyTask;
import io.jandy.util.worker.JandyWorker;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
package io.jandy.service;
/**
* @author JCooky
* @since 2016-11-19
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class TravisRestServiceTest {
@Autowired
private TravisRestService travisRestService;
@MockBean
private ProfContextDumpRepository profContextDumpRepository;
@MockBean
private ProjectRepository projectRepository;
@MockBean
private BranchRepository branchRepository;
@MockBean
private BuildRepository buildRepository;
@MockBean
private JandyWorker jandyWorker;
@MockBean
private SampleRepository sampleRepository;
| private BuildInfo bi; |
jandy-team/jandy | jandy-server/src/test/java/io/jandy/service/TravisRestServiceTest.java | // Path: jandy-server/src/main/java/io/jandy/domain/data/BuildInfo.java
// @Data
// @Accessors(chain = true)
// public class BuildInfo {
// private long buildId;
// private long buildNum;
// private String ownerName, repoName;
// private String branchName;
// private String lang;
// private int numSamples;
// }
//
// Path: jandy-server/src/main/java/io/jandy/domain/data/ProfilingContext.java
// @Data
// @Accessors(chain = true)
// public class ProfilingContext implements Serializable {
// private long profId;
// private List<ThreadObject> threadObjects;
//
// }
| import com.google.gson.Gson;
import io.jandy.domain.*;
import io.jandy.domain.data.BuildInfo;
import io.jandy.domain.data.ProfilingContext;
import io.jandy.domain.data.ProfilingInfo;
import io.jandy.domain.data.TreeNode;
import io.jandy.util.worker.JandyTask;
import io.jandy.util.worker.JandyWorker;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*; | sample.getBuilds().add(build);
build.getSamples().add(sample);
ProfContextDump prof = new ProfContextDump();
prof.setId(5L);
prof.setBuild(build);
prof.setSample(sample);
prof.setState(ProfContextState.CREATED);
when(buildRepository.findByTravisBuildId(eq(profParams.getBuildId()))).thenReturn(build);
when(projectRepository.findByBuild(any(Build.class))).thenReturn(project);
// Sample sample = sampleRepository.findByNameAndProject_Id(profParams.getSampleName(), project.getId());
when(sampleRepository.save(any(Sample.class))).thenReturn(sample);
when(buildRepository.save(any(Build.class))).thenReturn(build);
when(profContextDumpRepository.save(any(ProfContextDump.class))).thenReturn(prof);
Map<String, ?> result = travisRestService.createProf(profParams);
assertEquals(result.get("profId"), prof.getId());
verify(buildRepository, times(1)).findByTravisBuildId(eq(profParams.getBuildId()));
verify(projectRepository, times(1)).findByBuild(refEq(build, "id"));
verify(sampleRepository, times(1)).save(refEq(sample));
verify(sampleRepository, times(1)).findByNameAndProject_Id(eq(profParams.getSampleName()), eq(profParams.getBuildId()));
verify(buildRepository, times(1)).save(refEq(build, "id"));
verify(profContextDumpRepository, times(1)).save(refEq(prof, "id"));
}
@Test
public void testSaveProf() throws Exception { | // Path: jandy-server/src/main/java/io/jandy/domain/data/BuildInfo.java
// @Data
// @Accessors(chain = true)
// public class BuildInfo {
// private long buildId;
// private long buildNum;
// private String ownerName, repoName;
// private String branchName;
// private String lang;
// private int numSamples;
// }
//
// Path: jandy-server/src/main/java/io/jandy/domain/data/ProfilingContext.java
// @Data
// @Accessors(chain = true)
// public class ProfilingContext implements Serializable {
// private long profId;
// private List<ThreadObject> threadObjects;
//
// }
// Path: jandy-server/src/test/java/io/jandy/service/TravisRestServiceTest.java
import com.google.gson.Gson;
import io.jandy.domain.*;
import io.jandy.domain.data.BuildInfo;
import io.jandy.domain.data.ProfilingContext;
import io.jandy.domain.data.ProfilingInfo;
import io.jandy.domain.data.TreeNode;
import io.jandy.util.worker.JandyTask;
import io.jandy.util.worker.JandyWorker;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
sample.getBuilds().add(build);
build.getSamples().add(sample);
ProfContextDump prof = new ProfContextDump();
prof.setId(5L);
prof.setBuild(build);
prof.setSample(sample);
prof.setState(ProfContextState.CREATED);
when(buildRepository.findByTravisBuildId(eq(profParams.getBuildId()))).thenReturn(build);
when(projectRepository.findByBuild(any(Build.class))).thenReturn(project);
// Sample sample = sampleRepository.findByNameAndProject_Id(profParams.getSampleName(), project.getId());
when(sampleRepository.save(any(Sample.class))).thenReturn(sample);
when(buildRepository.save(any(Build.class))).thenReturn(build);
when(profContextDumpRepository.save(any(ProfContextDump.class))).thenReturn(prof);
Map<String, ?> result = travisRestService.createProf(profParams);
assertEquals(result.get("profId"), prof.getId());
verify(buildRepository, times(1)).findByTravisBuildId(eq(profParams.getBuildId()));
verify(projectRepository, times(1)).findByBuild(refEq(build, "id"));
verify(sampleRepository, times(1)).save(refEq(sample));
verify(sampleRepository, times(1)).findByNameAndProject_Id(eq(profParams.getSampleName()), eq(profParams.getBuildId()));
verify(buildRepository, times(1)).save(refEq(build, "id"));
verify(profContextDumpRepository, times(1)).save(refEq(prof, "id"));
}
@Test
public void testSaveProf() throws Exception { | ProfilingContext profContext = new Gson().fromJson(IOUtils.toString(ClassLoader.getSystemResource("java-profiler-result/end.json")), ProfilingContext.class); |
jandy-team/jandy | jandy-server/src/main/java/io/jandy/util/api/GitHubApi.java | // Path: jandy-server/src/main/java/io/jandy/domain/cache/HttpCacheEntry.java
// public class HttpCacheEntry<T> implements Serializable {
// private String etag;
// private T body;
// private List<String> link;
//
// public String getEtag() {
// return etag;
// }
//
// public HttpCacheEntry setEtag(String etag) {
// this.etag = etag;
// return this;
// }
//
// public T getBody() {
// return body;
// }
//
// public HttpCacheEntry setBody(T body) {
// this.body = body;
// return this;
// }
//
//
// public void setLink(List<String> link) {
// this.link = link;
// }
//
// public List<String> getLink() {
// return link;
// }
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/api/json/GHOrg.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// @Data
// public class GHOrg implements Serializable {
// @JsonProperty("login")
// private String login;
//
// @JsonProperty("id")
// private Long id;
//
// @JsonProperty("public_repos")
// private Integer publicRepos;
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/api/json/GHRepo.java
// @Data
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class GHRepo implements Serializable {
// @JsonProperty("id")
// private Long id;
//
// @JsonProperty("owner")
// private GHUser owner;
//
// @JsonProperty("name")
// private String name;
//
// @JsonProperty("full_name")
// private String fullName;
//
// @JsonProperty("description")
// private String description;
//
// @JsonProperty("default_branch")
// private String defaultBranch;
//
// public Long getId() {
// return id;
// }
//
// public GHRepo setId(Long id) {
// this.id = id;
// return this;
// }
//
// public GHUser getOwner() {
// return owner;
// }
//
// public GHRepo setOwner(GHUser owner) {
// this.owner = owner;
// return this;
// }
//
// public String getName() {
// return name;
// }
//
// public GHRepo setName(String name) {
// this.name = name;
// return this;
// }
//
// public String getFullName() {
// return fullName;
// }
//
// public GHRepo setFullName(String fullName) {
// this.fullName = fullName;
// return this;
// }
//
// public String getDescription() {
// return description;
// }
//
// public GHRepo setDescription(String description) {
// this.description = description;
// return this;
// }
//
// public String getDefaultBranch() {
// return defaultBranch;
// }
//
// public GHRepo setDefaultBranch(String defaultBranch) {
// this.defaultBranch = defaultBranch;
// return this;
// }
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/api/json/GHUser.java
// @Data
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class GHUser implements Serializable {
// @JsonProperty("id")
// private long id;
//
// @JsonProperty("login")
// private String login;
//
// @JsonProperty("avatar_url")
// private String avatarUrl;
//
// @JsonProperty("public_repos")
// private Integer publicRepos;
//
// private String email;
// }
| import io.jandy.domain.cache.HttpCacheEntry;
import io.jandy.util.api.json.GHOrg;
import io.jandy.util.api.json.GHRepo;
import io.jandy.util.api.json.GHUser;
import io.jandy.util.CachedRestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.javatuples.KeyValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cache.CacheManager;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.stereotype.Component;
import org.springframework.web.client.*;
import java.net.URI;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | package io.jandy.util.api;
/**
* @author JCooky
* @since 2015-07-01
*/
@Component
public class GitHubApi {
private Logger logger = LoggerFactory.getLogger(GitHubApi.class);
@Autowired
private OAuth2ClientContext clientContext;
@Autowired
private CacheManager cacheManager;
private CachedRestTemplate restTemplate;
public GitHubApi(RestTemplateBuilder builder) {
this.restTemplate = builder
.build(CachedRestTemplate.class);
this.restTemplate.setAccept("application/vnd.github.v3+json");
}
public boolean isAnonymous() {
return clientContext.getAccessToken() == null;
}
| // Path: jandy-server/src/main/java/io/jandy/domain/cache/HttpCacheEntry.java
// public class HttpCacheEntry<T> implements Serializable {
// private String etag;
// private T body;
// private List<String> link;
//
// public String getEtag() {
// return etag;
// }
//
// public HttpCacheEntry setEtag(String etag) {
// this.etag = etag;
// return this;
// }
//
// public T getBody() {
// return body;
// }
//
// public HttpCacheEntry setBody(T body) {
// this.body = body;
// return this;
// }
//
//
// public void setLink(List<String> link) {
// this.link = link;
// }
//
// public List<String> getLink() {
// return link;
// }
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/api/json/GHOrg.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// @Data
// public class GHOrg implements Serializable {
// @JsonProperty("login")
// private String login;
//
// @JsonProperty("id")
// private Long id;
//
// @JsonProperty("public_repos")
// private Integer publicRepos;
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/api/json/GHRepo.java
// @Data
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class GHRepo implements Serializable {
// @JsonProperty("id")
// private Long id;
//
// @JsonProperty("owner")
// private GHUser owner;
//
// @JsonProperty("name")
// private String name;
//
// @JsonProperty("full_name")
// private String fullName;
//
// @JsonProperty("description")
// private String description;
//
// @JsonProperty("default_branch")
// private String defaultBranch;
//
// public Long getId() {
// return id;
// }
//
// public GHRepo setId(Long id) {
// this.id = id;
// return this;
// }
//
// public GHUser getOwner() {
// return owner;
// }
//
// public GHRepo setOwner(GHUser owner) {
// this.owner = owner;
// return this;
// }
//
// public String getName() {
// return name;
// }
//
// public GHRepo setName(String name) {
// this.name = name;
// return this;
// }
//
// public String getFullName() {
// return fullName;
// }
//
// public GHRepo setFullName(String fullName) {
// this.fullName = fullName;
// return this;
// }
//
// public String getDescription() {
// return description;
// }
//
// public GHRepo setDescription(String description) {
// this.description = description;
// return this;
// }
//
// public String getDefaultBranch() {
// return defaultBranch;
// }
//
// public GHRepo setDefaultBranch(String defaultBranch) {
// this.defaultBranch = defaultBranch;
// return this;
// }
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/api/json/GHUser.java
// @Data
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class GHUser implements Serializable {
// @JsonProperty("id")
// private long id;
//
// @JsonProperty("login")
// private String login;
//
// @JsonProperty("avatar_url")
// private String avatarUrl;
//
// @JsonProperty("public_repos")
// private Integer publicRepos;
//
// private String email;
// }
// Path: jandy-server/src/main/java/io/jandy/util/api/GitHubApi.java
import io.jandy.domain.cache.HttpCacheEntry;
import io.jandy.util.api.json.GHOrg;
import io.jandy.util.api.json.GHRepo;
import io.jandy.util.api.json.GHUser;
import io.jandy.util.CachedRestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.javatuples.KeyValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cache.CacheManager;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.stereotype.Component;
import org.springframework.web.client.*;
import java.net.URI;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package io.jandy.util.api;
/**
* @author JCooky
* @since 2015-07-01
*/
@Component
public class GitHubApi {
private Logger logger = LoggerFactory.getLogger(GitHubApi.class);
@Autowired
private OAuth2ClientContext clientContext;
@Autowired
private CacheManager cacheManager;
private CachedRestTemplate restTemplate;
public GitHubApi(RestTemplateBuilder builder) {
this.restTemplate = builder
.build(CachedRestTemplate.class);
this.restTemplate.setAccept("application/vnd.github.v3+json");
}
public boolean isAnonymous() {
return clientContext.getAccessToken() == null;
}
| public GHUser getUser() { |
jandy-team/jandy | jandy-server/src/main/java/io/jandy/util/api/GitHubApi.java | // Path: jandy-server/src/main/java/io/jandy/domain/cache/HttpCacheEntry.java
// public class HttpCacheEntry<T> implements Serializable {
// private String etag;
// private T body;
// private List<String> link;
//
// public String getEtag() {
// return etag;
// }
//
// public HttpCacheEntry setEtag(String etag) {
// this.etag = etag;
// return this;
// }
//
// public T getBody() {
// return body;
// }
//
// public HttpCacheEntry setBody(T body) {
// this.body = body;
// return this;
// }
//
//
// public void setLink(List<String> link) {
// this.link = link;
// }
//
// public List<String> getLink() {
// return link;
// }
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/api/json/GHOrg.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// @Data
// public class GHOrg implements Serializable {
// @JsonProperty("login")
// private String login;
//
// @JsonProperty("id")
// private Long id;
//
// @JsonProperty("public_repos")
// private Integer publicRepos;
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/api/json/GHRepo.java
// @Data
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class GHRepo implements Serializable {
// @JsonProperty("id")
// private Long id;
//
// @JsonProperty("owner")
// private GHUser owner;
//
// @JsonProperty("name")
// private String name;
//
// @JsonProperty("full_name")
// private String fullName;
//
// @JsonProperty("description")
// private String description;
//
// @JsonProperty("default_branch")
// private String defaultBranch;
//
// public Long getId() {
// return id;
// }
//
// public GHRepo setId(Long id) {
// this.id = id;
// return this;
// }
//
// public GHUser getOwner() {
// return owner;
// }
//
// public GHRepo setOwner(GHUser owner) {
// this.owner = owner;
// return this;
// }
//
// public String getName() {
// return name;
// }
//
// public GHRepo setName(String name) {
// this.name = name;
// return this;
// }
//
// public String getFullName() {
// return fullName;
// }
//
// public GHRepo setFullName(String fullName) {
// this.fullName = fullName;
// return this;
// }
//
// public String getDescription() {
// return description;
// }
//
// public GHRepo setDescription(String description) {
// this.description = description;
// return this;
// }
//
// public String getDefaultBranch() {
// return defaultBranch;
// }
//
// public GHRepo setDefaultBranch(String defaultBranch) {
// this.defaultBranch = defaultBranch;
// return this;
// }
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/api/json/GHUser.java
// @Data
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class GHUser implements Serializable {
// @JsonProperty("id")
// private long id;
//
// @JsonProperty("login")
// private String login;
//
// @JsonProperty("avatar_url")
// private String avatarUrl;
//
// @JsonProperty("public_repos")
// private Integer publicRepos;
//
// private String email;
// }
| import io.jandy.domain.cache.HttpCacheEntry;
import io.jandy.util.api.json.GHOrg;
import io.jandy.util.api.json.GHRepo;
import io.jandy.util.api.json.GHUser;
import io.jandy.util.CachedRestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.javatuples.KeyValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cache.CacheManager;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.stereotype.Component;
import org.springframework.web.client.*;
import java.net.URI;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | package io.jandy.util.api;
/**
* @author JCooky
* @since 2015-07-01
*/
@Component
public class GitHubApi {
private Logger logger = LoggerFactory.getLogger(GitHubApi.class);
@Autowired
private OAuth2ClientContext clientContext;
@Autowired
private CacheManager cacheManager;
private CachedRestTemplate restTemplate;
public GitHubApi(RestTemplateBuilder builder) {
this.restTemplate = builder
.build(CachedRestTemplate.class);
this.restTemplate.setAccept("application/vnd.github.v3+json");
}
public boolean isAnonymous() {
return clientContext.getAccessToken() == null;
}
public GHUser getUser() {
return getForObject("https://api.github.com/user", GHUser.class);
}
public GHUser getUser(String login) {
try {
return getForObject("https://api.github.com/users/{login}", GHUser.class, login);
} catch (HttpClientErrorException e) {
logger.error(e.getMessage(), e);
return null;
}
}
| // Path: jandy-server/src/main/java/io/jandy/domain/cache/HttpCacheEntry.java
// public class HttpCacheEntry<T> implements Serializable {
// private String etag;
// private T body;
// private List<String> link;
//
// public String getEtag() {
// return etag;
// }
//
// public HttpCacheEntry setEtag(String etag) {
// this.etag = etag;
// return this;
// }
//
// public T getBody() {
// return body;
// }
//
// public HttpCacheEntry setBody(T body) {
// this.body = body;
// return this;
// }
//
//
// public void setLink(List<String> link) {
// this.link = link;
// }
//
// public List<String> getLink() {
// return link;
// }
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/api/json/GHOrg.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// @Data
// public class GHOrg implements Serializable {
// @JsonProperty("login")
// private String login;
//
// @JsonProperty("id")
// private Long id;
//
// @JsonProperty("public_repos")
// private Integer publicRepos;
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/api/json/GHRepo.java
// @Data
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class GHRepo implements Serializable {
// @JsonProperty("id")
// private Long id;
//
// @JsonProperty("owner")
// private GHUser owner;
//
// @JsonProperty("name")
// private String name;
//
// @JsonProperty("full_name")
// private String fullName;
//
// @JsonProperty("description")
// private String description;
//
// @JsonProperty("default_branch")
// private String defaultBranch;
//
// public Long getId() {
// return id;
// }
//
// public GHRepo setId(Long id) {
// this.id = id;
// return this;
// }
//
// public GHUser getOwner() {
// return owner;
// }
//
// public GHRepo setOwner(GHUser owner) {
// this.owner = owner;
// return this;
// }
//
// public String getName() {
// return name;
// }
//
// public GHRepo setName(String name) {
// this.name = name;
// return this;
// }
//
// public String getFullName() {
// return fullName;
// }
//
// public GHRepo setFullName(String fullName) {
// this.fullName = fullName;
// return this;
// }
//
// public String getDescription() {
// return description;
// }
//
// public GHRepo setDescription(String description) {
// this.description = description;
// return this;
// }
//
// public String getDefaultBranch() {
// return defaultBranch;
// }
//
// public GHRepo setDefaultBranch(String defaultBranch) {
// this.defaultBranch = defaultBranch;
// return this;
// }
// }
//
// Path: jandy-server/src/main/java/io/jandy/util/api/json/GHUser.java
// @Data
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class GHUser implements Serializable {
// @JsonProperty("id")
// private long id;
//
// @JsonProperty("login")
// private String login;
//
// @JsonProperty("avatar_url")
// private String avatarUrl;
//
// @JsonProperty("public_repos")
// private Integer publicRepos;
//
// private String email;
// }
// Path: jandy-server/src/main/java/io/jandy/util/api/GitHubApi.java
import io.jandy.domain.cache.HttpCacheEntry;
import io.jandy.util.api.json.GHOrg;
import io.jandy.util.api.json.GHRepo;
import io.jandy.util.api.json.GHUser;
import io.jandy.util.CachedRestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.javatuples.KeyValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cache.CacheManager;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.stereotype.Component;
import org.springframework.web.client.*;
import java.net.URI;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package io.jandy.util.api;
/**
* @author JCooky
* @since 2015-07-01
*/
@Component
public class GitHubApi {
private Logger logger = LoggerFactory.getLogger(GitHubApi.class);
@Autowired
private OAuth2ClientContext clientContext;
@Autowired
private CacheManager cacheManager;
private CachedRestTemplate restTemplate;
public GitHubApi(RestTemplateBuilder builder) {
this.restTemplate = builder
.build(CachedRestTemplate.class);
this.restTemplate.setAccept("application/vnd.github.v3+json");
}
public boolean isAnonymous() {
return clientContext.getAccessToken() == null;
}
public GHUser getUser() {
return getForObject("https://api.github.com/user", GHUser.class);
}
public GHUser getUser(String login) {
try {
return getForObject("https://api.github.com/users/{login}", GHUser.class, login);
} catch (HttpClientErrorException e) {
logger.error(e.getMessage(), e);
return null;
}
}
| public List<GHOrg> getUserOrgs(String login) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.