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
|
---|---|---|---|---|---|---|
cjstehno/ersatz
|
ersatz/src/test/java/io/github/cjstehno/ersatz/encdec/ResponseEncodersTest.java
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/ResponseEncoders.java
// public class ResponseEncoders {
//
// private final List<EncoderMapping> encoders = new LinkedList<>();
//
// /**
// * Creates a response encoder container configured by the provided consumer.
// *
// * @param consumer the configuration consumer
// * @return the configured response encoders
// */
// public static ResponseEncoders encoders(final Consumer<ResponseEncoders> consumer) {
// final var encoders = new ResponseEncoders();
// consumer.accept(encoders);
// return encoders;
// }
//
// /**
// * Used to register an encoder for a content-type, part object type.
// *
// * @param contentType the part content-type
// * @param objectType the part object type
// * @param encoder the encoder function
// */
// public void register(final String contentType, final Class objectType, final Function<Object, byte[]> encoder) {
// encoders.add(new EncoderMapping(createMimeType(contentType), objectType, encoder));
// }
//
// /**
// * Used to register an encoder for a content-type, part object type.
// *
// * @param contentType the part content-type
// * @param objectType the part object type
// * @param encoder the encoder function
// */
// public void register(final ContentType contentType, final Class objectType, final Function<Object, byte[]> encoder) {
// register(contentType.getValue(), objectType, encoder);
// }
//
// /**
// * Used to find an encoder for the given content-type and object type.
// *
// * @param contentType the part content-type
// * @param objectType the part object type
// * @return the encoder function if one exists or null
// */
// public Function<Object, byte[]> findEncoder(final String contentType, final Class objectType) {
// final var mime = createMimeType(contentType);
//
// return encoders.stream()
// .filter(m -> m.contentType.match(mime) && m.objectType.isAssignableFrom(objectType))
// .findFirst()
// .map(m -> m.encoder)
// .orElse(null);
// }
//
// /**
// * Used to find an encoder for the given content-type and object type.
// * <p>
// * param contentType the part content-type
// *
// * @param contentType the response content type to be encoded
// * @param objectType the part object type
// * @return the encoder function if one exists or null
// */
// public Function<Object, byte[]> findEncoder(final ContentType contentType, final Class objectType) {
// return findEncoder(contentType.getValue(), objectType);
// }
//
// /**
// * Immutable mapping of a content-type and object type to an encoder.
// */
// private static class EncoderMapping {
//
// final MimeType contentType;
// final Class objectType;
// final Function<Object, byte[]> encoder;
//
// public EncoderMapping(MimeType contentType, Class objectType, Function<Object, byte[]> encoder) {
// this.contentType = contentType;
// this.objectType = objectType;
// this.encoder = encoder;
// }
// }
// }
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType IMAGE_GIF = new ContentType("image/gif");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType TEXT_PLAIN = new ContentType("text/plain");
|
import io.github.cjstehno.ersatz.encdec.ResponseEncoders;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.InputStream;
import java.util.function.Function;
import static io.github.cjstehno.ersatz.cfg.ContentType.IMAGE_GIF;
import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.encdec;
class ResponseEncodersTest {
private static final Function<Object, byte[]> ENCODER_A = o -> new byte[0];
private static final Function<Object, byte[]> ENCODER_B = o -> new byte[0];
@Test @DisplayName("encoders") void encoders() {
final var encoders = ResponseEncoders.encoders(e -> {
e.register("text/plain", String.class, ENCODER_A);
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/ResponseEncoders.java
// public class ResponseEncoders {
//
// private final List<EncoderMapping> encoders = new LinkedList<>();
//
// /**
// * Creates a response encoder container configured by the provided consumer.
// *
// * @param consumer the configuration consumer
// * @return the configured response encoders
// */
// public static ResponseEncoders encoders(final Consumer<ResponseEncoders> consumer) {
// final var encoders = new ResponseEncoders();
// consumer.accept(encoders);
// return encoders;
// }
//
// /**
// * Used to register an encoder for a content-type, part object type.
// *
// * @param contentType the part content-type
// * @param objectType the part object type
// * @param encoder the encoder function
// */
// public void register(final String contentType, final Class objectType, final Function<Object, byte[]> encoder) {
// encoders.add(new EncoderMapping(createMimeType(contentType), objectType, encoder));
// }
//
// /**
// * Used to register an encoder for a content-type, part object type.
// *
// * @param contentType the part content-type
// * @param objectType the part object type
// * @param encoder the encoder function
// */
// public void register(final ContentType contentType, final Class objectType, final Function<Object, byte[]> encoder) {
// register(contentType.getValue(), objectType, encoder);
// }
//
// /**
// * Used to find an encoder for the given content-type and object type.
// *
// * @param contentType the part content-type
// * @param objectType the part object type
// * @return the encoder function if one exists or null
// */
// public Function<Object, byte[]> findEncoder(final String contentType, final Class objectType) {
// final var mime = createMimeType(contentType);
//
// return encoders.stream()
// .filter(m -> m.contentType.match(mime) && m.objectType.isAssignableFrom(objectType))
// .findFirst()
// .map(m -> m.encoder)
// .orElse(null);
// }
//
// /**
// * Used to find an encoder for the given content-type and object type.
// * <p>
// * param contentType the part content-type
// *
// * @param contentType the response content type to be encoded
// * @param objectType the part object type
// * @return the encoder function if one exists or null
// */
// public Function<Object, byte[]> findEncoder(final ContentType contentType, final Class objectType) {
// return findEncoder(contentType.getValue(), objectType);
// }
//
// /**
// * Immutable mapping of a content-type and object type to an encoder.
// */
// private static class EncoderMapping {
//
// final MimeType contentType;
// final Class objectType;
// final Function<Object, byte[]> encoder;
//
// public EncoderMapping(MimeType contentType, Class objectType, Function<Object, byte[]> encoder) {
// this.contentType = contentType;
// this.objectType = objectType;
// this.encoder = encoder;
// }
// }
// }
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType IMAGE_GIF = new ContentType("image/gif");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType TEXT_PLAIN = new ContentType("text/plain");
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/encdec/ResponseEncodersTest.java
import io.github.cjstehno.ersatz.encdec.ResponseEncoders;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.InputStream;
import java.util.function.Function;
import static io.github.cjstehno.ersatz.cfg.ContentType.IMAGE_GIF;
import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.encdec;
class ResponseEncodersTest {
private static final Function<Object, byte[]> ENCODER_A = o -> new byte[0];
private static final Function<Object, byte[]> ENCODER_B = o -> new byte[0];
@Test @DisplayName("encoders") void encoders() {
final var encoders = ResponseEncoders.encoders(e -> {
e.register("text/plain", String.class, ENCODER_A);
|
e.register(IMAGE_GIF, InputStream.class, ENCODER_B);
|
cjstehno/ersatz
|
ersatz/src/test/java/io/github/cjstehno/ersatz/encdec/ResponseEncodersTest.java
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/ResponseEncoders.java
// public class ResponseEncoders {
//
// private final List<EncoderMapping> encoders = new LinkedList<>();
//
// /**
// * Creates a response encoder container configured by the provided consumer.
// *
// * @param consumer the configuration consumer
// * @return the configured response encoders
// */
// public static ResponseEncoders encoders(final Consumer<ResponseEncoders> consumer) {
// final var encoders = new ResponseEncoders();
// consumer.accept(encoders);
// return encoders;
// }
//
// /**
// * Used to register an encoder for a content-type, part object type.
// *
// * @param contentType the part content-type
// * @param objectType the part object type
// * @param encoder the encoder function
// */
// public void register(final String contentType, final Class objectType, final Function<Object, byte[]> encoder) {
// encoders.add(new EncoderMapping(createMimeType(contentType), objectType, encoder));
// }
//
// /**
// * Used to register an encoder for a content-type, part object type.
// *
// * @param contentType the part content-type
// * @param objectType the part object type
// * @param encoder the encoder function
// */
// public void register(final ContentType contentType, final Class objectType, final Function<Object, byte[]> encoder) {
// register(contentType.getValue(), objectType, encoder);
// }
//
// /**
// * Used to find an encoder for the given content-type and object type.
// *
// * @param contentType the part content-type
// * @param objectType the part object type
// * @return the encoder function if one exists or null
// */
// public Function<Object, byte[]> findEncoder(final String contentType, final Class objectType) {
// final var mime = createMimeType(contentType);
//
// return encoders.stream()
// .filter(m -> m.contentType.match(mime) && m.objectType.isAssignableFrom(objectType))
// .findFirst()
// .map(m -> m.encoder)
// .orElse(null);
// }
//
// /**
// * Used to find an encoder for the given content-type and object type.
// * <p>
// * param contentType the part content-type
// *
// * @param contentType the response content type to be encoded
// * @param objectType the part object type
// * @return the encoder function if one exists or null
// */
// public Function<Object, byte[]> findEncoder(final ContentType contentType, final Class objectType) {
// return findEncoder(contentType.getValue(), objectType);
// }
//
// /**
// * Immutable mapping of a content-type and object type to an encoder.
// */
// private static class EncoderMapping {
//
// final MimeType contentType;
// final Class objectType;
// final Function<Object, byte[]> encoder;
//
// public EncoderMapping(MimeType contentType, Class objectType, Function<Object, byte[]> encoder) {
// this.contentType = contentType;
// this.objectType = objectType;
// this.encoder = encoder;
// }
// }
// }
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType IMAGE_GIF = new ContentType("image/gif");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType TEXT_PLAIN = new ContentType("text/plain");
|
import io.github.cjstehno.ersatz.encdec.ResponseEncoders;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.InputStream;
import java.util.function.Function;
import static io.github.cjstehno.ersatz.cfg.ContentType.IMAGE_GIF;
import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.encdec;
class ResponseEncodersTest {
private static final Function<Object, byte[]> ENCODER_A = o -> new byte[0];
private static final Function<Object, byte[]> ENCODER_B = o -> new byte[0];
@Test @DisplayName("encoders") void encoders() {
final var encoders = ResponseEncoders.encoders(e -> {
e.register("text/plain", String.class, ENCODER_A);
e.register(IMAGE_GIF, InputStream.class, ENCODER_B);
});
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/ResponseEncoders.java
// public class ResponseEncoders {
//
// private final List<EncoderMapping> encoders = new LinkedList<>();
//
// /**
// * Creates a response encoder container configured by the provided consumer.
// *
// * @param consumer the configuration consumer
// * @return the configured response encoders
// */
// public static ResponseEncoders encoders(final Consumer<ResponseEncoders> consumer) {
// final var encoders = new ResponseEncoders();
// consumer.accept(encoders);
// return encoders;
// }
//
// /**
// * Used to register an encoder for a content-type, part object type.
// *
// * @param contentType the part content-type
// * @param objectType the part object type
// * @param encoder the encoder function
// */
// public void register(final String contentType, final Class objectType, final Function<Object, byte[]> encoder) {
// encoders.add(new EncoderMapping(createMimeType(contentType), objectType, encoder));
// }
//
// /**
// * Used to register an encoder for a content-type, part object type.
// *
// * @param contentType the part content-type
// * @param objectType the part object type
// * @param encoder the encoder function
// */
// public void register(final ContentType contentType, final Class objectType, final Function<Object, byte[]> encoder) {
// register(contentType.getValue(), objectType, encoder);
// }
//
// /**
// * Used to find an encoder for the given content-type and object type.
// *
// * @param contentType the part content-type
// * @param objectType the part object type
// * @return the encoder function if one exists or null
// */
// public Function<Object, byte[]> findEncoder(final String contentType, final Class objectType) {
// final var mime = createMimeType(contentType);
//
// return encoders.stream()
// .filter(m -> m.contentType.match(mime) && m.objectType.isAssignableFrom(objectType))
// .findFirst()
// .map(m -> m.encoder)
// .orElse(null);
// }
//
// /**
// * Used to find an encoder for the given content-type and object type.
// * <p>
// * param contentType the part content-type
// *
// * @param contentType the response content type to be encoded
// * @param objectType the part object type
// * @return the encoder function if one exists or null
// */
// public Function<Object, byte[]> findEncoder(final ContentType contentType, final Class objectType) {
// return findEncoder(contentType.getValue(), objectType);
// }
//
// /**
// * Immutable mapping of a content-type and object type to an encoder.
// */
// private static class EncoderMapping {
//
// final MimeType contentType;
// final Class objectType;
// final Function<Object, byte[]> encoder;
//
// public EncoderMapping(MimeType contentType, Class objectType, Function<Object, byte[]> encoder) {
// this.contentType = contentType;
// this.objectType = objectType;
// this.encoder = encoder;
// }
// }
// }
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType IMAGE_GIF = new ContentType("image/gif");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType TEXT_PLAIN = new ContentType("text/plain");
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/encdec/ResponseEncodersTest.java
import io.github.cjstehno.ersatz.encdec.ResponseEncoders;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.InputStream;
import java.util.function.Function;
import static io.github.cjstehno.ersatz.cfg.ContentType.IMAGE_GIF;
import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.encdec;
class ResponseEncodersTest {
private static final Function<Object, byte[]> ENCODER_A = o -> new byte[0];
private static final Function<Object, byte[]> ENCODER_B = o -> new byte[0];
@Test @DisplayName("encoders") void encoders() {
final var encoders = ResponseEncoders.encoders(e -> {
e.register("text/plain", String.class, ENCODER_A);
e.register(IMAGE_GIF, InputStream.class, ENCODER_B);
});
|
assertEquals(ENCODER_A, encoders.findEncoder(TEXT_PLAIN, String.class));
|
cjstehno/ersatz
|
ersatz-groovy/src/main/java/io/github/cjstehno/ersatz/encdec/EncDecExtensions.java
|
// Path: ersatz-groovy/src/main/java/space/jasan/support/groovy/closure/ConsumerWithDelegate.java
// @SuppressWarnings("javadoc")
// public class ConsumerWithDelegate<T> implements Consumer<T> {
//
// public static <T> Consumer<T> create(Closure c, Object owner, int strategy) {
// return new ConsumerWithDelegate<>(c, strategy, owner);
// }
//
// public static <T> Consumer<T> create(Closure c, Object owner) {
// return create(c, owner, Closure.DELEGATE_FIRST);
// }
//
// public static <T> Consumer<T> create(Closure c, int strategy) {
// return create(c, GroovyClosure.getPropagatedOwner(c.getOwner()), strategy);
// }
//
// public static <T> Consumer<T> create(Closure c) {
// return create(c, Closure.DELEGATE_FIRST);
// }
//
// private final int strategy;
// private final Object owner;
// private final Closure closure;
//
// private ConsumerWithDelegate(Closure closure, int strategy, Object owner) {
// this.strategy = strategy;
// this.owner = owner;
// this.closure = closure;
// }
//
// @Override
// public void accept(T t) {
// Closure closure = this.closure.rehydrate(t, owner, this.closure.getThisObject());
// closure.setResolveStrategy(strategy);
// closure.call(t);
// }
// }
|
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import io.github.cjstehno.ersatz.encdec.*;
import space.jasan.support.groovy.closure.ConsumerWithDelegate;
import static groovy.lang.Closure.DELEGATE_FIRST;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.encdec;
/**
* Groovy extensions for the encoder and decoder functionality.
*/
public class EncDecExtensions {
/**
* Used to configure a request cookie with a configuration closure.
*
* @param type the type of object being extended
* @param closure the configuration closure
* @return the configured cookie
*/
public static Cookie cookie(
final Cookie type,
@DelegatesTo(value = Cookie.class, strategy = DELEGATE_FIRST) final Closure closure
) {
|
// Path: ersatz-groovy/src/main/java/space/jasan/support/groovy/closure/ConsumerWithDelegate.java
// @SuppressWarnings("javadoc")
// public class ConsumerWithDelegate<T> implements Consumer<T> {
//
// public static <T> Consumer<T> create(Closure c, Object owner, int strategy) {
// return new ConsumerWithDelegate<>(c, strategy, owner);
// }
//
// public static <T> Consumer<T> create(Closure c, Object owner) {
// return create(c, owner, Closure.DELEGATE_FIRST);
// }
//
// public static <T> Consumer<T> create(Closure c, int strategy) {
// return create(c, GroovyClosure.getPropagatedOwner(c.getOwner()), strategy);
// }
//
// public static <T> Consumer<T> create(Closure c) {
// return create(c, Closure.DELEGATE_FIRST);
// }
//
// private final int strategy;
// private final Object owner;
// private final Closure closure;
//
// private ConsumerWithDelegate(Closure closure, int strategy, Object owner) {
// this.strategy = strategy;
// this.owner = owner;
// this.closure = closure;
// }
//
// @Override
// public void accept(T t) {
// Closure closure = this.closure.rehydrate(t, owner, this.closure.getThisObject());
// closure.setResolveStrategy(strategy);
// closure.call(t);
// }
// }
// Path: ersatz-groovy/src/main/java/io/github/cjstehno/ersatz/encdec/EncDecExtensions.java
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import io.github.cjstehno.ersatz.encdec.*;
import space.jasan.support.groovy.closure.ConsumerWithDelegate;
import static groovy.lang.Closure.DELEGATE_FIRST;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.encdec;
/**
* Groovy extensions for the encoder and decoder functionality.
*/
public class EncDecExtensions {
/**
* Used to configure a request cookie with a configuration closure.
*
* @param type the type of object being extended
* @param closure the configuration closure
* @return the configured cookie
*/
public static Cookie cookie(
final Cookie type,
@DelegatesTo(value = Cookie.class, strategy = DELEGATE_FIRST) final Closure closure
) {
|
return Cookie.cookie(ConsumerWithDelegate.create(closure));
|
cjstehno/ersatz
|
ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/AnyExpectations.java
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/match/ErsatzMatchers.java
// static Matcher<String> pathMatcher(final String path) {
// return path.equals("*") ? Matchers.any(String.class) : equalTo(path);
// }
|
import org.hamcrest.Matcher;
import java.util.function.Consumer;
import static io.github.cjstehno.ersatz.match.ErsatzMatchers.pathMatcher;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.cfg;
/**
* Defines the available generic request (ANY) expectations.
*/
public interface AnyExpectations {
/**
* Allows configuration of a request expectation matching any request method.
*
* @param path the expected request path
* @return a <code>Request</code> configuration object
*/
default Request ANY(String path) {
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/match/ErsatzMatchers.java
// static Matcher<String> pathMatcher(final String path) {
// return path.equals("*") ? Matchers.any(String.class) : equalTo(path);
// }
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/AnyExpectations.java
import org.hamcrest.Matcher;
import java.util.function.Consumer;
import static io.github.cjstehno.ersatz.match.ErsatzMatchers.pathMatcher;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.cfg;
/**
* Defines the available generic request (ANY) expectations.
*/
public interface AnyExpectations {
/**
* Allows configuration of a request expectation matching any request method.
*
* @param path the expected request path
* @return a <code>Request</code> configuration object
*/
default Request ANY(String path) {
|
return ANY(pathMatcher(path));
|
cjstehno/ersatz
|
ersatz/src/test/java/io/github/cjstehno/ersatz/encdec/MultipartRequestContentTest.java
|
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/TestAssertions.java
// static void verifyEqualityAndHashCode(final Object instanceA, final Object instanceB) {
// assertThat(instanceA, equalTo(instanceA));
// assertThat(instanceB, equalTo(instanceB));
// assertThat(instanceA, equalTo(instanceB));
// assertThat(instanceB, equalTo(instanceA));
// assertThat(instanceA, not(equalTo(null)));
// assertThat(instanceB, not(equalTo(null)));
// assertThat(instanceA.hashCode(), equalTo(instanceA.hashCode()));
// assertThat(instanceB.hashCode(), equalTo(instanceB.hashCode()));
// assertThat(instanceA.hashCode(), equalTo(instanceB.hashCode()));
// assertThat(instanceB.hashCode(), equalTo(instanceA.hashCode()));
// }
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType IMAGE_PNG = new ContentType("image/png");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType TEXT_PLAIN = new ContentType("text/plain");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/MultipartRequestContent.java
// public static MultipartRequestContent multipartRequest(final Consumer<MultipartRequestContent> config) {
// MultipartRequestContent request = new MultipartRequestContent();
// config.accept(request);
// return request;
// }
|
import lombok.val;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static io.github.cjstehno.ersatz.TestAssertions.verifyEqualityAndHashCode;
import static io.github.cjstehno.ersatz.cfg.ContentType.IMAGE_PNG;
import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN;
import static io.github.cjstehno.ersatz.encdec.MultipartRequestContent.multipartRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.encdec;
class MultipartRequestContentTest {
private static MultipartRequestContent multipartRequestContent() {
|
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/TestAssertions.java
// static void verifyEqualityAndHashCode(final Object instanceA, final Object instanceB) {
// assertThat(instanceA, equalTo(instanceA));
// assertThat(instanceB, equalTo(instanceB));
// assertThat(instanceA, equalTo(instanceB));
// assertThat(instanceB, equalTo(instanceA));
// assertThat(instanceA, not(equalTo(null)));
// assertThat(instanceB, not(equalTo(null)));
// assertThat(instanceA.hashCode(), equalTo(instanceA.hashCode()));
// assertThat(instanceB.hashCode(), equalTo(instanceB.hashCode()));
// assertThat(instanceA.hashCode(), equalTo(instanceB.hashCode()));
// assertThat(instanceB.hashCode(), equalTo(instanceA.hashCode()));
// }
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType IMAGE_PNG = new ContentType("image/png");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType TEXT_PLAIN = new ContentType("text/plain");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/MultipartRequestContent.java
// public static MultipartRequestContent multipartRequest(final Consumer<MultipartRequestContent> config) {
// MultipartRequestContent request = new MultipartRequestContent();
// config.accept(request);
// return request;
// }
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/encdec/MultipartRequestContentTest.java
import lombok.val;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static io.github.cjstehno.ersatz.TestAssertions.verifyEqualityAndHashCode;
import static io.github.cjstehno.ersatz.cfg.ContentType.IMAGE_PNG;
import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN;
import static io.github.cjstehno.ersatz.encdec.MultipartRequestContent.multipartRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.encdec;
class MultipartRequestContentTest {
private static MultipartRequestContent multipartRequestContent() {
|
return multipartRequest(mrc -> {
|
cjstehno/ersatz
|
ersatz/src/test/java/io/github/cjstehno/ersatz/encdec/MultipartRequestContentTest.java
|
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/TestAssertions.java
// static void verifyEqualityAndHashCode(final Object instanceA, final Object instanceB) {
// assertThat(instanceA, equalTo(instanceA));
// assertThat(instanceB, equalTo(instanceB));
// assertThat(instanceA, equalTo(instanceB));
// assertThat(instanceB, equalTo(instanceA));
// assertThat(instanceA, not(equalTo(null)));
// assertThat(instanceB, not(equalTo(null)));
// assertThat(instanceA.hashCode(), equalTo(instanceA.hashCode()));
// assertThat(instanceB.hashCode(), equalTo(instanceB.hashCode()));
// assertThat(instanceA.hashCode(), equalTo(instanceB.hashCode()));
// assertThat(instanceB.hashCode(), equalTo(instanceA.hashCode()));
// }
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType IMAGE_PNG = new ContentType("image/png");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType TEXT_PLAIN = new ContentType("text/plain");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/MultipartRequestContent.java
// public static MultipartRequestContent multipartRequest(final Consumer<MultipartRequestContent> config) {
// MultipartRequestContent request = new MultipartRequestContent();
// config.accept(request);
// return request;
// }
|
import lombok.val;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static io.github.cjstehno.ersatz.TestAssertions.verifyEqualityAndHashCode;
import static io.github.cjstehno.ersatz.cfg.ContentType.IMAGE_PNG;
import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN;
import static io.github.cjstehno.ersatz.encdec.MultipartRequestContent.multipartRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.encdec;
class MultipartRequestContentTest {
private static MultipartRequestContent multipartRequestContent() {
return multipartRequest(mrc -> {
mrc.part("alpha", "one");
mrc.part("bravo", "text/markdown", "this _is_ *rich^ text");
|
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/TestAssertions.java
// static void verifyEqualityAndHashCode(final Object instanceA, final Object instanceB) {
// assertThat(instanceA, equalTo(instanceA));
// assertThat(instanceB, equalTo(instanceB));
// assertThat(instanceA, equalTo(instanceB));
// assertThat(instanceB, equalTo(instanceA));
// assertThat(instanceA, not(equalTo(null)));
// assertThat(instanceB, not(equalTo(null)));
// assertThat(instanceA.hashCode(), equalTo(instanceA.hashCode()));
// assertThat(instanceB.hashCode(), equalTo(instanceB.hashCode()));
// assertThat(instanceA.hashCode(), equalTo(instanceB.hashCode()));
// assertThat(instanceB.hashCode(), equalTo(instanceA.hashCode()));
// }
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType IMAGE_PNG = new ContentType("image/png");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType TEXT_PLAIN = new ContentType("text/plain");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/MultipartRequestContent.java
// public static MultipartRequestContent multipartRequest(final Consumer<MultipartRequestContent> config) {
// MultipartRequestContent request = new MultipartRequestContent();
// config.accept(request);
// return request;
// }
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/encdec/MultipartRequestContentTest.java
import lombok.val;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static io.github.cjstehno.ersatz.TestAssertions.verifyEqualityAndHashCode;
import static io.github.cjstehno.ersatz.cfg.ContentType.IMAGE_PNG;
import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN;
import static io.github.cjstehno.ersatz.encdec.MultipartRequestContent.multipartRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.encdec;
class MultipartRequestContentTest {
private static MultipartRequestContent multipartRequestContent() {
return multipartRequest(mrc -> {
mrc.part("alpha", "one");
mrc.part("bravo", "text/markdown", "this _is_ *rich^ text");
|
mrc.part("charlie", IMAGE_PNG, new byte[]{8, 6, 7, 5, 3, 0, 9});
|
cjstehno/ersatz
|
ersatz/src/test/java/io/github/cjstehno/ersatz/encdec/MultipartRequestContentTest.java
|
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/TestAssertions.java
// static void verifyEqualityAndHashCode(final Object instanceA, final Object instanceB) {
// assertThat(instanceA, equalTo(instanceA));
// assertThat(instanceB, equalTo(instanceB));
// assertThat(instanceA, equalTo(instanceB));
// assertThat(instanceB, equalTo(instanceA));
// assertThat(instanceA, not(equalTo(null)));
// assertThat(instanceB, not(equalTo(null)));
// assertThat(instanceA.hashCode(), equalTo(instanceA.hashCode()));
// assertThat(instanceB.hashCode(), equalTo(instanceB.hashCode()));
// assertThat(instanceA.hashCode(), equalTo(instanceB.hashCode()));
// assertThat(instanceB.hashCode(), equalTo(instanceA.hashCode()));
// }
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType IMAGE_PNG = new ContentType("image/png");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType TEXT_PLAIN = new ContentType("text/plain");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/MultipartRequestContent.java
// public static MultipartRequestContent multipartRequest(final Consumer<MultipartRequestContent> config) {
// MultipartRequestContent request = new MultipartRequestContent();
// config.accept(request);
// return request;
// }
|
import lombok.val;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static io.github.cjstehno.ersatz.TestAssertions.verifyEqualityAndHashCode;
import static io.github.cjstehno.ersatz.cfg.ContentType.IMAGE_PNG;
import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN;
import static io.github.cjstehno.ersatz.encdec.MultipartRequestContent.multipartRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.encdec;
class MultipartRequestContentTest {
private static MultipartRequestContent multipartRequestContent() {
return multipartRequest(mrc -> {
mrc.part("alpha", "one");
mrc.part("bravo", "text/markdown", "this _is_ *rich^ text");
mrc.part("charlie", IMAGE_PNG, new byte[]{8, 6, 7, 5, 3, 0, 9});
mrc.part("delta", "delta.txt", "text/markdown", "this _is_ more text");
mrc.part("echo", "some.png", IMAGE_PNG, new byte[]{4, 2});
});
}
@Test @DisplayName("consumer configuration") void consumer() {
val content = multipartRequestContent();
|
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/TestAssertions.java
// static void verifyEqualityAndHashCode(final Object instanceA, final Object instanceB) {
// assertThat(instanceA, equalTo(instanceA));
// assertThat(instanceB, equalTo(instanceB));
// assertThat(instanceA, equalTo(instanceB));
// assertThat(instanceB, equalTo(instanceA));
// assertThat(instanceA, not(equalTo(null)));
// assertThat(instanceB, not(equalTo(null)));
// assertThat(instanceA.hashCode(), equalTo(instanceA.hashCode()));
// assertThat(instanceB.hashCode(), equalTo(instanceB.hashCode()));
// assertThat(instanceA.hashCode(), equalTo(instanceB.hashCode()));
// assertThat(instanceB.hashCode(), equalTo(instanceA.hashCode()));
// }
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType IMAGE_PNG = new ContentType("image/png");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType TEXT_PLAIN = new ContentType("text/plain");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/MultipartRequestContent.java
// public static MultipartRequestContent multipartRequest(final Consumer<MultipartRequestContent> config) {
// MultipartRequestContent request = new MultipartRequestContent();
// config.accept(request);
// return request;
// }
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/encdec/MultipartRequestContentTest.java
import lombok.val;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static io.github.cjstehno.ersatz.TestAssertions.verifyEqualityAndHashCode;
import static io.github.cjstehno.ersatz.cfg.ContentType.IMAGE_PNG;
import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN;
import static io.github.cjstehno.ersatz.encdec.MultipartRequestContent.multipartRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.encdec;
class MultipartRequestContentTest {
private static MultipartRequestContent multipartRequestContent() {
return multipartRequest(mrc -> {
mrc.part("alpha", "one");
mrc.part("bravo", "text/markdown", "this _is_ *rich^ text");
mrc.part("charlie", IMAGE_PNG, new byte[]{8, 6, 7, 5, 3, 0, 9});
mrc.part("delta", "delta.txt", "text/markdown", "this _is_ more text");
mrc.part("echo", "some.png", IMAGE_PNG, new byte[]{4, 2});
});
}
@Test @DisplayName("consumer configuration") void consumer() {
val content = multipartRequestContent();
|
assertEquals(new MultipartPart("alpha", null, TEXT_PLAIN.getValue(), null, "one"), content.getAt("alpha"));
|
cjstehno/ersatz
|
ersatz/src/test/java/io/github/cjstehno/ersatz/encdec/MultipartRequestContentTest.java
|
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/TestAssertions.java
// static void verifyEqualityAndHashCode(final Object instanceA, final Object instanceB) {
// assertThat(instanceA, equalTo(instanceA));
// assertThat(instanceB, equalTo(instanceB));
// assertThat(instanceA, equalTo(instanceB));
// assertThat(instanceB, equalTo(instanceA));
// assertThat(instanceA, not(equalTo(null)));
// assertThat(instanceB, not(equalTo(null)));
// assertThat(instanceA.hashCode(), equalTo(instanceA.hashCode()));
// assertThat(instanceB.hashCode(), equalTo(instanceB.hashCode()));
// assertThat(instanceA.hashCode(), equalTo(instanceB.hashCode()));
// assertThat(instanceB.hashCode(), equalTo(instanceA.hashCode()));
// }
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType IMAGE_PNG = new ContentType("image/png");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType TEXT_PLAIN = new ContentType("text/plain");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/MultipartRequestContent.java
// public static MultipartRequestContent multipartRequest(final Consumer<MultipartRequestContent> config) {
// MultipartRequestContent request = new MultipartRequestContent();
// config.accept(request);
// return request;
// }
|
import lombok.val;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static io.github.cjstehno.ersatz.TestAssertions.verifyEqualityAndHashCode;
import static io.github.cjstehno.ersatz.cfg.ContentType.IMAGE_PNG;
import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN;
import static io.github.cjstehno.ersatz.encdec.MultipartRequestContent.multipartRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.encdec;
class MultipartRequestContentTest {
private static MultipartRequestContent multipartRequestContent() {
return multipartRequest(mrc -> {
mrc.part("alpha", "one");
mrc.part("bravo", "text/markdown", "this _is_ *rich^ text");
mrc.part("charlie", IMAGE_PNG, new byte[]{8, 6, 7, 5, 3, 0, 9});
mrc.part("delta", "delta.txt", "text/markdown", "this _is_ more text");
mrc.part("echo", "some.png", IMAGE_PNG, new byte[]{4, 2});
});
}
@Test @DisplayName("consumer configuration") void consumer() {
val content = multipartRequestContent();
assertEquals(new MultipartPart("alpha", null, TEXT_PLAIN.getValue(), null, "one"), content.getAt("alpha"));
assertEquals(new MultipartPart("bravo", null, "text/markdown", null, "this _is_ *rich^ text"), content.getAt("bravo"));
assertEquals(new MultipartPart("charlie", null, IMAGE_PNG.getValue(), null, new byte[]{8, 6, 7, 5, 3, 0, 9}), content.getAt("charlie"));
assertEquals(new MultipartPart("delta", "delta.txt", "text/markdown", null, "this _is_ more text"), content.getAt("delta"));
assertEquals(new MultipartPart("echo", "some.png", IMAGE_PNG.getValue(), null, new byte[]{4, 2}), content.getAt("echo"));
}
@Test void equalsAndHash() {
|
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/TestAssertions.java
// static void verifyEqualityAndHashCode(final Object instanceA, final Object instanceB) {
// assertThat(instanceA, equalTo(instanceA));
// assertThat(instanceB, equalTo(instanceB));
// assertThat(instanceA, equalTo(instanceB));
// assertThat(instanceB, equalTo(instanceA));
// assertThat(instanceA, not(equalTo(null)));
// assertThat(instanceB, not(equalTo(null)));
// assertThat(instanceA.hashCode(), equalTo(instanceA.hashCode()));
// assertThat(instanceB.hashCode(), equalTo(instanceB.hashCode()));
// assertThat(instanceA.hashCode(), equalTo(instanceB.hashCode()));
// assertThat(instanceB.hashCode(), equalTo(instanceA.hashCode()));
// }
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType IMAGE_PNG = new ContentType("image/png");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType TEXT_PLAIN = new ContentType("text/plain");
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/MultipartRequestContent.java
// public static MultipartRequestContent multipartRequest(final Consumer<MultipartRequestContent> config) {
// MultipartRequestContent request = new MultipartRequestContent();
// config.accept(request);
// return request;
// }
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/encdec/MultipartRequestContentTest.java
import lombok.val;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static io.github.cjstehno.ersatz.TestAssertions.verifyEqualityAndHashCode;
import static io.github.cjstehno.ersatz.cfg.ContentType.IMAGE_PNG;
import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN;
import static io.github.cjstehno.ersatz.encdec.MultipartRequestContent.multipartRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.encdec;
class MultipartRequestContentTest {
private static MultipartRequestContent multipartRequestContent() {
return multipartRequest(mrc -> {
mrc.part("alpha", "one");
mrc.part("bravo", "text/markdown", "this _is_ *rich^ text");
mrc.part("charlie", IMAGE_PNG, new byte[]{8, 6, 7, 5, 3, 0, 9});
mrc.part("delta", "delta.txt", "text/markdown", "this _is_ more text");
mrc.part("echo", "some.png", IMAGE_PNG, new byte[]{4, 2});
});
}
@Test @DisplayName("consumer configuration") void consumer() {
val content = multipartRequestContent();
assertEquals(new MultipartPart("alpha", null, TEXT_PLAIN.getValue(), null, "one"), content.getAt("alpha"));
assertEquals(new MultipartPart("bravo", null, "text/markdown", null, "this _is_ *rich^ text"), content.getAt("bravo"));
assertEquals(new MultipartPart("charlie", null, IMAGE_PNG.getValue(), null, new byte[]{8, 6, 7, 5, 3, 0, 9}), content.getAt("charlie"));
assertEquals(new MultipartPart("delta", "delta.txt", "text/markdown", null, "this _is_ more text"), content.getAt("delta"));
assertEquals(new MultipartPart("echo", "some.png", IMAGE_PNG.getValue(), null, new byte[]{4, 2}), content.getAt("echo"));
}
@Test void equalsAndHash() {
|
verifyEqualityAndHashCode(multipartRequestContent(), multipartRequestContent());
|
cjstehno/ersatz
|
ersatz/src/test/java/io/github/cjstehno/ersatz/match/NoCookiesMatcherTest.java
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/match/NoCookiesMatcher.java
// public class NoCookiesMatcher extends BaseMatcher<Map<String, Cookie>> {
//
// /**
// * Provides a matcher which expects there to be no cookies.
// *
// * @return a matcher which expects there to be no cookies
// */
// public static NoCookiesMatcher noCookies() {
// return new NoCookiesMatcher();
// }
//
// @Override
// public boolean matches(final Object item) {
// if (!(item instanceof Map)) {
// return false;
// }
//
// return ((Map)item).isEmpty();
// }
//
// @Override
// public void describeTo(Description description) {
// description.appendText("Has no cookies.");
// }
// }
|
import io.github.cjstehno.ersatz.match.NoCookiesMatcher;
import lombok.val;
import org.hamcrest.StringDescription;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.match;
class NoCookiesMatcherTest {
@Test void noCookies(){
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/match/NoCookiesMatcher.java
// public class NoCookiesMatcher extends BaseMatcher<Map<String, Cookie>> {
//
// /**
// * Provides a matcher which expects there to be no cookies.
// *
// * @return a matcher which expects there to be no cookies
// */
// public static NoCookiesMatcher noCookies() {
// return new NoCookiesMatcher();
// }
//
// @Override
// public boolean matches(final Object item) {
// if (!(item instanceof Map)) {
// return false;
// }
//
// return ((Map)item).isEmpty();
// }
//
// @Override
// public void describeTo(Description description) {
// description.appendText("Has no cookies.");
// }
// }
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/match/NoCookiesMatcherTest.java
import io.github.cjstehno.ersatz.match.NoCookiesMatcher;
import lombok.val;
import org.hamcrest.StringDescription;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.match;
class NoCookiesMatcherTest {
@Test void noCookies(){
|
val matcher = NoCookiesMatcher.noCookies();
|
cjstehno/ersatz
|
ersatz/src/test/java/io/github/cjstehno/ersatz/encdec/MimeTypesTest.java
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/MimeTypes.java
// public interface MimeTypes {
//
// /**
// * Creates a <code>MimeType</code> object from the specified string designator. If a parsing exception is thrown, it
// * will be wrapped in an <code>IllegalArgumentException</code> and rethrown.
// *
// * @param value the mime-type text value
// * @return the wrapped MimeType
// */
// static MimeType createMimeType(final String value) {
// try {
// return new MimeType(value);
// } catch (MimeTypeParseException e) {
// throw new IllegalArgumentException(e.getMessage());
// }
// }
// }
|
import io.github.cjstehno.ersatz.encdec.MimeTypes;
import lombok.val;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.encdec;
class MimeTypesTest {
@Test @DisplayName("valid mime type")
void validMimeType() {
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/MimeTypes.java
// public interface MimeTypes {
//
// /**
// * Creates a <code>MimeType</code> object from the specified string designator. If a parsing exception is thrown, it
// * will be wrapped in an <code>IllegalArgumentException</code> and rethrown.
// *
// * @param value the mime-type text value
// * @return the wrapped MimeType
// */
// static MimeType createMimeType(final String value) {
// try {
// return new MimeType(value);
// } catch (MimeTypeParseException e) {
// throw new IllegalArgumentException(e.getMessage());
// }
// }
// }
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/encdec/MimeTypesTest.java
import io.github.cjstehno.ersatz.encdec.MimeTypes;
import lombok.val;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.encdec;
class MimeTypesTest {
@Test @DisplayName("valid mime type")
void validMimeType() {
|
val mt = MimeTypes.createMimeType("text/plain");
|
cjstehno/ersatz
|
ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/Decoders.java
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType TEXT_PLAIN = new ContentType("text/plain");
|
import static java.nio.charset.StandardCharsets.UTF_8;
import lombok.val;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.UploadContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.function.BiFunction;
import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN;
import static java.net.URLDecoder.decode;
|
@Override
public String getCharacterEncoding() {
return ctx.getCharacterEncoding();
}
@Override
public String getContentType() {
return ctx.getContentType();
}
@Override
public int getContentLength() {
return (int) ctx.getContentLength();
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(content);
}
});
} catch (final Exception e) {
throw new IllegalArgumentException(e.getMessage());
}
val multipartRequest = new MultipartRequestContent();
parts.forEach(part -> {
val partCtx = new DecodingContext(part.getSize(), part.getContentType(), null, ctx.getDecoderChain());
if (part.isFormField()) {
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/ContentType.java
// public static final ContentType TEXT_PLAIN = new ContentType("text/plain");
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/Decoders.java
import static java.nio.charset.StandardCharsets.UTF_8;
import lombok.val;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.UploadContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.function.BiFunction;
import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN;
import static java.net.URLDecoder.decode;
@Override
public String getCharacterEncoding() {
return ctx.getCharacterEncoding();
}
@Override
public String getContentType() {
return ctx.getContentType();
}
@Override
public int getContentLength() {
return (int) ctx.getContentLength();
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(content);
}
});
} catch (final Exception e) {
throw new IllegalArgumentException(e.getMessage());
}
val multipartRequest = new MultipartRequestContent();
parts.forEach(part -> {
val partCtx = new DecodingContext(part.getSize(), part.getContentType(), null, ctx.getDecoderChain());
if (part.isFormField()) {
|
multipartRequest.part(part.getFieldName(), TEXT_PLAIN, ctx.getDecoderChain().resolve(TEXT_PLAIN).apply(part.get(), partCtx));
|
cjstehno/ersatz
|
ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/HeadExpectations.java
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/match/ErsatzMatchers.java
// static Matcher<String> pathMatcher(final String path) {
// return path.equals("*") ? Matchers.any(String.class) : equalTo(path);
// }
|
import org.hamcrest.Matcher;
import java.util.function.Consumer;
import static io.github.cjstehno.ersatz.match.ErsatzMatchers.pathMatcher;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.cfg;
/**
* Defines the available HEAD request expectations.
*/
public interface HeadExpectations {
/**
* Allows configuration of a HEAD request expectation.
*
* @param path the expected request path.
* @return a <code>Request</code> configuration object
*/
default Request HEAD(String path) {
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/match/ErsatzMatchers.java
// static Matcher<String> pathMatcher(final String path) {
// return path.equals("*") ? Matchers.any(String.class) : equalTo(path);
// }
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/HeadExpectations.java
import org.hamcrest.Matcher;
import java.util.function.Consumer;
import static io.github.cjstehno.ersatz.match.ErsatzMatchers.pathMatcher;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.cfg;
/**
* Defines the available HEAD request expectations.
*/
public interface HeadExpectations {
/**
* Allows configuration of a HEAD request expectation.
*
* @param path the expected request path.
* @return a <code>Request</code> configuration object
*/
default Request HEAD(String path) {
|
return HEAD(pathMatcher(path));
|
cjstehno/ersatz
|
ersatz/src/test/java/io/github/cjstehno/ersatz/util/BasicAuthTest.java
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/util/BasicAuth.java
// public interface BasicAuth {
//
// /**
// * The authorization header name.
// */
// String AUTHORIZATION_HEADER = "Authorization";
//
// /**
// * Used to generate the Authorization header value for the given username and password.
// *
// * @param username the username (cannot contain a colon)
// * @param password the password (cannot contain a colon)
// * @return the generated header value
// */
// static String header(final String username, final String password) {
// check(username, password);
// return "Basic " + getEncoder().encodeToString((username + ":" + password).getBytes(UTF_8));
// }
//
// /**
// * Shortcut method for configuring BASIC authentication on a request expectation with the provided username and
// * password.
// *
// * @param request the request expectation
// * @param userame the username (cannot contain a colon)
// * @param password the password (cannot contain a colon)
// * @return the request passed in (to allow chaining)
// */
// static Request basicAuth(final Request request, final String userame, final String password) {
// return request.header(AUTHORIZATION_HEADER, header(userame, password));
// }
//
// private static void check(final String... values) {
// for (String value : values) {
// if (value.contains(":"))
// throw new IllegalArgumentException("The username and password cannot contain a colon!");
// }
// }
// }
|
import io.github.cjstehno.ersatz.util.BasicAuth;
import lombok.val;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.util;
class BasicAuthTest {
@Test void basicHeader() {
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/util/BasicAuth.java
// public interface BasicAuth {
//
// /**
// * The authorization header name.
// */
// String AUTHORIZATION_HEADER = "Authorization";
//
// /**
// * Used to generate the Authorization header value for the given username and password.
// *
// * @param username the username (cannot contain a colon)
// * @param password the password (cannot contain a colon)
// * @return the generated header value
// */
// static String header(final String username, final String password) {
// check(username, password);
// return "Basic " + getEncoder().encodeToString((username + ":" + password).getBytes(UTF_8));
// }
//
// /**
// * Shortcut method for configuring BASIC authentication on a request expectation with the provided username and
// * password.
// *
// * @param request the request expectation
// * @param userame the username (cannot contain a colon)
// * @param password the password (cannot contain a colon)
// * @return the request passed in (to allow chaining)
// */
// static Request basicAuth(final Request request, final String userame, final String password) {
// return request.header(AUTHORIZATION_HEADER, header(userame, password));
// }
//
// private static void check(final String... values) {
// for (String value : values) {
// if (value.contains(":"))
// throw new IllegalArgumentException("The username and password cannot contain a colon!");
// }
// }
// }
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/util/BasicAuthTest.java
import io.github.cjstehno.ersatz.util.BasicAuth;
import lombok.val;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.util;
class BasicAuthTest {
@Test void basicHeader() {
|
val header = BasicAuth.header("Aladdin", "open sesame");
|
cjstehno/ersatz
|
ersatz/src/test/java/io/github/cjstehno/ersatz/impl/PatchExpectationsTest.java
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/HttpMethod.java
// public enum HttpMethod {
//
// /**
// * Wildcard matching any HTTP method.
// */
// ANY("*"),
//
// /**
// * HTTP GET method matcher.
// */
// GET("GET"),
//
// /**
// * HTTP HEAD method matcher.
// */
// HEAD("HEAD"),
//
// /**
// * HTTP POST method matcher.
// */
// POST("POST"),
//
// /**
// * HTTP PUT method matcher.
// */
// PUT("PUT"),
//
// /**
// * HTTP DELETE method matcher.
// */
// DELETE("DELETE"),
//
// /**
// * HTTP PATCH method matcher.
// */
// PATCH("PATCH"),
//
// /**
// * HTTP OPTIONS method matcher.
// */
// OPTIONS("OPTIONS"),
//
// /**
// * HTTP TRACE method matcher.
// */
// TRACE("TRACE");
//
// private final String value;
//
// HttpMethod(final String value) {
// this.value = value;
// }
//
// /**
// * Retrieve the text value for the method.
// *
// * @return the method label.
// */
// public String getValue() {
// return value;
// }
//
// @Override public String toString() {
// return value;
// }
// }
|
import io.github.cjstehno.ersatz.cfg.HttpMethod;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.hamcrest.CoreMatchers.startsWith;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.impl;
class PatchExpectationsTest extends ExpectationHarness {
PatchExpectationsTest() {
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/HttpMethod.java
// public enum HttpMethod {
//
// /**
// * Wildcard matching any HTTP method.
// */
// ANY("*"),
//
// /**
// * HTTP GET method matcher.
// */
// GET("GET"),
//
// /**
// * HTTP HEAD method matcher.
// */
// HEAD("HEAD"),
//
// /**
// * HTTP POST method matcher.
// */
// POST("POST"),
//
// /**
// * HTTP PUT method matcher.
// */
// PUT("PUT"),
//
// /**
// * HTTP DELETE method matcher.
// */
// DELETE("DELETE"),
//
// /**
// * HTTP PATCH method matcher.
// */
// PATCH("PATCH"),
//
// /**
// * HTTP OPTIONS method matcher.
// */
// OPTIONS("OPTIONS"),
//
// /**
// * HTTP TRACE method matcher.
// */
// TRACE("TRACE");
//
// private final String value;
//
// HttpMethod(final String value) {
// this.value = value;
// }
//
// /**
// * Retrieve the text value for the method.
// *
// * @return the method label.
// */
// public String getValue() {
// return value;
// }
//
// @Override public String toString() {
// return value;
// }
// }
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/impl/PatchExpectationsTest.java
import io.github.cjstehno.ersatz.cfg.HttpMethod;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.hamcrest.CoreMatchers.startsWith;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.impl;
class PatchExpectationsTest extends ExpectationHarness {
PatchExpectationsTest() {
|
super(HttpMethod.PATCH);
|
cjstehno/ersatz
|
ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/GetExpectations.java
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/match/ErsatzMatchers.java
// static Matcher<String> pathMatcher(final String path) {
// return path.equals("*") ? Matchers.any(String.class) : equalTo(path);
// }
|
import org.hamcrest.Matcher;
import java.util.function.Consumer;
import static io.github.cjstehno.ersatz.match.ErsatzMatchers.pathMatcher;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.cfg;
/**
* Defines the available GET request expectations.
*/
public interface GetExpectations {
/**
* Allows configuration of a GET request expectation.
*
* @param path the expected request path
* @return a <code>Request</code> configuration object
*/
default Request GET(String path) {
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/match/ErsatzMatchers.java
// static Matcher<String> pathMatcher(final String path) {
// return path.equals("*") ? Matchers.any(String.class) : equalTo(path);
// }
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/GetExpectations.java
import org.hamcrest.Matcher;
import java.util.function.Consumer;
import static io.github.cjstehno.ersatz.match.ErsatzMatchers.pathMatcher;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.cfg;
/**
* Defines the available GET request expectations.
*/
public interface GetExpectations {
/**
* Allows configuration of a GET request expectation.
*
* @param path the expected request path
* @return a <code>Request</code> configuration object
*/
default Request GET(String path) {
|
return GET(pathMatcher(path));
|
cjstehno/ersatz
|
ersatz-groovy/src/main/java/io/github/cjstehno/ersatz/cfg/RequestResponseExtensions.java
|
// Path: ersatz-groovy/src/main/java/space/jasan/support/groovy/closure/ConsumerWithDelegate.java
// @SuppressWarnings("javadoc")
// public class ConsumerWithDelegate<T> implements Consumer<T> {
//
// public static <T> Consumer<T> create(Closure c, Object owner, int strategy) {
// return new ConsumerWithDelegate<>(c, strategy, owner);
// }
//
// public static <T> Consumer<T> create(Closure c, Object owner) {
// return create(c, owner, Closure.DELEGATE_FIRST);
// }
//
// public static <T> Consumer<T> create(Closure c, int strategy) {
// return create(c, GroovyClosure.getPropagatedOwner(c.getOwner()), strategy);
// }
//
// public static <T> Consumer<T> create(Closure c) {
// return create(c, Closure.DELEGATE_FIRST);
// }
//
// private final int strategy;
// private final Object owner;
// private final Closure closure;
//
// private ConsumerWithDelegate(Closure closure, int strategy, Object owner) {
// this.strategy = strategy;
// this.owner = owner;
// this.closure = closure;
// }
//
// @Override
// public void accept(T t) {
// Closure closure = this.closure.rehydrate(t, owner, this.closure.getThisObject());
// closure.setResolveStrategy(strategy);
// closure.call(t);
// }
// }
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/match/ErsatzMatchers.java
// static Matcher<String> pathMatcher(final String path) {
// return path.equals("*") ? Matchers.any(String.class) : equalTo(path);
// }
|
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import io.github.cjstehno.ersatz.cfg.*;
import org.hamcrest.Matcher;
import space.jasan.support.groovy.closure.ConsumerWithDelegate;
import static io.github.cjstehno.ersatz.match.ErsatzMatchers.pathMatcher;
import static groovy.lang.Closure.DELEGATE_FIRST;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.cfg;
/**
* Groovy extensions of the RequestResponse class to provide Groovy DSL enhancements.
*/
public class RequestResponseExtensions {
/**
* Allows for configuration of a <code>Response</code> by the given Groovy <code>Closure</code>, which will delegate to a <code>Response</code>
* instance passed into it for configuration using the Groovy DSL.
*
* @param self the type of object being extended
* @param closure the <code>Closure<Response></code> to provide configuration of the response
* @return a reference to this request
*/
public static Request responder(
final Request self,
@DelegatesTo(value = Response.class, strategy = DELEGATE_FIRST) final Closure closure
) {
|
// Path: ersatz-groovy/src/main/java/space/jasan/support/groovy/closure/ConsumerWithDelegate.java
// @SuppressWarnings("javadoc")
// public class ConsumerWithDelegate<T> implements Consumer<T> {
//
// public static <T> Consumer<T> create(Closure c, Object owner, int strategy) {
// return new ConsumerWithDelegate<>(c, strategy, owner);
// }
//
// public static <T> Consumer<T> create(Closure c, Object owner) {
// return create(c, owner, Closure.DELEGATE_FIRST);
// }
//
// public static <T> Consumer<T> create(Closure c, int strategy) {
// return create(c, GroovyClosure.getPropagatedOwner(c.getOwner()), strategy);
// }
//
// public static <T> Consumer<T> create(Closure c) {
// return create(c, Closure.DELEGATE_FIRST);
// }
//
// private final int strategy;
// private final Object owner;
// private final Closure closure;
//
// private ConsumerWithDelegate(Closure closure, int strategy, Object owner) {
// this.strategy = strategy;
// this.owner = owner;
// this.closure = closure;
// }
//
// @Override
// public void accept(T t) {
// Closure closure = this.closure.rehydrate(t, owner, this.closure.getThisObject());
// closure.setResolveStrategy(strategy);
// closure.call(t);
// }
// }
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/match/ErsatzMatchers.java
// static Matcher<String> pathMatcher(final String path) {
// return path.equals("*") ? Matchers.any(String.class) : equalTo(path);
// }
// Path: ersatz-groovy/src/main/java/io/github/cjstehno/ersatz/cfg/RequestResponseExtensions.java
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import io.github.cjstehno.ersatz.cfg.*;
import org.hamcrest.Matcher;
import space.jasan.support.groovy.closure.ConsumerWithDelegate;
import static io.github.cjstehno.ersatz.match.ErsatzMatchers.pathMatcher;
import static groovy.lang.Closure.DELEGATE_FIRST;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.cfg;
/**
* Groovy extensions of the RequestResponse class to provide Groovy DSL enhancements.
*/
public class RequestResponseExtensions {
/**
* Allows for configuration of a <code>Response</code> by the given Groovy <code>Closure</code>, which will delegate to a <code>Response</code>
* instance passed into it for configuration using the Groovy DSL.
*
* @param self the type of object being extended
* @param closure the <code>Closure<Response></code> to provide configuration of the response
* @return a reference to this request
*/
public static Request responder(
final Request self,
@DelegatesTo(value = Response.class, strategy = DELEGATE_FIRST) final Closure closure
) {
|
return self.responder(ConsumerWithDelegate.create(closure));
|
cjstehno/ersatz
|
ersatz-groovy/src/main/java/io/github/cjstehno/ersatz/cfg/RequestResponseExtensions.java
|
// Path: ersatz-groovy/src/main/java/space/jasan/support/groovy/closure/ConsumerWithDelegate.java
// @SuppressWarnings("javadoc")
// public class ConsumerWithDelegate<T> implements Consumer<T> {
//
// public static <T> Consumer<T> create(Closure c, Object owner, int strategy) {
// return new ConsumerWithDelegate<>(c, strategy, owner);
// }
//
// public static <T> Consumer<T> create(Closure c, Object owner) {
// return create(c, owner, Closure.DELEGATE_FIRST);
// }
//
// public static <T> Consumer<T> create(Closure c, int strategy) {
// return create(c, GroovyClosure.getPropagatedOwner(c.getOwner()), strategy);
// }
//
// public static <T> Consumer<T> create(Closure c) {
// return create(c, Closure.DELEGATE_FIRST);
// }
//
// private final int strategy;
// private final Object owner;
// private final Closure closure;
//
// private ConsumerWithDelegate(Closure closure, int strategy, Object owner) {
// this.strategy = strategy;
// this.owner = owner;
// this.closure = closure;
// }
//
// @Override
// public void accept(T t) {
// Closure closure = this.closure.rehydrate(t, owner, this.closure.getThisObject());
// closure.setResolveStrategy(strategy);
// closure.call(t);
// }
// }
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/match/ErsatzMatchers.java
// static Matcher<String> pathMatcher(final String path) {
// return path.equals("*") ? Matchers.any(String.class) : equalTo(path);
// }
|
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import io.github.cjstehno.ersatz.cfg.*;
import org.hamcrest.Matcher;
import space.jasan.support.groovy.closure.ConsumerWithDelegate;
import static io.github.cjstehno.ersatz.match.ErsatzMatchers.pathMatcher;
import static groovy.lang.Closure.DELEGATE_FIRST;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.cfg;
/**
* Groovy extensions of the RequestResponse class to provide Groovy DSL enhancements.
*/
public class RequestResponseExtensions {
/**
* Allows for configuration of a <code>Response</code> by the given Groovy <code>Closure</code>, which will delegate to a <code>Response</code>
* instance passed into it for configuration using the Groovy DSL.
*
* @param self the type of object being extended
* @param closure the <code>Closure<Response></code> to provide configuration of the response
* @return a reference to this request
*/
public static Request responder(
final Request self,
@DelegatesTo(value = Response.class, strategy = DELEGATE_FIRST) final Closure closure
) {
return self.responder(ConsumerWithDelegate.create(closure));
}
/**
* Allows for configuration of a chunked response using a Groovy <code>Closure</code>, which will delegate to a
* <code>ChunkingConfig</code> instance passed into it for configuration using the Groovy DSL.
*
* @param self the type of object being extended
* @param closure the <code>Closure</code> to provide configuration
* @return a reference to the configured response
*/
public static Response chunked(
final Response self,
@DelegatesTo(value = ChunkingConfig.class, strategy = DELEGATE_FIRST) Closure closure
) {
return self.chunked(ConsumerWithDelegate.create(closure));
}
/**
* Allows configuration of a request expectation matching any request method using the Groovy DSL.
*
* @param self the type of object being extended
* @param path the expected request path.
* @param closure the Groovy closure containing the configuration
* @return a <code>Request</code> configuration object
*/
public static Request ANY(
final AnyExpectations self,
String path,
@DelegatesTo(value = Request.class, strategy = DELEGATE_FIRST) Closure closure
) {
|
// Path: ersatz-groovy/src/main/java/space/jasan/support/groovy/closure/ConsumerWithDelegate.java
// @SuppressWarnings("javadoc")
// public class ConsumerWithDelegate<T> implements Consumer<T> {
//
// public static <T> Consumer<T> create(Closure c, Object owner, int strategy) {
// return new ConsumerWithDelegate<>(c, strategy, owner);
// }
//
// public static <T> Consumer<T> create(Closure c, Object owner) {
// return create(c, owner, Closure.DELEGATE_FIRST);
// }
//
// public static <T> Consumer<T> create(Closure c, int strategy) {
// return create(c, GroovyClosure.getPropagatedOwner(c.getOwner()), strategy);
// }
//
// public static <T> Consumer<T> create(Closure c) {
// return create(c, Closure.DELEGATE_FIRST);
// }
//
// private final int strategy;
// private final Object owner;
// private final Closure closure;
//
// private ConsumerWithDelegate(Closure closure, int strategy, Object owner) {
// this.strategy = strategy;
// this.owner = owner;
// this.closure = closure;
// }
//
// @Override
// public void accept(T t) {
// Closure closure = this.closure.rehydrate(t, owner, this.closure.getThisObject());
// closure.setResolveStrategy(strategy);
// closure.call(t);
// }
// }
//
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/match/ErsatzMatchers.java
// static Matcher<String> pathMatcher(final String path) {
// return path.equals("*") ? Matchers.any(String.class) : equalTo(path);
// }
// Path: ersatz-groovy/src/main/java/io/github/cjstehno/ersatz/cfg/RequestResponseExtensions.java
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import io.github.cjstehno.ersatz.cfg.*;
import org.hamcrest.Matcher;
import space.jasan.support.groovy.closure.ConsumerWithDelegate;
import static io.github.cjstehno.ersatz.match.ErsatzMatchers.pathMatcher;
import static groovy.lang.Closure.DELEGATE_FIRST;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.cfg;
/**
* Groovy extensions of the RequestResponse class to provide Groovy DSL enhancements.
*/
public class RequestResponseExtensions {
/**
* Allows for configuration of a <code>Response</code> by the given Groovy <code>Closure</code>, which will delegate to a <code>Response</code>
* instance passed into it for configuration using the Groovy DSL.
*
* @param self the type of object being extended
* @param closure the <code>Closure<Response></code> to provide configuration of the response
* @return a reference to this request
*/
public static Request responder(
final Request self,
@DelegatesTo(value = Response.class, strategy = DELEGATE_FIRST) final Closure closure
) {
return self.responder(ConsumerWithDelegate.create(closure));
}
/**
* Allows for configuration of a chunked response using a Groovy <code>Closure</code>, which will delegate to a
* <code>ChunkingConfig</code> instance passed into it for configuration using the Groovy DSL.
*
* @param self the type of object being extended
* @param closure the <code>Closure</code> to provide configuration
* @return a reference to the configured response
*/
public static Response chunked(
final Response self,
@DelegatesTo(value = ChunkingConfig.class, strategy = DELEGATE_FIRST) Closure closure
) {
return self.chunked(ConsumerWithDelegate.create(closure));
}
/**
* Allows configuration of a request expectation matching any request method using the Groovy DSL.
*
* @param self the type of object being extended
* @param path the expected request path.
* @param closure the Groovy closure containing the configuration
* @return a <code>Request</code> configuration object
*/
public static Request ANY(
final AnyExpectations self,
String path,
@DelegatesTo(value = Request.class, strategy = DELEGATE_FIRST) Closure closure
) {
|
return self.ANY(pathMatcher(path), ConsumerWithDelegate.create(closure));
|
cjstehno/ersatz
|
ersatz/src/test/java/io/github/cjstehno/ersatz/util/TimeoutTest.java
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/util/Timeout.java
// static boolean isTrueBefore(final Supplier<Boolean> condition, final long timeout, final TimeUnit unit) {
// val started = currentTimeMillis();
// val timeoutMs = unit.toMillis(timeout);
//
// if (!condition.get()) {
// val executor = newSingleThreadScheduledExecutor();
// try {
// var future = executor.schedule(condition::get, 250, MILLISECONDS);
//
// while (!future.get(timeout, unit) && !timedOut(started, timeoutMs)) {
// future = executor.schedule(condition::get, 250, MILLISECONDS);
// }
//
// return !timedOut(started, timeoutMs);
//
// } catch (final Exception e) {
// return false;
// } finally {
// executor.shutdown();
// }
//
// } else {
// return true;
// }
// }
|
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import static io.github.cjstehno.ersatz.util.Timeout.isTrueBefore;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.util;
class TimeoutTest {
private AtomicBoolean state;
private ScheduledExecutorService executor;
@BeforeEach void beforeEach() {
state = new AtomicBoolean(false);
executor = Executors.newSingleThreadScheduledExecutor();
}
@AfterEach void afterEach() {
executor.shutdown();
}
@Test @DisplayName("when ready immediately")
void readyImmediately() {
changeStateIn(0);
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/util/Timeout.java
// static boolean isTrueBefore(final Supplier<Boolean> condition, final long timeout, final TimeUnit unit) {
// val started = currentTimeMillis();
// val timeoutMs = unit.toMillis(timeout);
//
// if (!condition.get()) {
// val executor = newSingleThreadScheduledExecutor();
// try {
// var future = executor.schedule(condition::get, 250, MILLISECONDS);
//
// while (!future.get(timeout, unit) && !timedOut(started, timeoutMs)) {
// future = executor.schedule(condition::get, 250, MILLISECONDS);
// }
//
// return !timedOut(started, timeoutMs);
//
// } catch (final Exception e) {
// return false;
// } finally {
// executor.shutdown();
// }
//
// } else {
// return true;
// }
// }
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/util/TimeoutTest.java
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import static io.github.cjstehno.ersatz.util.Timeout.isTrueBefore;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.util;
class TimeoutTest {
private AtomicBoolean state;
private ScheduledExecutorService executor;
@BeforeEach void beforeEach() {
state = new AtomicBoolean(false);
executor = Executors.newSingleThreadScheduledExecutor();
}
@AfterEach void afterEach() {
executor.shutdown();
}
@Test @DisplayName("when ready immediately")
void readyImmediately() {
changeStateIn(0);
|
assertTrue(isTrueBefore(() -> state.get(), 1, SECONDS));
|
cjstehno/ersatz
|
ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/RequestWithContent.java
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/DecodingContext.java
// @RequiredArgsConstructor @Getter
// public class DecodingContext {
//
// private final long contentLength;
// private final String contentType;
// private final String characterEncoding;
// private final DecoderChain decoderChain;
// }
|
import io.github.cjstehno.ersatz.encdec.DecodingContext;
import org.hamcrest.Matcher;
import java.util.function.BiFunction;
import static org.hamcrest.Matchers.equalTo;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.cfg;
/**
* Expectation configuration for a request with body content.
*/
public interface RequestWithContent extends Request {
/**
* Configures the expected body content of the request with the specified content type.
*
* @param body the body content
* @param contentType the body content type
* @return a reference to this request
*/
default RequestWithContent body(final Object body, String contentType) {
return body(body instanceof Matcher ? (Matcher<Object>) body : equalTo(body), contentType);
}
/**
* Configures the expected body content of the request with the specified content type.
*
* @param body the body content matcher
* @param contentType the body content type
* @return a reference to this request
*/
RequestWithContent body(final Matcher<Object> body, String contentType);
/**
* Configures the expected body content of the request with the specified content type.
*
* @param body the body content
* @param contentType the body content type
* @return a reference to this request
*/
default RequestWithContent body(final Object body, ContentType contentType) {
return body(body, contentType.getValue());
}
/**
* Configures the expected body content of the request with the specified content type.
*
* @param body the body content matcher
* @param contentType the body content type
* @return a reference to this request
*/
default RequestWithContent body(final Matcher<Object> body, ContentType contentType) {
return body(body, contentType.getValue());
}
/**
* Specifies a custom body content converter function. The function will have the client request body content as a byte array and it will be
* converted into the specified output type. Generally the conversion is used when comparing the client request with the configured request
* body expectation.
*
* @param contentType the content type that the convert will handle
* @param decoder the conversion function
* @return a reference to this request
*/
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/encdec/DecodingContext.java
// @RequiredArgsConstructor @Getter
// public class DecodingContext {
//
// private final long contentLength;
// private final String contentType;
// private final String characterEncoding;
// private final DecoderChain decoderChain;
// }
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/RequestWithContent.java
import io.github.cjstehno.ersatz.encdec.DecodingContext;
import org.hamcrest.Matcher;
import java.util.function.BiFunction;
import static org.hamcrest.Matchers.equalTo;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.cfg;
/**
* Expectation configuration for a request with body content.
*/
public interface RequestWithContent extends Request {
/**
* Configures the expected body content of the request with the specified content type.
*
* @param body the body content
* @param contentType the body content type
* @return a reference to this request
*/
default RequestWithContent body(final Object body, String contentType) {
return body(body instanceof Matcher ? (Matcher<Object>) body : equalTo(body), contentType);
}
/**
* Configures the expected body content of the request with the specified content type.
*
* @param body the body content matcher
* @param contentType the body content type
* @return a reference to this request
*/
RequestWithContent body(final Matcher<Object> body, String contentType);
/**
* Configures the expected body content of the request with the specified content type.
*
* @param body the body content
* @param contentType the body content type
* @return a reference to this request
*/
default RequestWithContent body(final Object body, ContentType contentType) {
return body(body, contentType.getValue());
}
/**
* Configures the expected body content of the request with the specified content type.
*
* @param body the body content matcher
* @param contentType the body content type
* @return a reference to this request
*/
default RequestWithContent body(final Matcher<Object> body, ContentType contentType) {
return body(body, contentType.getValue());
}
/**
* Specifies a custom body content converter function. The function will have the client request body content as a byte array and it will be
* converted into the specified output type. Generally the conversion is used when comparing the client request with the configured request
* body expectation.
*
* @param contentType the content type that the convert will handle
* @param decoder the conversion function
* @return a reference to this request
*/
|
RequestWithContent decoder(final String contentType, final BiFunction<byte[], DecodingContext, Object> decoder);
|
cjstehno/ersatz
|
ersatz/src/test/java/io/github/cjstehno/ersatz/impl/HeadExpectationsTest.java
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/HttpMethod.java
// public enum HttpMethod {
//
// /**
// * Wildcard matching any HTTP method.
// */
// ANY("*"),
//
// /**
// * HTTP GET method matcher.
// */
// GET("GET"),
//
// /**
// * HTTP HEAD method matcher.
// */
// HEAD("HEAD"),
//
// /**
// * HTTP POST method matcher.
// */
// POST("POST"),
//
// /**
// * HTTP PUT method matcher.
// */
// PUT("PUT"),
//
// /**
// * HTTP DELETE method matcher.
// */
// DELETE("DELETE"),
//
// /**
// * HTTP PATCH method matcher.
// */
// PATCH("PATCH"),
//
// /**
// * HTTP OPTIONS method matcher.
// */
// OPTIONS("OPTIONS"),
//
// /**
// * HTTP TRACE method matcher.
// */
// TRACE("TRACE");
//
// private final String value;
//
// HttpMethod(final String value) {
// this.value = value;
// }
//
// /**
// * Retrieve the text value for the method.
// *
// * @return the method label.
// */
// public String getValue() {
// return value;
// }
//
// @Override public String toString() {
// return value;
// }
// }
|
import io.github.cjstehno.ersatz.cfg.HttpMethod;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.hamcrest.CoreMatchers.startsWith;
|
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.impl;
public class HeadExpectationsTest extends ExpectationHarness {
HeadExpectationsTest() {
|
// Path: ersatz/src/main/java/io/github/cjstehno/ersatz/cfg/HttpMethod.java
// public enum HttpMethod {
//
// /**
// * Wildcard matching any HTTP method.
// */
// ANY("*"),
//
// /**
// * HTTP GET method matcher.
// */
// GET("GET"),
//
// /**
// * HTTP HEAD method matcher.
// */
// HEAD("HEAD"),
//
// /**
// * HTTP POST method matcher.
// */
// POST("POST"),
//
// /**
// * HTTP PUT method matcher.
// */
// PUT("PUT"),
//
// /**
// * HTTP DELETE method matcher.
// */
// DELETE("DELETE"),
//
// /**
// * HTTP PATCH method matcher.
// */
// PATCH("PATCH"),
//
// /**
// * HTTP OPTIONS method matcher.
// */
// OPTIONS("OPTIONS"),
//
// /**
// * HTTP TRACE method matcher.
// */
// TRACE("TRACE");
//
// private final String value;
//
// HttpMethod(final String value) {
// this.value = value;
// }
//
// /**
// * Retrieve the text value for the method.
// *
// * @return the method label.
// */
// public String getValue() {
// return value;
// }
//
// @Override public String toString() {
// return value;
// }
// }
// Path: ersatz/src/test/java/io/github/cjstehno/ersatz/impl/HeadExpectationsTest.java
import io.github.cjstehno.ersatz.cfg.HttpMethod;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.hamcrest.CoreMatchers.startsWith;
/**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.impl;
public class HeadExpectationsTest extends ExpectationHarness {
HeadExpectationsTest() {
|
super(HttpMethod.HEAD);
|
kstenschke/shifter-plugin
|
src/com/kstenschke/shifter/models/ShiftableTypesManager.java
|
// Path: src/com/kstenschke/shifter/utils/UtilsFile.java
// public class UtilsFile {
//
// public static String extractFileExtension(@Nullable String filename) {
// return extractFileExtension(filename, false);
// }
//
// /**
// * @param filename Filename from which to extract the extension
// * @param toLowerCase Convert extension to lower case?
// * @return The extension Everything after the last "." in the full filename
// */
// public static String extractFileExtension(@Nullable String filename, boolean toLowerCase) {
// if (null == filename ||
// filename.isEmpty() ||
// filename.length() < 3 ||
// !filename.contains(".")
// ) {
// return "";
// }
// filename = getBasename(filename);
// if ("".equals(filename)) {
// return filename;
// }
//
// return toLowerCase
// ? filename.substring(filename.lastIndexOf('.') + 1).toLowerCase()
// : filename.substring(filename.lastIndexOf('.') + 1);
// }
//
// private static String getBasename(@Nullable String filename) {
// if (null == filename) {
// return "";
// }
// if (filename.contains("/")) {
// filename = filename.substring(filename.lastIndexOf("/") + 1);
// }
// if (filename.contains("\\")) {
// filename = filename.substring(filename.lastIndexOf("\\") + 1);
// }
// return filename;
// }
//
// private static boolean filenameEndsWithExtension(@Nullable String filename) {
// filename = getBasename(filename);
// if (null == filename || filename.isEmpty() || !filename.contains(".")) {
// return false;
// }
//
// String[] parts = filename.split("\\.");
//
// return parts.length > 1 && parts[0].length() > 0 && parts[1].length() >= 2;
// }
//
// public static boolean isPhpFile(@Nullable String filename) {
// filename = getBasename(filename).toLowerCase();
// return filenameEndsWithExtension(filename) && extractFileExtension(filename).matches("(php|phtml)");
// }
//
// public static boolean isCssFile(@Nullable String filename) {
// filename = getBasename(filename).toLowerCase();
// return filenameEndsWithExtension(filename) && extractFileExtension(filename).matches("(css|scss|sass|less|styl)");
// }
//
// public static boolean isJavaScriptFile(@Nullable String filename, boolean allowTypeScript) {
// filename = getBasename(filename).toLowerCase();
// if (!filenameEndsWithExtension(filename)) {
// return false;
// }
//
// return extractFileExtension(filename).matches(allowTypeScript ? "(js|ts)" : "(js)");
// }
//
// /**
// * @param is Input stream
// * @return String Full contents of given stream as string
// */
// public static String getFileStreamAsString(java.io.InputStream is) {
// java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
//
// return s.hasNext() ? s.next() : "";
// }
// }
//
// Path: src/com/kstenschke/shifter/models/ShiftableSelection.java
// static final String ACTION_TEXT_SHIFT_SELECTION = "Shift Selection";
//
// Path: src/com/kstenschke/shifter/models/ShiftableTypes.java
// public enum Type {
// UNKNOWN,
//
// // Dictionaric types
// ACCESS_TYPE,
// DICTIONARY_WORD_EXT_SPECIFIC,
// DICTIONARY_WORD_GLOBAL,
//
// // Numeric types
// NUMERIC_VALUE,
// NUMERIC_POSTFIXED,
// ROMAN_NUMERAL,
//
// // Generic shiftable types
// QUOTED_STRING,
// PARENTHESIS,
// HTML_ENCODABLE,
// CAMEL_CASED,
// SEPARATED_PATH,
// WORDS_TUPEL,
//
// // Operators (<, >, +, -, etc.) and expressions
// OPERATOR_SIGN,
// LOGICAL_OPERATOR,
// MONO_CHARACTER,
// TERNARY_EXPRESSION,
//
// RGB_COLOR,
//
// // CSS unit (%, cm, em, in, pt, px, rem, vw, vh, vmin, vmax)
// CSS_UNIT,
//
// // DOC comment related
// DOC_COMMENT_TAG,
// DOC_COMMENT_DATA_TYPE,
//
// // PHP specific
// PHP_VARIABLE_OR_ARRAY,
//
// // JavaScript specific
// JS_VARIABLES_DECLARATIONS,
// SIZZLE_SELECTOR,
// JQUERY_OBSERVER,
//
// TRAILING_COMMENT
// }
|
import com.kstenschke.shifter.models.shiftable_types.*;
import com.kstenschke.shifter.utils.UtilsFile;
import org.jetbrains.annotations.Nullable;
import static com.kstenschke.shifter.models.ShiftableSelection.ACTION_TEXT_SHIFT_SELECTION;
import static com.kstenschke.shifter.models.ShiftableTypes.Type.*;
|
if (JsVariablesDeclarations.isJsVariables(word)) {
return JS_VARIABLES_DECLARATIONS;
}
if (SizzleSelector.isSelector(word)) {
return SIZZLE_SELECTOR;
}
// DocComment shiftable_types (must be prefixed w/ "@")
typeDataTypeInDocComment = new DocCommentType();
if (DocCommentType.isDocCommentTypeLineContext(actionContainer.caretLine)) {
typeTagInDocComment = new DocCommentTag();
if (prefixChar.matches("@")
&& typeTagInDocComment.isDocCommentTag(prefixChar, actionContainer.caretLine)
) {
return DOC_COMMENT_TAG;
}
if (typeDataTypeInDocComment.isDocCommentType(prefixChar, actionContainer.caretLine)) {
return DOC_COMMENT_DATA_TYPE;
}
}
// Object visibility
accessType = new AccessType();
if (!"@".equals(prefixChar) && accessType.isAccessType(word)) {
return ACCESS_TYPE;
}
// File extension specific term in dictionary
typeDictionaryTerm = new DictionaryTerm();
|
// Path: src/com/kstenschke/shifter/utils/UtilsFile.java
// public class UtilsFile {
//
// public static String extractFileExtension(@Nullable String filename) {
// return extractFileExtension(filename, false);
// }
//
// /**
// * @param filename Filename from which to extract the extension
// * @param toLowerCase Convert extension to lower case?
// * @return The extension Everything after the last "." in the full filename
// */
// public static String extractFileExtension(@Nullable String filename, boolean toLowerCase) {
// if (null == filename ||
// filename.isEmpty() ||
// filename.length() < 3 ||
// !filename.contains(".")
// ) {
// return "";
// }
// filename = getBasename(filename);
// if ("".equals(filename)) {
// return filename;
// }
//
// return toLowerCase
// ? filename.substring(filename.lastIndexOf('.') + 1).toLowerCase()
// : filename.substring(filename.lastIndexOf('.') + 1);
// }
//
// private static String getBasename(@Nullable String filename) {
// if (null == filename) {
// return "";
// }
// if (filename.contains("/")) {
// filename = filename.substring(filename.lastIndexOf("/") + 1);
// }
// if (filename.contains("\\")) {
// filename = filename.substring(filename.lastIndexOf("\\") + 1);
// }
// return filename;
// }
//
// private static boolean filenameEndsWithExtension(@Nullable String filename) {
// filename = getBasename(filename);
// if (null == filename || filename.isEmpty() || !filename.contains(".")) {
// return false;
// }
//
// String[] parts = filename.split("\\.");
//
// return parts.length > 1 && parts[0].length() > 0 && parts[1].length() >= 2;
// }
//
// public static boolean isPhpFile(@Nullable String filename) {
// filename = getBasename(filename).toLowerCase();
// return filenameEndsWithExtension(filename) && extractFileExtension(filename).matches("(php|phtml)");
// }
//
// public static boolean isCssFile(@Nullable String filename) {
// filename = getBasename(filename).toLowerCase();
// return filenameEndsWithExtension(filename) && extractFileExtension(filename).matches("(css|scss|sass|less|styl)");
// }
//
// public static boolean isJavaScriptFile(@Nullable String filename, boolean allowTypeScript) {
// filename = getBasename(filename).toLowerCase();
// if (!filenameEndsWithExtension(filename)) {
// return false;
// }
//
// return extractFileExtension(filename).matches(allowTypeScript ? "(js|ts)" : "(js)");
// }
//
// /**
// * @param is Input stream
// * @return String Full contents of given stream as string
// */
// public static String getFileStreamAsString(java.io.InputStream is) {
// java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
//
// return s.hasNext() ? s.next() : "";
// }
// }
//
// Path: src/com/kstenschke/shifter/models/ShiftableSelection.java
// static final String ACTION_TEXT_SHIFT_SELECTION = "Shift Selection";
//
// Path: src/com/kstenschke/shifter/models/ShiftableTypes.java
// public enum Type {
// UNKNOWN,
//
// // Dictionaric types
// ACCESS_TYPE,
// DICTIONARY_WORD_EXT_SPECIFIC,
// DICTIONARY_WORD_GLOBAL,
//
// // Numeric types
// NUMERIC_VALUE,
// NUMERIC_POSTFIXED,
// ROMAN_NUMERAL,
//
// // Generic shiftable types
// QUOTED_STRING,
// PARENTHESIS,
// HTML_ENCODABLE,
// CAMEL_CASED,
// SEPARATED_PATH,
// WORDS_TUPEL,
//
// // Operators (<, >, +, -, etc.) and expressions
// OPERATOR_SIGN,
// LOGICAL_OPERATOR,
// MONO_CHARACTER,
// TERNARY_EXPRESSION,
//
// RGB_COLOR,
//
// // CSS unit (%, cm, em, in, pt, px, rem, vw, vh, vmin, vmax)
// CSS_UNIT,
//
// // DOC comment related
// DOC_COMMENT_TAG,
// DOC_COMMENT_DATA_TYPE,
//
// // PHP specific
// PHP_VARIABLE_OR_ARRAY,
//
// // JavaScript specific
// JS_VARIABLES_DECLARATIONS,
// SIZZLE_SELECTOR,
// JQUERY_OBSERVER,
//
// TRAILING_COMMENT
// }
// Path: src/com/kstenschke/shifter/models/ShiftableTypesManager.java
import com.kstenschke.shifter.models.shiftable_types.*;
import com.kstenschke.shifter.utils.UtilsFile;
import org.jetbrains.annotations.Nullable;
import static com.kstenschke.shifter.models.ShiftableSelection.ACTION_TEXT_SHIFT_SELECTION;
import static com.kstenschke.shifter.models.ShiftableTypes.Type.*;
if (JsVariablesDeclarations.isJsVariables(word)) {
return JS_VARIABLES_DECLARATIONS;
}
if (SizzleSelector.isSelector(word)) {
return SIZZLE_SELECTOR;
}
// DocComment shiftable_types (must be prefixed w/ "@")
typeDataTypeInDocComment = new DocCommentType();
if (DocCommentType.isDocCommentTypeLineContext(actionContainer.caretLine)) {
typeTagInDocComment = new DocCommentTag();
if (prefixChar.matches("@")
&& typeTagInDocComment.isDocCommentTag(prefixChar, actionContainer.caretLine)
) {
return DOC_COMMENT_TAG;
}
if (typeDataTypeInDocComment.isDocCommentType(prefixChar, actionContainer.caretLine)) {
return DOC_COMMENT_DATA_TYPE;
}
}
// Object visibility
accessType = new AccessType();
if (!"@".equals(prefixChar) && accessType.isAccessType(word)) {
return ACCESS_TYPE;
}
// File extension specific term in dictionary
typeDictionaryTerm = new DictionaryTerm();
|
String fileExtension = UtilsFile.extractFileExtension(actionContainer.filename);
|
kstenschke/shifter-plugin
|
src/com/kstenschke/shifter/models/ShiftableTypesManager.java
|
// Path: src/com/kstenschke/shifter/utils/UtilsFile.java
// public class UtilsFile {
//
// public static String extractFileExtension(@Nullable String filename) {
// return extractFileExtension(filename, false);
// }
//
// /**
// * @param filename Filename from which to extract the extension
// * @param toLowerCase Convert extension to lower case?
// * @return The extension Everything after the last "." in the full filename
// */
// public static String extractFileExtension(@Nullable String filename, boolean toLowerCase) {
// if (null == filename ||
// filename.isEmpty() ||
// filename.length() < 3 ||
// !filename.contains(".")
// ) {
// return "";
// }
// filename = getBasename(filename);
// if ("".equals(filename)) {
// return filename;
// }
//
// return toLowerCase
// ? filename.substring(filename.lastIndexOf('.') + 1).toLowerCase()
// : filename.substring(filename.lastIndexOf('.') + 1);
// }
//
// private static String getBasename(@Nullable String filename) {
// if (null == filename) {
// return "";
// }
// if (filename.contains("/")) {
// filename = filename.substring(filename.lastIndexOf("/") + 1);
// }
// if (filename.contains("\\")) {
// filename = filename.substring(filename.lastIndexOf("\\") + 1);
// }
// return filename;
// }
//
// private static boolean filenameEndsWithExtension(@Nullable String filename) {
// filename = getBasename(filename);
// if (null == filename || filename.isEmpty() || !filename.contains(".")) {
// return false;
// }
//
// String[] parts = filename.split("\\.");
//
// return parts.length > 1 && parts[0].length() > 0 && parts[1].length() >= 2;
// }
//
// public static boolean isPhpFile(@Nullable String filename) {
// filename = getBasename(filename).toLowerCase();
// return filenameEndsWithExtension(filename) && extractFileExtension(filename).matches("(php|phtml)");
// }
//
// public static boolean isCssFile(@Nullable String filename) {
// filename = getBasename(filename).toLowerCase();
// return filenameEndsWithExtension(filename) && extractFileExtension(filename).matches("(css|scss|sass|less|styl)");
// }
//
// public static boolean isJavaScriptFile(@Nullable String filename, boolean allowTypeScript) {
// filename = getBasename(filename).toLowerCase();
// if (!filenameEndsWithExtension(filename)) {
// return false;
// }
//
// return extractFileExtension(filename).matches(allowTypeScript ? "(js|ts)" : "(js)");
// }
//
// /**
// * @param is Input stream
// * @return String Full contents of given stream as string
// */
// public static String getFileStreamAsString(java.io.InputStream is) {
// java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
//
// return s.hasNext() ? s.next() : "";
// }
// }
//
// Path: src/com/kstenschke/shifter/models/ShiftableSelection.java
// static final String ACTION_TEXT_SHIFT_SELECTION = "Shift Selection";
//
// Path: src/com/kstenschke/shifter/models/ShiftableTypes.java
// public enum Type {
// UNKNOWN,
//
// // Dictionaric types
// ACCESS_TYPE,
// DICTIONARY_WORD_EXT_SPECIFIC,
// DICTIONARY_WORD_GLOBAL,
//
// // Numeric types
// NUMERIC_VALUE,
// NUMERIC_POSTFIXED,
// ROMAN_NUMERAL,
//
// // Generic shiftable types
// QUOTED_STRING,
// PARENTHESIS,
// HTML_ENCODABLE,
// CAMEL_CASED,
// SEPARATED_PATH,
// WORDS_TUPEL,
//
// // Operators (<, >, +, -, etc.) and expressions
// OPERATOR_SIGN,
// LOGICAL_OPERATOR,
// MONO_CHARACTER,
// TERNARY_EXPRESSION,
//
// RGB_COLOR,
//
// // CSS unit (%, cm, em, in, pt, px, rem, vw, vh, vmin, vmax)
// CSS_UNIT,
//
// // DOC comment related
// DOC_COMMENT_TAG,
// DOC_COMMENT_DATA_TYPE,
//
// // PHP specific
// PHP_VARIABLE_OR_ARRAY,
//
// // JavaScript specific
// JS_VARIABLES_DECLARATIONS,
// SIZZLE_SELECTOR,
// JQUERY_OBSERVER,
//
// TRAILING_COMMENT
// }
|
import com.kstenschke.shifter.models.shiftable_types.*;
import com.kstenschke.shifter.utils.UtilsFile;
import org.jetbrains.annotations.Nullable;
import static com.kstenschke.shifter.models.ShiftableSelection.ACTION_TEXT_SHIFT_SELECTION;
import static com.kstenschke.shifter.models.ShiftableTypes.Type.*;
|
String getShiftedWord(ActionContainer actionContainer, @Nullable Integer moreCount) {
wordType = getWordType(actionContainer.selectedText, "", "", false, actionContainer);
return getShiftedWord(actionContainer, actionContainer.selectedText, wordType, moreCount);
}
String getActionText() {
switch (wordType) {
case CSS_UNIT:
return CssUnit.ACTION_TEXT;
case HTML_ENCODABLE:
return HtmlEncodable.ACTION_TEXT;
case JS_VARIABLES_DECLARATIONS:
return JsVariablesDeclarations.ACTION_TEXT;
case LOGICAL_OPERATOR:
return LogicalOperator.ACTION_TEXT;
case MONO_CHARACTER:
return MonoCharacter.ACTION_TEXT;
case NUMERIC_VALUE:
return NumericValue.ACTION_TEXT;
case RGB_COLOR:
return RgbColor.ACTION_TEXT;
case TERNARY_EXPRESSION:
return TernaryExpression.ACTION_TEXT;
case TRAILING_COMMENT:
return TrailingComment.ACTION_TEXT;
case WORDS_TUPEL:
return Tupel.ACTION_TEXT;
default:
|
// Path: src/com/kstenschke/shifter/utils/UtilsFile.java
// public class UtilsFile {
//
// public static String extractFileExtension(@Nullable String filename) {
// return extractFileExtension(filename, false);
// }
//
// /**
// * @param filename Filename from which to extract the extension
// * @param toLowerCase Convert extension to lower case?
// * @return The extension Everything after the last "." in the full filename
// */
// public static String extractFileExtension(@Nullable String filename, boolean toLowerCase) {
// if (null == filename ||
// filename.isEmpty() ||
// filename.length() < 3 ||
// !filename.contains(".")
// ) {
// return "";
// }
// filename = getBasename(filename);
// if ("".equals(filename)) {
// return filename;
// }
//
// return toLowerCase
// ? filename.substring(filename.lastIndexOf('.') + 1).toLowerCase()
// : filename.substring(filename.lastIndexOf('.') + 1);
// }
//
// private static String getBasename(@Nullable String filename) {
// if (null == filename) {
// return "";
// }
// if (filename.contains("/")) {
// filename = filename.substring(filename.lastIndexOf("/") + 1);
// }
// if (filename.contains("\\")) {
// filename = filename.substring(filename.lastIndexOf("\\") + 1);
// }
// return filename;
// }
//
// private static boolean filenameEndsWithExtension(@Nullable String filename) {
// filename = getBasename(filename);
// if (null == filename || filename.isEmpty() || !filename.contains(".")) {
// return false;
// }
//
// String[] parts = filename.split("\\.");
//
// return parts.length > 1 && parts[0].length() > 0 && parts[1].length() >= 2;
// }
//
// public static boolean isPhpFile(@Nullable String filename) {
// filename = getBasename(filename).toLowerCase();
// return filenameEndsWithExtension(filename) && extractFileExtension(filename).matches("(php|phtml)");
// }
//
// public static boolean isCssFile(@Nullable String filename) {
// filename = getBasename(filename).toLowerCase();
// return filenameEndsWithExtension(filename) && extractFileExtension(filename).matches("(css|scss|sass|less|styl)");
// }
//
// public static boolean isJavaScriptFile(@Nullable String filename, boolean allowTypeScript) {
// filename = getBasename(filename).toLowerCase();
// if (!filenameEndsWithExtension(filename)) {
// return false;
// }
//
// return extractFileExtension(filename).matches(allowTypeScript ? "(js|ts)" : "(js)");
// }
//
// /**
// * @param is Input stream
// * @return String Full contents of given stream as string
// */
// public static String getFileStreamAsString(java.io.InputStream is) {
// java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
//
// return s.hasNext() ? s.next() : "";
// }
// }
//
// Path: src/com/kstenschke/shifter/models/ShiftableSelection.java
// static final String ACTION_TEXT_SHIFT_SELECTION = "Shift Selection";
//
// Path: src/com/kstenschke/shifter/models/ShiftableTypes.java
// public enum Type {
// UNKNOWN,
//
// // Dictionaric types
// ACCESS_TYPE,
// DICTIONARY_WORD_EXT_SPECIFIC,
// DICTIONARY_WORD_GLOBAL,
//
// // Numeric types
// NUMERIC_VALUE,
// NUMERIC_POSTFIXED,
// ROMAN_NUMERAL,
//
// // Generic shiftable types
// QUOTED_STRING,
// PARENTHESIS,
// HTML_ENCODABLE,
// CAMEL_CASED,
// SEPARATED_PATH,
// WORDS_TUPEL,
//
// // Operators (<, >, +, -, etc.) and expressions
// OPERATOR_SIGN,
// LOGICAL_OPERATOR,
// MONO_CHARACTER,
// TERNARY_EXPRESSION,
//
// RGB_COLOR,
//
// // CSS unit (%, cm, em, in, pt, px, rem, vw, vh, vmin, vmax)
// CSS_UNIT,
//
// // DOC comment related
// DOC_COMMENT_TAG,
// DOC_COMMENT_DATA_TYPE,
//
// // PHP specific
// PHP_VARIABLE_OR_ARRAY,
//
// // JavaScript specific
// JS_VARIABLES_DECLARATIONS,
// SIZZLE_SELECTOR,
// JQUERY_OBSERVER,
//
// TRAILING_COMMENT
// }
// Path: src/com/kstenschke/shifter/models/ShiftableTypesManager.java
import com.kstenschke.shifter.models.shiftable_types.*;
import com.kstenschke.shifter.utils.UtilsFile;
import org.jetbrains.annotations.Nullable;
import static com.kstenschke.shifter.models.ShiftableSelection.ACTION_TEXT_SHIFT_SELECTION;
import static com.kstenschke.shifter.models.ShiftableTypes.Type.*;
String getShiftedWord(ActionContainer actionContainer, @Nullable Integer moreCount) {
wordType = getWordType(actionContainer.selectedText, "", "", false, actionContainer);
return getShiftedWord(actionContainer, actionContainer.selectedText, wordType, moreCount);
}
String getActionText() {
switch (wordType) {
case CSS_UNIT:
return CssUnit.ACTION_TEXT;
case HTML_ENCODABLE:
return HtmlEncodable.ACTION_TEXT;
case JS_VARIABLES_DECLARATIONS:
return JsVariablesDeclarations.ACTION_TEXT;
case LOGICAL_OPERATOR:
return LogicalOperator.ACTION_TEXT;
case MONO_CHARACTER:
return MonoCharacter.ACTION_TEXT;
case NUMERIC_VALUE:
return NumericValue.ACTION_TEXT;
case RGB_COLOR:
return RgbColor.ACTION_TEXT;
case TERNARY_EXPRESSION:
return TernaryExpression.ACTION_TEXT;
case TRAILING_COMMENT:
return TrailingComment.ACTION_TEXT;
case WORDS_TUPEL:
return Tupel.ACTION_TEXT;
default:
|
return ACTION_TEXT_SHIFT_SELECTION;
|
kstenschke/shifter-plugin
|
src/com/kstenschke/shifter/models/shiftable_types/StaticWordType.java
|
// Path: src/com/kstenschke/shifter/utils/UtilsArray.java
// public class UtilsArray {
//
// /**
// * Find strings position in array
// *
// * @param haystack String array to search in
// * @param needle String to be looked for
// * @return int Found position or -1
// */
// public static int getOffset(String[] haystack, String needle) {
// for (int i = 0; i < haystack.length; i++) {
// if (haystack[i].equals(needle)) {
// return i;
// }
// }
//
// return -1;
// }
//
// /**
// * Concatenate strings of given array glued by given delimiter
// *
// * @param stringsArr Array of strings
// * @param glue Glue in between concatenated strings
// * @return String All items of stringsArr concatenated w/ glue
// */
// public static String implode(String[] stringsArr, String glue) {
// StringBuilder out = new StringBuilder();
// for (int i = 0; i < stringsArr.length; i++) {
// out.append(0 == i ? "" : glue).append(stringsArr[i]);
// }
//
// return out.toString();
// }
//
// /**
// * This String utility or util method can be used to merge 2 arrays of
// * string values. If the input arrays are like this array1 = {"a", "b" ,
// * "c"} array2 = {"c", "d", "e"} Then the output array will have {"a", "b" ,
// * "c", "d", "e"}
// * <p/>
// * This takes care of eliminating duplicates and checks null values.
// *
// * @param array1 Array of strings
// * @param array2 Array of strings
// * @return array Merged array containing each of the elements of array1 and array2
// */
// private static String[] mergeArrays(String[] array1, String[] array2) {
// if (null == array1 || array1.length == 0) {
// return array2;
// }
// if (null == array2 || array2.length == 0) {
// return array1;
// }
//
// List<String> array1List = Arrays.asList(array1);
// List<String> array2List = Arrays.asList(array2);
//
// List<String> result = new ArrayList<>(array1List);
//
// List<String> tmp = new ArrayList<>(array1List);
// tmp.retainAll(array2List);
//
// result.removeAll(tmp);
// result.addAll(array2List);
//
// return result.toArray(new String[0]);
// }
//
// /**
// * Merge three string arrays
// *
// * @param array1 Array of strings
// * @param array2 Array of strings
// * @param array3 Array of strings
// * @return array Merged array containing each of the elements of array1, array2 and array3
// */
// public static String[] mergeArrays(String[] array1, String[] array2, String[] array3) {
// return mergeArrays(mergeArrays(array1, array2), array3);
// }
//
// public static boolean hasDuplicateItems(String[] array) {
// for (int j = 0; j < array.length; j++) {
// for (int k = j + 1; k < array.length; k++) {
// if (array[k].equals(array[j])) {
// return true;
// }
// }
// }
//
// return false;
// }
//
// public static String[] reduceDuplicateItems(String[] items) {
// return new HashSet<>(Arrays.asList(items)).toArray(new String[0]);
// }
// }
|
import com.kstenschke.shifter.utils.UtilsArray;
|
/*
* Copyright Kay Stenschke
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kstenschke.shifter.models.shiftable_types;
/**
* Shifter general word type class
*/
class StaticWordType {
private final String[] keywords;
private final int amountKeywords;
private final String regExPattern;
public StaticWordType(String[] keywords) {
this.keywords = keywords;
amountKeywords = keywords.length;
|
// Path: src/com/kstenschke/shifter/utils/UtilsArray.java
// public class UtilsArray {
//
// /**
// * Find strings position in array
// *
// * @param haystack String array to search in
// * @param needle String to be looked for
// * @return int Found position or -1
// */
// public static int getOffset(String[] haystack, String needle) {
// for (int i = 0; i < haystack.length; i++) {
// if (haystack[i].equals(needle)) {
// return i;
// }
// }
//
// return -1;
// }
//
// /**
// * Concatenate strings of given array glued by given delimiter
// *
// * @param stringsArr Array of strings
// * @param glue Glue in between concatenated strings
// * @return String All items of stringsArr concatenated w/ glue
// */
// public static String implode(String[] stringsArr, String glue) {
// StringBuilder out = new StringBuilder();
// for (int i = 0; i < stringsArr.length; i++) {
// out.append(0 == i ? "" : glue).append(stringsArr[i]);
// }
//
// return out.toString();
// }
//
// /**
// * This String utility or util method can be used to merge 2 arrays of
// * string values. If the input arrays are like this array1 = {"a", "b" ,
// * "c"} array2 = {"c", "d", "e"} Then the output array will have {"a", "b" ,
// * "c", "d", "e"}
// * <p/>
// * This takes care of eliminating duplicates and checks null values.
// *
// * @param array1 Array of strings
// * @param array2 Array of strings
// * @return array Merged array containing each of the elements of array1 and array2
// */
// private static String[] mergeArrays(String[] array1, String[] array2) {
// if (null == array1 || array1.length == 0) {
// return array2;
// }
// if (null == array2 || array2.length == 0) {
// return array1;
// }
//
// List<String> array1List = Arrays.asList(array1);
// List<String> array2List = Arrays.asList(array2);
//
// List<String> result = new ArrayList<>(array1List);
//
// List<String> tmp = new ArrayList<>(array1List);
// tmp.retainAll(array2List);
//
// result.removeAll(tmp);
// result.addAll(array2List);
//
// return result.toArray(new String[0]);
// }
//
// /**
// * Merge three string arrays
// *
// * @param array1 Array of strings
// * @param array2 Array of strings
// * @param array3 Array of strings
// * @return array Merged array containing each of the elements of array1, array2 and array3
// */
// public static String[] mergeArrays(String[] array1, String[] array2, String[] array3) {
// return mergeArrays(mergeArrays(array1, array2), array3);
// }
//
// public static boolean hasDuplicateItems(String[] array) {
// for (int j = 0; j < array.length; j++) {
// for (int k = j + 1; k < array.length; k++) {
// if (array[k].equals(array[j])) {
// return true;
// }
// }
// }
//
// return false;
// }
//
// public static String[] reduceDuplicateItems(String[] items) {
// return new HashSet<>(Arrays.asList(items)).toArray(new String[0]);
// }
// }
// Path: src/com/kstenschke/shifter/models/shiftable_types/StaticWordType.java
import com.kstenschke.shifter.utils.UtilsArray;
/*
* Copyright Kay Stenschke
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kstenschke.shifter.models.shiftable_types;
/**
* Shifter general word type class
*/
class StaticWordType {
private final String[] keywords;
private final int amountKeywords;
private final String regExPattern;
public StaticWordType(String[] keywords) {
this.keywords = keywords;
amountKeywords = keywords.length;
|
regExPattern = UtilsArray.implode(keywords, "|");
|
kstenschke/shifter-plugin
|
src/com/kstenschke/shifter/models/shiftable_types/DocCommentDataType.java
|
// Path: src/com/kstenschke/shifter/utils/UtilsFile.java
// public class UtilsFile {
//
// public static String extractFileExtension(@Nullable String filename) {
// return extractFileExtension(filename, false);
// }
//
// /**
// * @param filename Filename from which to extract the extension
// * @param toLowerCase Convert extension to lower case?
// * @return The extension Everything after the last "." in the full filename
// */
// public static String extractFileExtension(@Nullable String filename, boolean toLowerCase) {
// if (null == filename ||
// filename.isEmpty() ||
// filename.length() < 3 ||
// !filename.contains(".")
// ) {
// return "";
// }
// filename = getBasename(filename);
// if ("".equals(filename)) {
// return filename;
// }
//
// return toLowerCase
// ? filename.substring(filename.lastIndexOf('.') + 1).toLowerCase()
// : filename.substring(filename.lastIndexOf('.') + 1);
// }
//
// private static String getBasename(@Nullable String filename) {
// if (null == filename) {
// return "";
// }
// if (filename.contains("/")) {
// filename = filename.substring(filename.lastIndexOf("/") + 1);
// }
// if (filename.contains("\\")) {
// filename = filename.substring(filename.lastIndexOf("\\") + 1);
// }
// return filename;
// }
//
// private static boolean filenameEndsWithExtension(@Nullable String filename) {
// filename = getBasename(filename);
// if (null == filename || filename.isEmpty() || !filename.contains(".")) {
// return false;
// }
//
// String[] parts = filename.split("\\.");
//
// return parts.length > 1 && parts[0].length() > 0 && parts[1].length() >= 2;
// }
//
// public static boolean isPhpFile(@Nullable String filename) {
// filename = getBasename(filename).toLowerCase();
// return filenameEndsWithExtension(filename) && extractFileExtension(filename).matches("(php|phtml)");
// }
//
// public static boolean isCssFile(@Nullable String filename) {
// filename = getBasename(filename).toLowerCase();
// return filenameEndsWithExtension(filename) && extractFileExtension(filename).matches("(css|scss|sass|less|styl)");
// }
//
// public static boolean isJavaScriptFile(@Nullable String filename, boolean allowTypeScript) {
// filename = getBasename(filename).toLowerCase();
// if (!filenameEndsWithExtension(filename)) {
// return false;
// }
//
// return extractFileExtension(filename).matches(allowTypeScript ? "(js|ts)" : "(js)");
// }
//
// /**
// * @param is Input stream
// * @return String Full contents of given stream as string
// */
// public static String getFileStreamAsString(java.io.InputStream is) {
// java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
//
// return s.hasNext() ? s.next() : "";
// }
// }
|
import com.kstenschke.shifter.utils.UtilsFile;
import java.util.Arrays;
import java.util.List;
|
/*
* Copyright Kay Stenschke
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kstenschke.shifter.models.shiftable_types;
/**
* DocCommentType class
*/
class DocCommentDataType {
private final String[] typesJavaScript;
private final String[] typesJava;
private final String[] typesPHP;
private final String[] typesObjectiveC;
DocCommentDataType() {
typesJavaScript = new String[]{ "array", "boolean", "element", "event", "function", "number", "null", "object", "string", "undefined" };
typesJava = new String[]{ "boolean", "byte", "char", "double", "float", "int", "long", "short", "string" };
typesPHP = new String[]{ "array", "bool", "float", "int", "null", "object", "resource", "string" };
typesObjectiveC = new String[]{ "int", "char", "float", "double", "id", "BOOL", "long", "short", "signed", "unsigned" };
}
/**
* @param word String to be shifted
* @param filename Filename of the edited file
* @param isUp Shifting up or down?
* @return String Shifting result
*/
public String getShifted(String word, String filename, boolean isUp) {
String[] dataTypes = getDataTypesByFilename(filename);
int amountTypes = dataTypes.length;
String wordLower = word.toLowerCase();
if (0 == amountTypes) {
return wordLower;
}
List<String> dataTypesList = Arrays.asList(dataTypes);
int curIndex = dataTypesList.indexOf(wordLower);
curIndex = NumericValue.moduloShiftInteger(curIndex, amountTypes, isUp);
if (curIndex < 0) {
curIndex = 0;
}
return dataTypesList.get(curIndex);
}
/**
* Return array of data shiftable_types of detected language of edited file
*
* @param filename Filename of edited file
* @return String[]
*/
private String[] getDataTypesByFilename(String filename) {
if (null != filename) {
String filenameLower = filename.toLowerCase();
|
// Path: src/com/kstenschke/shifter/utils/UtilsFile.java
// public class UtilsFile {
//
// public static String extractFileExtension(@Nullable String filename) {
// return extractFileExtension(filename, false);
// }
//
// /**
// * @param filename Filename from which to extract the extension
// * @param toLowerCase Convert extension to lower case?
// * @return The extension Everything after the last "." in the full filename
// */
// public static String extractFileExtension(@Nullable String filename, boolean toLowerCase) {
// if (null == filename ||
// filename.isEmpty() ||
// filename.length() < 3 ||
// !filename.contains(".")
// ) {
// return "";
// }
// filename = getBasename(filename);
// if ("".equals(filename)) {
// return filename;
// }
//
// return toLowerCase
// ? filename.substring(filename.lastIndexOf('.') + 1).toLowerCase()
// : filename.substring(filename.lastIndexOf('.') + 1);
// }
//
// private static String getBasename(@Nullable String filename) {
// if (null == filename) {
// return "";
// }
// if (filename.contains("/")) {
// filename = filename.substring(filename.lastIndexOf("/") + 1);
// }
// if (filename.contains("\\")) {
// filename = filename.substring(filename.lastIndexOf("\\") + 1);
// }
// return filename;
// }
//
// private static boolean filenameEndsWithExtension(@Nullable String filename) {
// filename = getBasename(filename);
// if (null == filename || filename.isEmpty() || !filename.contains(".")) {
// return false;
// }
//
// String[] parts = filename.split("\\.");
//
// return parts.length > 1 && parts[0].length() > 0 && parts[1].length() >= 2;
// }
//
// public static boolean isPhpFile(@Nullable String filename) {
// filename = getBasename(filename).toLowerCase();
// return filenameEndsWithExtension(filename) && extractFileExtension(filename).matches("(php|phtml)");
// }
//
// public static boolean isCssFile(@Nullable String filename) {
// filename = getBasename(filename).toLowerCase();
// return filenameEndsWithExtension(filename) && extractFileExtension(filename).matches("(css|scss|sass|less|styl)");
// }
//
// public static boolean isJavaScriptFile(@Nullable String filename, boolean allowTypeScript) {
// filename = getBasename(filename).toLowerCase();
// if (!filenameEndsWithExtension(filename)) {
// return false;
// }
//
// return extractFileExtension(filename).matches(allowTypeScript ? "(js|ts)" : "(js)");
// }
//
// /**
// * @param is Input stream
// * @return String Full contents of given stream as string
// */
// public static String getFileStreamAsString(java.io.InputStream is) {
// java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
//
// return s.hasNext() ? s.next() : "";
// }
// }
// Path: src/com/kstenschke/shifter/models/shiftable_types/DocCommentDataType.java
import com.kstenschke.shifter.utils.UtilsFile;
import java.util.Arrays;
import java.util.List;
/*
* Copyright Kay Stenschke
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kstenschke.shifter.models.shiftable_types;
/**
* DocCommentType class
*/
class DocCommentDataType {
private final String[] typesJavaScript;
private final String[] typesJava;
private final String[] typesPHP;
private final String[] typesObjectiveC;
DocCommentDataType() {
typesJavaScript = new String[]{ "array", "boolean", "element", "event", "function", "number", "null", "object", "string", "undefined" };
typesJava = new String[]{ "boolean", "byte", "char", "double", "float", "int", "long", "short", "string" };
typesPHP = new String[]{ "array", "bool", "float", "int", "null", "object", "resource", "string" };
typesObjectiveC = new String[]{ "int", "char", "float", "double", "id", "BOOL", "long", "short", "signed", "unsigned" };
}
/**
* @param word String to be shifted
* @param filename Filename of the edited file
* @param isUp Shifting up or down?
* @return String Shifting result
*/
public String getShifted(String word, String filename, boolean isUp) {
String[] dataTypes = getDataTypesByFilename(filename);
int amountTypes = dataTypes.length;
String wordLower = word.toLowerCase();
if (0 == amountTypes) {
return wordLower;
}
List<String> dataTypesList = Arrays.asList(dataTypes);
int curIndex = dataTypesList.indexOf(wordLower);
curIndex = NumericValue.moduloShiftInteger(curIndex, amountTypes, isUp);
if (curIndex < 0) {
curIndex = 0;
}
return dataTypesList.get(curIndex);
}
/**
* Return array of data shiftable_types of detected language of edited file
*
* @param filename Filename of edited file
* @return String[]
*/
private String[] getDataTypesByFilename(String filename) {
if (null != filename) {
String filenameLower = filename.toLowerCase();
|
if (UtilsFile.isJavaScriptFile(filenameLower, true)) {
|
kstenschke/shifter-plugin
|
src/com/kstenschke/shifter/models/shiftable_types/CssUnit.java
|
// Path: src/com/kstenschke/shifter/utils/UtilsMap.java
// public class UtilsMap {
//
// public static int getSumOfValues(HashMap<String, Integer> map) {
// int sum = 0;
// for (int value : map.values()){
// sum+= value;
// }
// return sum;
// }
//
// public static String getKeyOfHighestValue(HashMap<String, Integer> map) {
// int max = 0;
// String key = "";
//
// Iterator it = map.entrySet().iterator();
// while (it.hasNext()) {
// java.util.Map.Entry pairs = (java.util.Map.Entry) it.next();
// int value = Integer.parseInt( pairs.getValue().toString());
// if (value > max) {
// max = value;
// key = pairs.getKey().toString();
// }
// // Avoid ConcurrentModificationException
// it.remove();
// }
//
// return key;
// }
// }
|
import com.kstenschke.shifter.utils.UtilsMap;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
|
|| value.endsWith(UNIT_IN) || value.endsWith(UNIT_MM)
|| value.endsWith(UNIT_PC) || value.endsWith(UNIT_PT) || value.endsWith(UNIT_PX)
|| value.endsWith(UNIT_VH) || value.endsWith(UNIT_VW)
) {
return value.substring(value.length() - 2);
}
return "";
}
/**
* @param stylesheet CSS content
* @return String most prominently used unit of given stylesheet, 'px' if none used yet
*/
public static String determineMostProminentUnit(String stylesheet) {
HashMap<String, Integer> map = new HashMap<>();
map.put(UNIT_CM, StringUtils.countMatches(stylesheet,UNIT_CM + ";"));
map.put(UNIT_EM, StringUtils.countMatches(stylesheet,UNIT_EM + ";"));
map.put(UNIT_IN, StringUtils.countMatches(stylesheet,UNIT_IN + ";"));
map.put(UNIT_MM, StringUtils.countMatches(stylesheet,UNIT_MM + ";"));
map.put(UNIT_PC, StringUtils.countMatches(stylesheet,UNIT_PC + ";"));
map.put(UNIT_PT, StringUtils.countMatches(stylesheet,UNIT_PT + ";"));
map.put(UNIT_PX, StringUtils.countMatches(stylesheet,UNIT_PX + ";"));
map.put(UNIT_REM, StringUtils.countMatches(stylesheet,UNIT_REM + ";"));
map.put(UNIT_VW, StringUtils.countMatches(stylesheet,UNIT_VW + ";"));
map.put(UNIT_VH, StringUtils.countMatches(stylesheet,UNIT_VH + ";"));
map.put(UNIT_VMIN, StringUtils.countMatches(stylesheet,UNIT_VMIN + ";"));
map.put(UNIT_VMAX, StringUtils.countMatches(stylesheet,UNIT_VMAX + ";"));
|
// Path: src/com/kstenschke/shifter/utils/UtilsMap.java
// public class UtilsMap {
//
// public static int getSumOfValues(HashMap<String, Integer> map) {
// int sum = 0;
// for (int value : map.values()){
// sum+= value;
// }
// return sum;
// }
//
// public static String getKeyOfHighestValue(HashMap<String, Integer> map) {
// int max = 0;
// String key = "";
//
// Iterator it = map.entrySet().iterator();
// while (it.hasNext()) {
// java.util.Map.Entry pairs = (java.util.Map.Entry) it.next();
// int value = Integer.parseInt( pairs.getValue().toString());
// if (value > max) {
// max = value;
// key = pairs.getKey().toString();
// }
// // Avoid ConcurrentModificationException
// it.remove();
// }
//
// return key;
// }
// }
// Path: src/com/kstenschke/shifter/models/shiftable_types/CssUnit.java
import com.kstenschke.shifter.utils.UtilsMap;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
|| value.endsWith(UNIT_IN) || value.endsWith(UNIT_MM)
|| value.endsWith(UNIT_PC) || value.endsWith(UNIT_PT) || value.endsWith(UNIT_PX)
|| value.endsWith(UNIT_VH) || value.endsWith(UNIT_VW)
) {
return value.substring(value.length() - 2);
}
return "";
}
/**
* @param stylesheet CSS content
* @return String most prominently used unit of given stylesheet, 'px' if none used yet
*/
public static String determineMostProminentUnit(String stylesheet) {
HashMap<String, Integer> map = new HashMap<>();
map.put(UNIT_CM, StringUtils.countMatches(stylesheet,UNIT_CM + ";"));
map.put(UNIT_EM, StringUtils.countMatches(stylesheet,UNIT_EM + ";"));
map.put(UNIT_IN, StringUtils.countMatches(stylesheet,UNIT_IN + ";"));
map.put(UNIT_MM, StringUtils.countMatches(stylesheet,UNIT_MM + ";"));
map.put(UNIT_PC, StringUtils.countMatches(stylesheet,UNIT_PC + ";"));
map.put(UNIT_PT, StringUtils.countMatches(stylesheet,UNIT_PT + ";"));
map.put(UNIT_PX, StringUtils.countMatches(stylesheet,UNIT_PX + ";"));
map.put(UNIT_REM, StringUtils.countMatches(stylesheet,UNIT_REM + ";"));
map.put(UNIT_VW, StringUtils.countMatches(stylesheet,UNIT_VW + ";"));
map.put(UNIT_VH, StringUtils.countMatches(stylesheet,UNIT_VH + ";"));
map.put(UNIT_VMIN, StringUtils.countMatches(stylesheet,UNIT_VMIN + ";"));
map.put(UNIT_VMAX, StringUtils.countMatches(stylesheet,UNIT_VMAX + ";"));
|
return UtilsMap.getSumOfValues(map) == 0 ? "px" : UtilsMap.getKeyOfHighestValue(map);
|
xushaomin/apple-config
|
apple-config-core/src/main/java/com/appleframework/config/core/factory/ConfigurerFactory.java
|
// Path: apple-config-core/src/main/java/com/appleframework/config/core/event/ConfigListener.java
// public interface ConfigListener extends EventListener {
//
// public Properties receiveConfigInfo(Map<String, Properties> propsMap);
//
// }
|
import java.util.Collection;
import java.util.Map;
import java.util.Properties;
import org.springframework.core.io.Resource;
import com.appleframework.config.core.event.ConfigListener;
|
package com.appleframework.config.core.factory;
public interface ConfigurerFactory {
public boolean isLoadRemote();
public void setRemoteFirst(boolean remoteFirst);
public void setLoadRemote(boolean loadRemote);
public void setEventListenerClass(String eventListenerClass);
|
// Path: apple-config-core/src/main/java/com/appleframework/config/core/event/ConfigListener.java
// public interface ConfigListener extends EventListener {
//
// public Properties receiveConfigInfo(Map<String, Properties> propsMap);
//
// }
// Path: apple-config-core/src/main/java/com/appleframework/config/core/factory/ConfigurerFactory.java
import java.util.Collection;
import java.util.Map;
import java.util.Properties;
import org.springframework.core.io.Resource;
import com.appleframework.config.core.event.ConfigListener;
package com.appleframework.config.core.factory;
public interface ConfigurerFactory {
public boolean isLoadRemote();
public void setRemoteFirst(boolean remoteFirst);
public void setLoadRemote(boolean loadRemote);
public void setEventListenerClass(String eventListenerClass);
|
public void setEventListener(ConfigListener eventListener);
|
xushaomin/apple-config
|
apple-config-apollo/src/main/java/com/appleframework/config/AppleApolloConfigRegistrarHelper.java
|
// Path: apple-config-core/src/main/java/com/appleframework/config/core/spi/NamespaceLoadSpi.java
// public interface NamespaceLoadSpi {
//
// public Set<String> load();
//
// }
|
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import com.appleframework.config.core.spi.NamespaceLoadSpi;
import com.ctrip.framework.apollo.core.spi.Ordered;
import com.ctrip.framework.apollo.spring.annotation.ApolloAnnotationProcessor;
import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValueProcessor;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.SpringValueProcessor;
import com.ctrip.framework.apollo.spring.property.SpringValueDefinitionProcessor;
import com.ctrip.framework.apollo.spring.spi.ApolloConfigRegistrarHelper;
import com.ctrip.framework.apollo.spring.util.BeanRegistrationUtil;
import com.google.common.collect.Lists;
|
package com.appleframework.config;
public class AppleApolloConfigRegistrarHelper implements ApolloConfigRegistrarHelper {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
AnnotationAttributes attributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableApolloConfig.class.getName()));
String[] namespaces = attributes.getStringArray("value");
int order = attributes.getNumber("order");
ApplePropertySourcesProcessor.addNamespaces(Lists.newArrayList(namespaces), order++);
|
// Path: apple-config-core/src/main/java/com/appleframework/config/core/spi/NamespaceLoadSpi.java
// public interface NamespaceLoadSpi {
//
// public Set<String> load();
//
// }
// Path: apple-config-apollo/src/main/java/com/appleframework/config/AppleApolloConfigRegistrarHelper.java
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import com.appleframework.config.core.spi.NamespaceLoadSpi;
import com.ctrip.framework.apollo.core.spi.Ordered;
import com.ctrip.framework.apollo.spring.annotation.ApolloAnnotationProcessor;
import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValueProcessor;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.SpringValueProcessor;
import com.ctrip.framework.apollo.spring.property.SpringValueDefinitionProcessor;
import com.ctrip.framework.apollo.spring.spi.ApolloConfigRegistrarHelper;
import com.ctrip.framework.apollo.spring.util.BeanRegistrationUtil;
import com.google.common.collect.Lists;
package com.appleframework.config;
public class AppleApolloConfigRegistrarHelper implements ApolloConfigRegistrarHelper {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
AnnotationAttributes attributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableApolloConfig.class.getName()));
String[] namespaces = attributes.getStringArray("value");
int order = attributes.getNumber("order");
ApplePropertySourcesProcessor.addNamespaces(Lists.newArrayList(namespaces), order++);
|
ServiceLoader<NamespaceLoadSpi> serviceLoader = ServiceLoader.load(NamespaceLoadSpi.class);
|
firebase/quickstart-android
|
crash/app/src/androidTest/java/com/google/samples/quickstart/crash/MainActivityTest.java
|
// Path: crash/app/src/main/java/com/google/samples/quickstart/crash/java/MainActivity.java
// public class MainActivity extends AppCompatActivity {
//
// private static final String TAG = "MainActivity";
// private FirebaseCrashlytics mCrashlytics;
// private CustomKeySamples samples;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// final ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
// setContentView(binding.getRoot());
//
// this.samples = new CustomKeySamples(this.getApplicationContext());
// samples.setSampleCustomKeys();
// samples.updateAndTrackNetworkState();
//
// mCrashlytics = FirebaseCrashlytics.getInstance();
//
// // Log the onCreate event, this will also be printed in logcat
// mCrashlytics.log("onCreate");
//
// // Add some custom values and identifiers to be included in crash reports
// mCrashlytics.setCustomKey("MeaningOfLife", 42);
// mCrashlytics.setCustomKey("LastUIAction", "Test value");
// mCrashlytics.setUserId("123456789");
//
// // Report a non-fatal exception, for demonstration purposes
// mCrashlytics.recordException(new Exception("Non-fatal exception: something went wrong!"));
//
// // Button that causes NullPointerException to be thrown.
// binding.crashButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// // Log that crash button was clicked.
// mCrashlytics.log("Crash button clicked.");
//
// // If catchCrashCheckBox is checked catch the exception and report it using
// // logException(), Otherwise throw the exception and let Crashlytics automatically
// // report the crash.
// if (binding.catchCrashCheckBox.isChecked()) {
// try {
// throw new NullPointerException();
// } catch (NullPointerException ex) {
// // [START crashlytics_log_and_report]
// mCrashlytics.log("NPE caught!");
// mCrashlytics.recordException(ex);
// // [END crashlytics_log_and_report]
// }
// } else {
// throw new NullPointerException();
// }
// }
// });
//
// // Log that the Activity was created.
// // [START crashlytics_log_event]
// mCrashlytics.log("Activity created");
// // [END crashlytics_log_event]
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// samples.stopTrackingNetworkState();
// }
// }
|
import androidx.test.espresso.ViewInteraction;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.rule.ActivityTestRule;
import androidx.test.filters.LargeTest;
import android.widget.CheckBox;
import com.google.samples.quickstart.crash.java.MainActivity;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
|
package com.google.samples.quickstart.crash;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
@Rule
|
// Path: crash/app/src/main/java/com/google/samples/quickstart/crash/java/MainActivity.java
// public class MainActivity extends AppCompatActivity {
//
// private static final String TAG = "MainActivity";
// private FirebaseCrashlytics mCrashlytics;
// private CustomKeySamples samples;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// final ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
// setContentView(binding.getRoot());
//
// this.samples = new CustomKeySamples(this.getApplicationContext());
// samples.setSampleCustomKeys();
// samples.updateAndTrackNetworkState();
//
// mCrashlytics = FirebaseCrashlytics.getInstance();
//
// // Log the onCreate event, this will also be printed in logcat
// mCrashlytics.log("onCreate");
//
// // Add some custom values and identifiers to be included in crash reports
// mCrashlytics.setCustomKey("MeaningOfLife", 42);
// mCrashlytics.setCustomKey("LastUIAction", "Test value");
// mCrashlytics.setUserId("123456789");
//
// // Report a non-fatal exception, for demonstration purposes
// mCrashlytics.recordException(new Exception("Non-fatal exception: something went wrong!"));
//
// // Button that causes NullPointerException to be thrown.
// binding.crashButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// // Log that crash button was clicked.
// mCrashlytics.log("Crash button clicked.");
//
// // If catchCrashCheckBox is checked catch the exception and report it using
// // logException(), Otherwise throw the exception and let Crashlytics automatically
// // report the crash.
// if (binding.catchCrashCheckBox.isChecked()) {
// try {
// throw new NullPointerException();
// } catch (NullPointerException ex) {
// // [START crashlytics_log_and_report]
// mCrashlytics.log("NPE caught!");
// mCrashlytics.recordException(ex);
// // [END crashlytics_log_and_report]
// }
// } else {
// throw new NullPointerException();
// }
// }
// });
//
// // Log that the Activity was created.
// // [START crashlytics_log_event]
// mCrashlytics.log("Activity created");
// // [END crashlytics_log_event]
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// samples.stopTrackingNetworkState();
// }
// }
// Path: crash/app/src/androidTest/java/com/google/samples/quickstart/crash/MainActivityTest.java
import androidx.test.espresso.ViewInteraction;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.rule.ActivityTestRule;
import androidx.test.filters.LargeTest;
import android.widget.CheckBox;
import com.google.samples.quickstart.crash.java.MainActivity;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
package com.google.samples.quickstart.crash;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
@Rule
|
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
|
firebase/quickstart-android
|
database/app/src/main/java/com/google/firebase/quickstart/database/java/PostDetailFragment.java
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Comment.java
// @IgnoreExtraProperties
// public class Comment {
//
// public String uid;
// public String author;
// public String text;
//
// public Comment() {
// // Default constructor required for calls to DataSnapshot.getValue(Comment.class)
// }
//
// public Comment(String uid, String author, String text) {
// this.uid = uid;
// this.author = author;
// this.text = text;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Post.java
// @IgnoreExtraProperties
// public class Post {
//
// public String uid;
// public String author;
// public String title;
// public String body;
// public int starCount = 0;
// public Map<String, Boolean> stars = new HashMap<>();
//
// public Post() {
// // Default constructor required for calls to DataSnapshot.getValue(Post.class)
// }
//
// public Post(String uid, String author, String title, String body) {
// this.uid = uid;
// this.author = author;
// this.title = title;
// this.body = body;
// }
//
// @Exclude
// public Map<String, Object> toMap() {
// HashMap<String, Object> result = new HashMap<>();
// result.put("uid", uid);
// result.put("author", author);
// result.put("title", title);
// result.put("body", body);
// result.put("starCount", starCount);
// result.put("stars", stars);
//
// return result;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/User.java
// @IgnoreExtraProperties
// public class User {
//
// public String username;
// public String email;
//
// public User() {
// // Default constructor required for calls to DataSnapshot.getValue(User.class)
// }
//
// public User(String username, String email) {
// this.username = username;
// this.email = email;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/viewholder/CommentViewHolder.java
// public class CommentViewHolder extends RecyclerView.ViewHolder {
// public TextView authorView;
// public TextView bodyView;
//
// public CommentViewHolder(View itemView) {
// super(itemView);
// authorView = itemView.findViewById(R.id.commentAuthor);
// bodyView = itemView.findViewById(R.id.commentBody);
// }
// }
|
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentPostDetailBinding;
import com.google.firebase.quickstart.database.java.models.Comment;
import com.google.firebase.quickstart.database.java.models.Post;
import com.google.firebase.quickstart.database.java.models.User;
import com.google.firebase.quickstart.database.java.viewholder.CommentViewHolder;
import java.util.ArrayList;
import java.util.List;
|
// Get post key from arguments
mPostKey = requireArguments().getString(EXTRA_POST_KEY);
if (mPostKey == null) {
throw new IllegalArgumentException("Must pass EXTRA_POST_KEY");
}
// Initialize Database
mPostReference = FirebaseDatabase.getInstance().getReference()
.child("posts").child(mPostKey);
mCommentsReference = FirebaseDatabase.getInstance().getReference()
.child("post-comments").child(mPostKey);
binding.buttonPostComment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
postComment();
}
});
binding.recyclerPostComments.setLayoutManager(new LinearLayoutManager(getContext()));
}
@Override
public void onStart() {
super.onStart();
// Add value event listener to the post
ValueEventListener postListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Comment.java
// @IgnoreExtraProperties
// public class Comment {
//
// public String uid;
// public String author;
// public String text;
//
// public Comment() {
// // Default constructor required for calls to DataSnapshot.getValue(Comment.class)
// }
//
// public Comment(String uid, String author, String text) {
// this.uid = uid;
// this.author = author;
// this.text = text;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Post.java
// @IgnoreExtraProperties
// public class Post {
//
// public String uid;
// public String author;
// public String title;
// public String body;
// public int starCount = 0;
// public Map<String, Boolean> stars = new HashMap<>();
//
// public Post() {
// // Default constructor required for calls to DataSnapshot.getValue(Post.class)
// }
//
// public Post(String uid, String author, String title, String body) {
// this.uid = uid;
// this.author = author;
// this.title = title;
// this.body = body;
// }
//
// @Exclude
// public Map<String, Object> toMap() {
// HashMap<String, Object> result = new HashMap<>();
// result.put("uid", uid);
// result.put("author", author);
// result.put("title", title);
// result.put("body", body);
// result.put("starCount", starCount);
// result.put("stars", stars);
//
// return result;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/User.java
// @IgnoreExtraProperties
// public class User {
//
// public String username;
// public String email;
//
// public User() {
// // Default constructor required for calls to DataSnapshot.getValue(User.class)
// }
//
// public User(String username, String email) {
// this.username = username;
// this.email = email;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/viewholder/CommentViewHolder.java
// public class CommentViewHolder extends RecyclerView.ViewHolder {
// public TextView authorView;
// public TextView bodyView;
//
// public CommentViewHolder(View itemView) {
// super(itemView);
// authorView = itemView.findViewById(R.id.commentAuthor);
// bodyView = itemView.findViewById(R.id.commentBody);
// }
// }
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/PostDetailFragment.java
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentPostDetailBinding;
import com.google.firebase.quickstart.database.java.models.Comment;
import com.google.firebase.quickstart.database.java.models.Post;
import com.google.firebase.quickstart.database.java.models.User;
import com.google.firebase.quickstart.database.java.viewholder.CommentViewHolder;
import java.util.ArrayList;
import java.util.List;
// Get post key from arguments
mPostKey = requireArguments().getString(EXTRA_POST_KEY);
if (mPostKey == null) {
throw new IllegalArgumentException("Must pass EXTRA_POST_KEY");
}
// Initialize Database
mPostReference = FirebaseDatabase.getInstance().getReference()
.child("posts").child(mPostKey);
mCommentsReference = FirebaseDatabase.getInstance().getReference()
.child("post-comments").child(mPostKey);
binding.buttonPostComment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
postComment();
}
});
binding.recyclerPostComments.setLayoutManager(new LinearLayoutManager(getContext()));
}
@Override
public void onStart() {
super.onStart();
// Add value event listener to the post
ValueEventListener postListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
|
Post post = dataSnapshot.getValue(Post.class);
|
firebase/quickstart-android
|
database/app/src/main/java/com/google/firebase/quickstart/database/java/PostDetailFragment.java
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Comment.java
// @IgnoreExtraProperties
// public class Comment {
//
// public String uid;
// public String author;
// public String text;
//
// public Comment() {
// // Default constructor required for calls to DataSnapshot.getValue(Comment.class)
// }
//
// public Comment(String uid, String author, String text) {
// this.uid = uid;
// this.author = author;
// this.text = text;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Post.java
// @IgnoreExtraProperties
// public class Post {
//
// public String uid;
// public String author;
// public String title;
// public String body;
// public int starCount = 0;
// public Map<String, Boolean> stars = new HashMap<>();
//
// public Post() {
// // Default constructor required for calls to DataSnapshot.getValue(Post.class)
// }
//
// public Post(String uid, String author, String title, String body) {
// this.uid = uid;
// this.author = author;
// this.title = title;
// this.body = body;
// }
//
// @Exclude
// public Map<String, Object> toMap() {
// HashMap<String, Object> result = new HashMap<>();
// result.put("uid", uid);
// result.put("author", author);
// result.put("title", title);
// result.put("body", body);
// result.put("starCount", starCount);
// result.put("stars", stars);
//
// return result;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/User.java
// @IgnoreExtraProperties
// public class User {
//
// public String username;
// public String email;
//
// public User() {
// // Default constructor required for calls to DataSnapshot.getValue(User.class)
// }
//
// public User(String username, String email) {
// this.username = username;
// this.email = email;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/viewholder/CommentViewHolder.java
// public class CommentViewHolder extends RecyclerView.ViewHolder {
// public TextView authorView;
// public TextView bodyView;
//
// public CommentViewHolder(View itemView) {
// super(itemView);
// authorView = itemView.findViewById(R.id.commentAuthor);
// bodyView = itemView.findViewById(R.id.commentBody);
// }
// }
|
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentPostDetailBinding;
import com.google.firebase.quickstart.database.java.models.Comment;
import com.google.firebase.quickstart.database.java.models.Post;
import com.google.firebase.quickstart.database.java.models.User;
import com.google.firebase.quickstart.database.java.viewholder.CommentViewHolder;
import java.util.ArrayList;
import java.util.List;
|
mPostReference.addValueEventListener(postListener);
// Keep copy of post listener so we can remove it when app stops
mPostListener = postListener;
// Listen for comments
mAdapter = new CommentAdapter(getContext(), mCommentsReference);
binding.recyclerPostComments.setAdapter(mAdapter);
}
@Override
public void onStop() {
super.onStop();
// Remove post value event listener
if (mPostListener != null) {
mPostReference.removeEventListener(mPostListener);
}
// Clean up comments listener
mAdapter.cleanupListener();
}
private void postComment() {
final String uid = getUid();
FirebaseDatabase.getInstance().getReference().child("users").child(uid)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user information
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Comment.java
// @IgnoreExtraProperties
// public class Comment {
//
// public String uid;
// public String author;
// public String text;
//
// public Comment() {
// // Default constructor required for calls to DataSnapshot.getValue(Comment.class)
// }
//
// public Comment(String uid, String author, String text) {
// this.uid = uid;
// this.author = author;
// this.text = text;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Post.java
// @IgnoreExtraProperties
// public class Post {
//
// public String uid;
// public String author;
// public String title;
// public String body;
// public int starCount = 0;
// public Map<String, Boolean> stars = new HashMap<>();
//
// public Post() {
// // Default constructor required for calls to DataSnapshot.getValue(Post.class)
// }
//
// public Post(String uid, String author, String title, String body) {
// this.uid = uid;
// this.author = author;
// this.title = title;
// this.body = body;
// }
//
// @Exclude
// public Map<String, Object> toMap() {
// HashMap<String, Object> result = new HashMap<>();
// result.put("uid", uid);
// result.put("author", author);
// result.put("title", title);
// result.put("body", body);
// result.put("starCount", starCount);
// result.put("stars", stars);
//
// return result;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/User.java
// @IgnoreExtraProperties
// public class User {
//
// public String username;
// public String email;
//
// public User() {
// // Default constructor required for calls to DataSnapshot.getValue(User.class)
// }
//
// public User(String username, String email) {
// this.username = username;
// this.email = email;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/viewholder/CommentViewHolder.java
// public class CommentViewHolder extends RecyclerView.ViewHolder {
// public TextView authorView;
// public TextView bodyView;
//
// public CommentViewHolder(View itemView) {
// super(itemView);
// authorView = itemView.findViewById(R.id.commentAuthor);
// bodyView = itemView.findViewById(R.id.commentBody);
// }
// }
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/PostDetailFragment.java
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentPostDetailBinding;
import com.google.firebase.quickstart.database.java.models.Comment;
import com.google.firebase.quickstart.database.java.models.Post;
import com.google.firebase.quickstart.database.java.models.User;
import com.google.firebase.quickstart.database.java.viewholder.CommentViewHolder;
import java.util.ArrayList;
import java.util.List;
mPostReference.addValueEventListener(postListener);
// Keep copy of post listener so we can remove it when app stops
mPostListener = postListener;
// Listen for comments
mAdapter = new CommentAdapter(getContext(), mCommentsReference);
binding.recyclerPostComments.setAdapter(mAdapter);
}
@Override
public void onStop() {
super.onStop();
// Remove post value event listener
if (mPostListener != null) {
mPostReference.removeEventListener(mPostListener);
}
// Clean up comments listener
mAdapter.cleanupListener();
}
private void postComment() {
final String uid = getUid();
FirebaseDatabase.getInstance().getReference().child("users").child(uid)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user information
|
User user = dataSnapshot.getValue(User.class);
|
firebase/quickstart-android
|
database/app/src/main/java/com/google/firebase/quickstart/database/java/PostDetailFragment.java
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Comment.java
// @IgnoreExtraProperties
// public class Comment {
//
// public String uid;
// public String author;
// public String text;
//
// public Comment() {
// // Default constructor required for calls to DataSnapshot.getValue(Comment.class)
// }
//
// public Comment(String uid, String author, String text) {
// this.uid = uid;
// this.author = author;
// this.text = text;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Post.java
// @IgnoreExtraProperties
// public class Post {
//
// public String uid;
// public String author;
// public String title;
// public String body;
// public int starCount = 0;
// public Map<String, Boolean> stars = new HashMap<>();
//
// public Post() {
// // Default constructor required for calls to DataSnapshot.getValue(Post.class)
// }
//
// public Post(String uid, String author, String title, String body) {
// this.uid = uid;
// this.author = author;
// this.title = title;
// this.body = body;
// }
//
// @Exclude
// public Map<String, Object> toMap() {
// HashMap<String, Object> result = new HashMap<>();
// result.put("uid", uid);
// result.put("author", author);
// result.put("title", title);
// result.put("body", body);
// result.put("starCount", starCount);
// result.put("stars", stars);
//
// return result;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/User.java
// @IgnoreExtraProperties
// public class User {
//
// public String username;
// public String email;
//
// public User() {
// // Default constructor required for calls to DataSnapshot.getValue(User.class)
// }
//
// public User(String username, String email) {
// this.username = username;
// this.email = email;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/viewholder/CommentViewHolder.java
// public class CommentViewHolder extends RecyclerView.ViewHolder {
// public TextView authorView;
// public TextView bodyView;
//
// public CommentViewHolder(View itemView) {
// super(itemView);
// authorView = itemView.findViewById(R.id.commentAuthor);
// bodyView = itemView.findViewById(R.id.commentBody);
// }
// }
|
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentPostDetailBinding;
import com.google.firebase.quickstart.database.java.models.Comment;
import com.google.firebase.quickstart.database.java.models.Post;
import com.google.firebase.quickstart.database.java.models.User;
import com.google.firebase.quickstart.database.java.viewholder.CommentViewHolder;
import java.util.ArrayList;
import java.util.List;
|
// Listen for comments
mAdapter = new CommentAdapter(getContext(), mCommentsReference);
binding.recyclerPostComments.setAdapter(mAdapter);
}
@Override
public void onStop() {
super.onStop();
// Remove post value event listener
if (mPostListener != null) {
mPostReference.removeEventListener(mPostListener);
}
// Clean up comments listener
mAdapter.cleanupListener();
}
private void postComment() {
final String uid = getUid();
FirebaseDatabase.getInstance().getReference().child("users").child(uid)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user information
User user = dataSnapshot.getValue(User.class);
String authorName = user.username;
// Create new comment object
String commentText = binding.fieldCommentText.getText().toString();
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Comment.java
// @IgnoreExtraProperties
// public class Comment {
//
// public String uid;
// public String author;
// public String text;
//
// public Comment() {
// // Default constructor required for calls to DataSnapshot.getValue(Comment.class)
// }
//
// public Comment(String uid, String author, String text) {
// this.uid = uid;
// this.author = author;
// this.text = text;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Post.java
// @IgnoreExtraProperties
// public class Post {
//
// public String uid;
// public String author;
// public String title;
// public String body;
// public int starCount = 0;
// public Map<String, Boolean> stars = new HashMap<>();
//
// public Post() {
// // Default constructor required for calls to DataSnapshot.getValue(Post.class)
// }
//
// public Post(String uid, String author, String title, String body) {
// this.uid = uid;
// this.author = author;
// this.title = title;
// this.body = body;
// }
//
// @Exclude
// public Map<String, Object> toMap() {
// HashMap<String, Object> result = new HashMap<>();
// result.put("uid", uid);
// result.put("author", author);
// result.put("title", title);
// result.put("body", body);
// result.put("starCount", starCount);
// result.put("stars", stars);
//
// return result;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/User.java
// @IgnoreExtraProperties
// public class User {
//
// public String username;
// public String email;
//
// public User() {
// // Default constructor required for calls to DataSnapshot.getValue(User.class)
// }
//
// public User(String username, String email) {
// this.username = username;
// this.email = email;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/viewholder/CommentViewHolder.java
// public class CommentViewHolder extends RecyclerView.ViewHolder {
// public TextView authorView;
// public TextView bodyView;
//
// public CommentViewHolder(View itemView) {
// super(itemView);
// authorView = itemView.findViewById(R.id.commentAuthor);
// bodyView = itemView.findViewById(R.id.commentBody);
// }
// }
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/PostDetailFragment.java
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentPostDetailBinding;
import com.google.firebase.quickstart.database.java.models.Comment;
import com.google.firebase.quickstart.database.java.models.Post;
import com.google.firebase.quickstart.database.java.models.User;
import com.google.firebase.quickstart.database.java.viewholder.CommentViewHolder;
import java.util.ArrayList;
import java.util.List;
// Listen for comments
mAdapter = new CommentAdapter(getContext(), mCommentsReference);
binding.recyclerPostComments.setAdapter(mAdapter);
}
@Override
public void onStop() {
super.onStop();
// Remove post value event listener
if (mPostListener != null) {
mPostReference.removeEventListener(mPostListener);
}
// Clean up comments listener
mAdapter.cleanupListener();
}
private void postComment() {
final String uid = getUid();
FirebaseDatabase.getInstance().getReference().child("users").child(uid)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user information
User user = dataSnapshot.getValue(User.class);
String authorName = user.username;
// Create new comment object
String commentText = binding.fieldCommentText.getText().toString();
|
Comment comment = new Comment(uid, authorName, commentText);
|
firebase/quickstart-android
|
database/app/src/main/java/com/google/firebase/quickstart/database/java/PostDetailFragment.java
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Comment.java
// @IgnoreExtraProperties
// public class Comment {
//
// public String uid;
// public String author;
// public String text;
//
// public Comment() {
// // Default constructor required for calls to DataSnapshot.getValue(Comment.class)
// }
//
// public Comment(String uid, String author, String text) {
// this.uid = uid;
// this.author = author;
// this.text = text;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Post.java
// @IgnoreExtraProperties
// public class Post {
//
// public String uid;
// public String author;
// public String title;
// public String body;
// public int starCount = 0;
// public Map<String, Boolean> stars = new HashMap<>();
//
// public Post() {
// // Default constructor required for calls to DataSnapshot.getValue(Post.class)
// }
//
// public Post(String uid, String author, String title, String body) {
// this.uid = uid;
// this.author = author;
// this.title = title;
// this.body = body;
// }
//
// @Exclude
// public Map<String, Object> toMap() {
// HashMap<String, Object> result = new HashMap<>();
// result.put("uid", uid);
// result.put("author", author);
// result.put("title", title);
// result.put("body", body);
// result.put("starCount", starCount);
// result.put("stars", stars);
//
// return result;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/User.java
// @IgnoreExtraProperties
// public class User {
//
// public String username;
// public String email;
//
// public User() {
// // Default constructor required for calls to DataSnapshot.getValue(User.class)
// }
//
// public User(String username, String email) {
// this.username = username;
// this.email = email;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/viewholder/CommentViewHolder.java
// public class CommentViewHolder extends RecyclerView.ViewHolder {
// public TextView authorView;
// public TextView bodyView;
//
// public CommentViewHolder(View itemView) {
// super(itemView);
// authorView = itemView.findViewById(R.id.commentAuthor);
// bodyView = itemView.findViewById(R.id.commentBody);
// }
// }
|
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentPostDetailBinding;
import com.google.firebase.quickstart.database.java.models.Comment;
import com.google.firebase.quickstart.database.java.models.Post;
import com.google.firebase.quickstart.database.java.models.User;
import com.google.firebase.quickstart.database.java.viewholder.CommentViewHolder;
import java.util.ArrayList;
import java.util.List;
|
}
private void postComment() {
final String uid = getUid();
FirebaseDatabase.getInstance().getReference().child("users").child(uid)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user information
User user = dataSnapshot.getValue(User.class);
String authorName = user.username;
// Create new comment object
String commentText = binding.fieldCommentText.getText().toString();
Comment comment = new Comment(uid, authorName, commentText);
// Push the comment, it will appear in the list
mCommentsReference.push().setValue(comment);
// Clear the field
binding.fieldCommentText.setText(null);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Comment.java
// @IgnoreExtraProperties
// public class Comment {
//
// public String uid;
// public String author;
// public String text;
//
// public Comment() {
// // Default constructor required for calls to DataSnapshot.getValue(Comment.class)
// }
//
// public Comment(String uid, String author, String text) {
// this.uid = uid;
// this.author = author;
// this.text = text;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Post.java
// @IgnoreExtraProperties
// public class Post {
//
// public String uid;
// public String author;
// public String title;
// public String body;
// public int starCount = 0;
// public Map<String, Boolean> stars = new HashMap<>();
//
// public Post() {
// // Default constructor required for calls to DataSnapshot.getValue(Post.class)
// }
//
// public Post(String uid, String author, String title, String body) {
// this.uid = uid;
// this.author = author;
// this.title = title;
// this.body = body;
// }
//
// @Exclude
// public Map<String, Object> toMap() {
// HashMap<String, Object> result = new HashMap<>();
// result.put("uid", uid);
// result.put("author", author);
// result.put("title", title);
// result.put("body", body);
// result.put("starCount", starCount);
// result.put("stars", stars);
//
// return result;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/User.java
// @IgnoreExtraProperties
// public class User {
//
// public String username;
// public String email;
//
// public User() {
// // Default constructor required for calls to DataSnapshot.getValue(User.class)
// }
//
// public User(String username, String email) {
// this.username = username;
// this.email = email;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/viewholder/CommentViewHolder.java
// public class CommentViewHolder extends RecyclerView.ViewHolder {
// public TextView authorView;
// public TextView bodyView;
//
// public CommentViewHolder(View itemView) {
// super(itemView);
// authorView = itemView.findViewById(R.id.commentAuthor);
// bodyView = itemView.findViewById(R.id.commentBody);
// }
// }
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/PostDetailFragment.java
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentPostDetailBinding;
import com.google.firebase.quickstart.database.java.models.Comment;
import com.google.firebase.quickstart.database.java.models.Post;
import com.google.firebase.quickstart.database.java.models.User;
import com.google.firebase.quickstart.database.java.viewholder.CommentViewHolder;
import java.util.ArrayList;
import java.util.List;
}
private void postComment() {
final String uid = getUid();
FirebaseDatabase.getInstance().getReference().child("users").child(uid)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user information
User user = dataSnapshot.getValue(User.class);
String authorName = user.username;
// Create new comment object
String commentText = binding.fieldCommentText.getText().toString();
Comment comment = new Comment(uid, authorName, commentText);
// Push the comment, it will appear in the list
mCommentsReference.push().setValue(comment);
// Clear the field
binding.fieldCommentText.setText(null);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
|
private static class CommentAdapter extends RecyclerView.Adapter<CommentViewHolder> {
|
firebase/quickstart-android
|
database/app/src/main/java/com/google/firebase/quickstart/database/java/viewholder/PostViewHolder.java
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Post.java
// @IgnoreExtraProperties
// public class Post {
//
// public String uid;
// public String author;
// public String title;
// public String body;
// public int starCount = 0;
// public Map<String, Boolean> stars = new HashMap<>();
//
// public Post() {
// // Default constructor required for calls to DataSnapshot.getValue(Post.class)
// }
//
// public Post(String uid, String author, String title, String body) {
// this.uid = uid;
// this.author = author;
// this.title = title;
// this.body = body;
// }
//
// @Exclude
// public Map<String, Object> toMap() {
// HashMap<String, Object> result = new HashMap<>();
// result.put("uid", uid);
// result.put("author", author);
// result.put("title", title);
// result.put("body", body);
// result.put("starCount", starCount);
// result.put("stars", stars);
//
// return result;
// }
//
// }
|
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.java.models.Post;
|
package com.google.firebase.quickstart.database.java.viewholder;
public class PostViewHolder extends RecyclerView.ViewHolder {
public TextView titleView;
public TextView authorView;
public ImageView starView;
public TextView numStarsView;
public TextView bodyView;
public PostViewHolder(View itemView) {
super(itemView);
titleView = itemView.findViewById(R.id.postTitle);
authorView = itemView.findViewById(R.id.postAuthor);
starView = itemView.findViewById(R.id.star);
numStarsView = itemView.findViewById(R.id.postNumStars);
bodyView = itemView.findViewById(R.id.postBody);
}
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Post.java
// @IgnoreExtraProperties
// public class Post {
//
// public String uid;
// public String author;
// public String title;
// public String body;
// public int starCount = 0;
// public Map<String, Boolean> stars = new HashMap<>();
//
// public Post() {
// // Default constructor required for calls to DataSnapshot.getValue(Post.class)
// }
//
// public Post(String uid, String author, String title, String body) {
// this.uid = uid;
// this.author = author;
// this.title = title;
// this.body = body;
// }
//
// @Exclude
// public Map<String, Object> toMap() {
// HashMap<String, Object> result = new HashMap<>();
// result.put("uid", uid);
// result.put("author", author);
// result.put("title", title);
// result.put("body", body);
// result.put("starCount", starCount);
// result.put("stars", stars);
//
// return result;
// }
//
// }
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/viewholder/PostViewHolder.java
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.java.models.Post;
package com.google.firebase.quickstart.database.java.viewholder;
public class PostViewHolder extends RecyclerView.ViewHolder {
public TextView titleView;
public TextView authorView;
public ImageView starView;
public TextView numStarsView;
public TextView bodyView;
public PostViewHolder(View itemView) {
super(itemView);
titleView = itemView.findViewById(R.id.postTitle);
authorView = itemView.findViewById(R.id.postAuthor);
starView = itemView.findViewById(R.id.star);
numStarsView = itemView.findViewById(R.id.postNumStars);
bodyView = itemView.findViewById(R.id.postBody);
}
|
public void bindToPost(Post post, View.OnClickListener starClickListener) {
|
firebase/quickstart-android
|
database/app/src/main/java/com/google/firebase/quickstart/database/java/NewPostFragment.java
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Post.java
// @IgnoreExtraProperties
// public class Post {
//
// public String uid;
// public String author;
// public String title;
// public String body;
// public int starCount = 0;
// public Map<String, Boolean> stars = new HashMap<>();
//
// public Post() {
// // Default constructor required for calls to DataSnapshot.getValue(Post.class)
// }
//
// public Post(String uid, String author, String title, String body) {
// this.uid = uid;
// this.author = author;
// this.title = title;
// this.body = body;
// }
//
// @Exclude
// public Map<String, Object> toMap() {
// HashMap<String, Object> result = new HashMap<>();
// result.put("uid", uid);
// result.put("author", author);
// result.put("title", title);
// result.put("body", body);
// result.put("starCount", starCount);
// result.put("stars", stars);
//
// return result;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/User.java
// @IgnoreExtraProperties
// public class User {
//
// public String username;
// public String email;
//
// public User() {
// // Default constructor required for calls to DataSnapshot.getValue(User.class)
// }
//
// public User(String username, String email) {
// this.username = username;
// this.email = email;
// }
//
// }
|
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.navigation.fragment.NavHostFragment;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentNewPostBinding;
import com.google.firebase.quickstart.database.java.models.Post;
import com.google.firebase.quickstart.database.java.models.User;
import java.util.HashMap;
import java.util.Map;
|
}
});
}
private void submitPost() {
final String title = binding.fieldTitle.getText().toString();
final String body = binding.fieldBody.getText().toString();
// Title is required
if (TextUtils.isEmpty(title)) {
binding.fieldTitle.setError(REQUIRED);
return;
}
// Body is required
if (TextUtils.isEmpty(body)) {
binding.fieldBody.setError(REQUIRED);
return;
}
// Disable button so there are no multi-posts
setEditingEnabled(false);
Toast.makeText(getContext(), "Posting...", Toast.LENGTH_SHORT).show();
final String userId = getUid();
mDatabase.child("users").child(userId).addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// Get user value
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Post.java
// @IgnoreExtraProperties
// public class Post {
//
// public String uid;
// public String author;
// public String title;
// public String body;
// public int starCount = 0;
// public Map<String, Boolean> stars = new HashMap<>();
//
// public Post() {
// // Default constructor required for calls to DataSnapshot.getValue(Post.class)
// }
//
// public Post(String uid, String author, String title, String body) {
// this.uid = uid;
// this.author = author;
// this.title = title;
// this.body = body;
// }
//
// @Exclude
// public Map<String, Object> toMap() {
// HashMap<String, Object> result = new HashMap<>();
// result.put("uid", uid);
// result.put("author", author);
// result.put("title", title);
// result.put("body", body);
// result.put("starCount", starCount);
// result.put("stars", stars);
//
// return result;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/User.java
// @IgnoreExtraProperties
// public class User {
//
// public String username;
// public String email;
//
// public User() {
// // Default constructor required for calls to DataSnapshot.getValue(User.class)
// }
//
// public User(String username, String email) {
// this.username = username;
// this.email = email;
// }
//
// }
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/NewPostFragment.java
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.navigation.fragment.NavHostFragment;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentNewPostBinding;
import com.google.firebase.quickstart.database.java.models.Post;
import com.google.firebase.quickstart.database.java.models.User;
import java.util.HashMap;
import java.util.Map;
}
});
}
private void submitPost() {
final String title = binding.fieldTitle.getText().toString();
final String body = binding.fieldBody.getText().toString();
// Title is required
if (TextUtils.isEmpty(title)) {
binding.fieldTitle.setError(REQUIRED);
return;
}
// Body is required
if (TextUtils.isEmpty(body)) {
binding.fieldBody.setError(REQUIRED);
return;
}
// Disable button so there are no multi-posts
setEditingEnabled(false);
Toast.makeText(getContext(), "Posting...", Toast.LENGTH_SHORT).show();
final String userId = getUid();
mDatabase.child("users").child(userId).addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// Get user value
|
User user = dataSnapshot.getValue(User.class);
|
firebase/quickstart-android
|
database/app/src/main/java/com/google/firebase/quickstart/database/java/NewPostFragment.java
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Post.java
// @IgnoreExtraProperties
// public class Post {
//
// public String uid;
// public String author;
// public String title;
// public String body;
// public int starCount = 0;
// public Map<String, Boolean> stars = new HashMap<>();
//
// public Post() {
// // Default constructor required for calls to DataSnapshot.getValue(Post.class)
// }
//
// public Post(String uid, String author, String title, String body) {
// this.uid = uid;
// this.author = author;
// this.title = title;
// this.body = body;
// }
//
// @Exclude
// public Map<String, Object> toMap() {
// HashMap<String, Object> result = new HashMap<>();
// result.put("uid", uid);
// result.put("author", author);
// result.put("title", title);
// result.put("body", body);
// result.put("starCount", starCount);
// result.put("stars", stars);
//
// return result;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/User.java
// @IgnoreExtraProperties
// public class User {
//
// public String username;
// public String email;
//
// public User() {
// // Default constructor required for calls to DataSnapshot.getValue(User.class)
// }
//
// public User(String username, String email) {
// this.username = username;
// this.email = email;
// }
//
// }
|
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.navigation.fragment.NavHostFragment;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentNewPostBinding;
import com.google.firebase.quickstart.database.java.models.Post;
import com.google.firebase.quickstart.database.java.models.User;
import java.util.HashMap;
import java.util.Map;
|
writeNewPost(userId, user.username, title, body);
}
setEditingEnabled(true);
NavHostFragment.findNavController(NewPostFragment.this)
.navigate(R.id.action_NewPostFragment_to_MainFragment);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
setEditingEnabled(true);
}
});
}
private void setEditingEnabled(boolean enabled) {
binding.fieldTitle.setEnabled(enabled);
binding.fieldBody.setEnabled(enabled);
if (enabled) {
binding.fabSubmitPost.show();
} else {
binding.fabSubmitPost.hide();
}
}
private void writeNewPost(String userId, String username, String title, String body) {
// Create new post at /user-posts/$userid/$postid and at
// /posts/$postid simultaneously
String key = mDatabase.child("posts").push().getKey();
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/Post.java
// @IgnoreExtraProperties
// public class Post {
//
// public String uid;
// public String author;
// public String title;
// public String body;
// public int starCount = 0;
// public Map<String, Boolean> stars = new HashMap<>();
//
// public Post() {
// // Default constructor required for calls to DataSnapshot.getValue(Post.class)
// }
//
// public Post(String uid, String author, String title, String body) {
// this.uid = uid;
// this.author = author;
// this.title = title;
// this.body = body;
// }
//
// @Exclude
// public Map<String, Object> toMap() {
// HashMap<String, Object> result = new HashMap<>();
// result.put("uid", uid);
// result.put("author", author);
// result.put("title", title);
// result.put("body", body);
// result.put("starCount", starCount);
// result.put("stars", stars);
//
// return result;
// }
//
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/User.java
// @IgnoreExtraProperties
// public class User {
//
// public String username;
// public String email;
//
// public User() {
// // Default constructor required for calls to DataSnapshot.getValue(User.class)
// }
//
// public User(String username, String email) {
// this.username = username;
// this.email = email;
// }
//
// }
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/NewPostFragment.java
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.navigation.fragment.NavHostFragment;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentNewPostBinding;
import com.google.firebase.quickstart.database.java.models.Post;
import com.google.firebase.quickstart.database.java.models.User;
import java.util.HashMap;
import java.util.Map;
writeNewPost(userId, user.username, title, body);
}
setEditingEnabled(true);
NavHostFragment.findNavController(NewPostFragment.this)
.navigate(R.id.action_NewPostFragment_to_MainFragment);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
setEditingEnabled(true);
}
});
}
private void setEditingEnabled(boolean enabled) {
binding.fieldTitle.setEnabled(enabled);
binding.fieldBody.setEnabled(enabled);
if (enabled) {
binding.fabSubmitPost.show();
} else {
binding.fabSubmitPost.hide();
}
}
private void writeNewPost(String userId, String username, String title, String body) {
// Create new post at /user-posts/$userid/$postid and at
// /posts/$postid simultaneously
String key = mDatabase.child("posts").push().getKey();
|
Post post = new Post(userId, username, title, body);
|
firebase/quickstart-android
|
database/app/src/main/java/com/google/firebase/quickstart/database/java/MainFragment.java
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/MyPostsFragment.java
// public class MyPostsFragment extends PostListFragment {
//
// public MyPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // All my posts
// return databaseReference.child("user-posts")
// .child(getUid());
// }
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/MyTopPostsFragment.java
// public class MyTopPostsFragment extends PostListFragment {
//
// public MyTopPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // My top posts by number of stars
// String myUserId = getUid();
// Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId)
// .orderByChild("starCount");
//
// return myTopPostsQuery;
// }
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/RecentPostsFragment.java
// public class RecentPostsFragment extends PostListFragment {
//
// public RecentPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // [START recent_posts_query]
// // Last 100 posts, these are automatically the 100 most recent
// // due to sorting by push() keys
// Query recentPostsQuery = databaseReference.child("posts")
// .limitToFirst(100);
// // [END recent_posts_query]
//
// return recentPostsQuery;
// }
// }
|
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentMainBinding;
import com.google.firebase.quickstart.database.java.listfragments.MyPostsFragment;
import com.google.firebase.quickstart.database.java.listfragments.MyTopPostsFragment;
import com.google.firebase.quickstart.database.java.listfragments.RecentPostsFragment;
|
package com.google.firebase.quickstart.database.java;
public class MainFragment extends Fragment {
private FragmentMainBinding binding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentMainBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
// Create the adapter that will return a fragment for each section
FragmentStateAdapter mPagerAdapter = new FragmentStateAdapter(getParentFragmentManager(),
getViewLifecycleOwner().getLifecycle()) {
private final Fragment[] mFragments = new Fragment[]{
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/MyPostsFragment.java
// public class MyPostsFragment extends PostListFragment {
//
// public MyPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // All my posts
// return databaseReference.child("user-posts")
// .child(getUid());
// }
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/MyTopPostsFragment.java
// public class MyTopPostsFragment extends PostListFragment {
//
// public MyTopPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // My top posts by number of stars
// String myUserId = getUid();
// Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId)
// .orderByChild("starCount");
//
// return myTopPostsQuery;
// }
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/RecentPostsFragment.java
// public class RecentPostsFragment extends PostListFragment {
//
// public RecentPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // [START recent_posts_query]
// // Last 100 posts, these are automatically the 100 most recent
// // due to sorting by push() keys
// Query recentPostsQuery = databaseReference.child("posts")
// .limitToFirst(100);
// // [END recent_posts_query]
//
// return recentPostsQuery;
// }
// }
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/MainFragment.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentMainBinding;
import com.google.firebase.quickstart.database.java.listfragments.MyPostsFragment;
import com.google.firebase.quickstart.database.java.listfragments.MyTopPostsFragment;
import com.google.firebase.quickstart.database.java.listfragments.RecentPostsFragment;
package com.google.firebase.quickstart.database.java;
public class MainFragment extends Fragment {
private FragmentMainBinding binding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentMainBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
// Create the adapter that will return a fragment for each section
FragmentStateAdapter mPagerAdapter = new FragmentStateAdapter(getParentFragmentManager(),
getViewLifecycleOwner().getLifecycle()) {
private final Fragment[] mFragments = new Fragment[]{
|
new RecentPostsFragment(),
|
firebase/quickstart-android
|
database/app/src/main/java/com/google/firebase/quickstart/database/java/MainFragment.java
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/MyPostsFragment.java
// public class MyPostsFragment extends PostListFragment {
//
// public MyPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // All my posts
// return databaseReference.child("user-posts")
// .child(getUid());
// }
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/MyTopPostsFragment.java
// public class MyTopPostsFragment extends PostListFragment {
//
// public MyTopPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // My top posts by number of stars
// String myUserId = getUid();
// Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId)
// .orderByChild("starCount");
//
// return myTopPostsQuery;
// }
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/RecentPostsFragment.java
// public class RecentPostsFragment extends PostListFragment {
//
// public RecentPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // [START recent_posts_query]
// // Last 100 posts, these are automatically the 100 most recent
// // due to sorting by push() keys
// Query recentPostsQuery = databaseReference.child("posts")
// .limitToFirst(100);
// // [END recent_posts_query]
//
// return recentPostsQuery;
// }
// }
|
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentMainBinding;
import com.google.firebase.quickstart.database.java.listfragments.MyPostsFragment;
import com.google.firebase.quickstart.database.java.listfragments.MyTopPostsFragment;
import com.google.firebase.quickstart.database.java.listfragments.RecentPostsFragment;
|
package com.google.firebase.quickstart.database.java;
public class MainFragment extends Fragment {
private FragmentMainBinding binding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentMainBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
// Create the adapter that will return a fragment for each section
FragmentStateAdapter mPagerAdapter = new FragmentStateAdapter(getParentFragmentManager(),
getViewLifecycleOwner().getLifecycle()) {
private final Fragment[] mFragments = new Fragment[]{
new RecentPostsFragment(),
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/MyPostsFragment.java
// public class MyPostsFragment extends PostListFragment {
//
// public MyPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // All my posts
// return databaseReference.child("user-posts")
// .child(getUid());
// }
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/MyTopPostsFragment.java
// public class MyTopPostsFragment extends PostListFragment {
//
// public MyTopPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // My top posts by number of stars
// String myUserId = getUid();
// Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId)
// .orderByChild("starCount");
//
// return myTopPostsQuery;
// }
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/RecentPostsFragment.java
// public class RecentPostsFragment extends PostListFragment {
//
// public RecentPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // [START recent_posts_query]
// // Last 100 posts, these are automatically the 100 most recent
// // due to sorting by push() keys
// Query recentPostsQuery = databaseReference.child("posts")
// .limitToFirst(100);
// // [END recent_posts_query]
//
// return recentPostsQuery;
// }
// }
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/MainFragment.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentMainBinding;
import com.google.firebase.quickstart.database.java.listfragments.MyPostsFragment;
import com.google.firebase.quickstart.database.java.listfragments.MyTopPostsFragment;
import com.google.firebase.quickstart.database.java.listfragments.RecentPostsFragment;
package com.google.firebase.quickstart.database.java;
public class MainFragment extends Fragment {
private FragmentMainBinding binding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentMainBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
// Create the adapter that will return a fragment for each section
FragmentStateAdapter mPagerAdapter = new FragmentStateAdapter(getParentFragmentManager(),
getViewLifecycleOwner().getLifecycle()) {
private final Fragment[] mFragments = new Fragment[]{
new RecentPostsFragment(),
|
new MyPostsFragment(),
|
firebase/quickstart-android
|
database/app/src/main/java/com/google/firebase/quickstart/database/java/MainFragment.java
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/MyPostsFragment.java
// public class MyPostsFragment extends PostListFragment {
//
// public MyPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // All my posts
// return databaseReference.child("user-posts")
// .child(getUid());
// }
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/MyTopPostsFragment.java
// public class MyTopPostsFragment extends PostListFragment {
//
// public MyTopPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // My top posts by number of stars
// String myUserId = getUid();
// Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId)
// .orderByChild("starCount");
//
// return myTopPostsQuery;
// }
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/RecentPostsFragment.java
// public class RecentPostsFragment extends PostListFragment {
//
// public RecentPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // [START recent_posts_query]
// // Last 100 posts, these are automatically the 100 most recent
// // due to sorting by push() keys
// Query recentPostsQuery = databaseReference.child("posts")
// .limitToFirst(100);
// // [END recent_posts_query]
//
// return recentPostsQuery;
// }
// }
|
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentMainBinding;
import com.google.firebase.quickstart.database.java.listfragments.MyPostsFragment;
import com.google.firebase.quickstart.database.java.listfragments.MyTopPostsFragment;
import com.google.firebase.quickstart.database.java.listfragments.RecentPostsFragment;
|
package com.google.firebase.quickstart.database.java;
public class MainFragment extends Fragment {
private FragmentMainBinding binding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentMainBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
// Create the adapter that will return a fragment for each section
FragmentStateAdapter mPagerAdapter = new FragmentStateAdapter(getParentFragmentManager(),
getViewLifecycleOwner().getLifecycle()) {
private final Fragment[] mFragments = new Fragment[]{
new RecentPostsFragment(),
new MyPostsFragment(),
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/MyPostsFragment.java
// public class MyPostsFragment extends PostListFragment {
//
// public MyPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // All my posts
// return databaseReference.child("user-posts")
// .child(getUid());
// }
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/MyTopPostsFragment.java
// public class MyTopPostsFragment extends PostListFragment {
//
// public MyTopPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // My top posts by number of stars
// String myUserId = getUid();
// Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId)
// .orderByChild("starCount");
//
// return myTopPostsQuery;
// }
// }
//
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/listfragments/RecentPostsFragment.java
// public class RecentPostsFragment extends PostListFragment {
//
// public RecentPostsFragment() {}
//
// @Override
// public Query getQuery(DatabaseReference databaseReference) {
// // [START recent_posts_query]
// // Last 100 posts, these are automatically the 100 most recent
// // due to sorting by push() keys
// Query recentPostsQuery = databaseReference.child("posts")
// .limitToFirst(100);
// // [END recent_posts_query]
//
// return recentPostsQuery;
// }
// }
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/MainFragment.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentMainBinding;
import com.google.firebase.quickstart.database.java.listfragments.MyPostsFragment;
import com.google.firebase.quickstart.database.java.listfragments.MyTopPostsFragment;
import com.google.firebase.quickstart.database.java.listfragments.RecentPostsFragment;
package com.google.firebase.quickstart.database.java;
public class MainFragment extends Fragment {
private FragmentMainBinding binding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentMainBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
// Create the adapter that will return a fragment for each section
FragmentStateAdapter mPagerAdapter = new FragmentStateAdapter(getParentFragmentManager(),
getViewLifecycleOwner().getLifecycle()) {
private final Fragment[] mFragments = new Fragment[]{
new RecentPostsFragment(),
new MyPostsFragment(),
|
new MyTopPostsFragment(),
|
firebase/quickstart-android
|
firestore/app/src/main/java/com/google/firebase/example/fireeats/java/RatingDialogFragment.java
|
// Path: firestore/app/src/main/java/com/google/firebase/example/fireeats/java/model/Rating.java
// public class Rating {
//
// private String userId;
// private String userName;
// private double rating;
// private String text;
// private @ServerTimestamp Date timestamp;
//
// public Rating() {}
//
// public Rating(FirebaseUser user, double rating, String text) {
// this.userId = user.getUid();
// this.userName = user.getDisplayName();
// if (TextUtils.isEmpty(this.userName)) {
// this.userName = user.getEmail();
// }
//
// this.rating = rating;
// this.text = text;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public double getRating() {
// return rating;
// }
//
// public void setRating(double rating) {
// this.rating = rating;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
// }
|
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.example.fireeats.R;
import com.google.firebase.example.fireeats.databinding.DialogRatingBinding;
import com.google.firebase.example.fireeats.java.model.Rating;
import me.zhanghai.android.materialratingbar.MaterialRatingBar;
|
package com.google.firebase.example.fireeats.java;
/**
* Dialog Fragment containing rating form.
*/
public class RatingDialogFragment extends DialogFragment implements View.OnClickListener {
public static final String TAG = "RatingDialog";
private DialogRatingBinding mBinding;
interface RatingListener {
|
// Path: firestore/app/src/main/java/com/google/firebase/example/fireeats/java/model/Rating.java
// public class Rating {
//
// private String userId;
// private String userName;
// private double rating;
// private String text;
// private @ServerTimestamp Date timestamp;
//
// public Rating() {}
//
// public Rating(FirebaseUser user, double rating, String text) {
// this.userId = user.getUid();
// this.userName = user.getDisplayName();
// if (TextUtils.isEmpty(this.userName)) {
// this.userName = user.getEmail();
// }
//
// this.rating = rating;
// this.text = text;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public double getRating() {
// return rating;
// }
//
// public void setRating(double rating) {
// this.rating = rating;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
// }
// Path: firestore/app/src/main/java/com/google/firebase/example/fireeats/java/RatingDialogFragment.java
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.example.fireeats.R;
import com.google.firebase.example.fireeats.databinding.DialogRatingBinding;
import com.google.firebase.example.fireeats.java.model.Rating;
import me.zhanghai.android.materialratingbar.MaterialRatingBar;
package com.google.firebase.example.fireeats.java;
/**
* Dialog Fragment containing rating form.
*/
public class RatingDialogFragment extends DialogFragment implements View.OnClickListener {
public static final String TAG = "RatingDialog";
private DialogRatingBinding mBinding;
interface RatingListener {
|
void onRating(Rating rating);
|
firebase/quickstart-android
|
firestore/app/src/main/java/com/google/firebase/example/fireeats/java/RestaurantDetailFragment.java
|
// Path: firestore/app/src/main/java/com/google/firebase/example/fireeats/java/model/Rating.java
// public class Rating {
//
// private String userId;
// private String userName;
// private double rating;
// private String text;
// private @ServerTimestamp Date timestamp;
//
// public Rating() {}
//
// public Rating(FirebaseUser user, double rating, String text) {
// this.userId = user.getUid();
// this.userName = user.getDisplayName();
// if (TextUtils.isEmpty(this.userName)) {
// this.userName = user.getEmail();
// }
//
// this.rating = rating;
// this.text = text;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public double getRating() {
// return rating;
// }
//
// public void setRating(double rating) {
// this.rating = rating;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
// }
//
// Path: firestore/app/src/main/java/com/google/firebase/example/fireeats/java/model/Restaurant.java
// @IgnoreExtraProperties
// public class Restaurant {
//
// public static final String FIELD_CITY = "city";
// public static final String FIELD_CATEGORY = "category";
// public static final String FIELD_PRICE = "price";
// public static final String FIELD_POPULARITY = "numRatings";
// public static final String FIELD_AVG_RATING = "avgRating";
//
// private String name;
// private String city;
// private String category;
// private String photo;
// private int price;
// private int numRatings;
// private double avgRating;
//
// public Restaurant() {}
//
// public Restaurant(String name, String city, String category, String photo,
// int price, int numRatings, double avgRating) {
// this.name = name;
// this.city = city;
// this.category = category;
// this.photo = photo;
// this.price = price;
// this.numRatings = numRatings;
// this.avgRating = avgRating;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getCategory() {
// return category;
// }
//
// public void setCategory(String category) {
// this.category = category;
// }
//
// public String getPhoto() {
// return photo;
// }
//
// public void setPhoto(String photo) {
// this.photo = photo;
// }
//
// public int getPrice() {
// return price;
// }
//
// public void setPrice(int price) {
// this.price = price;
// }
//
// public int getNumRatings() {
// return numRatings;
// }
//
// public void setNumRatings(int numRatings) {
// this.numRatings = numRatings;
// }
//
// public double getAvgRating() {
// return avgRating;
// }
//
// public void setAvgRating(double avgRating) {
// this.avgRating = avgRating;
// }
// }
|
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.example.fireeats.R;
import com.google.firebase.example.fireeats.databinding.FragmentRestaurantDetailBinding;
import com.google.firebase.example.fireeats.java.adapter.RatingAdapter;
import com.google.firebase.example.fireeats.java.model.Rating;
import com.google.firebase.example.fireeats.java.model.Restaurant;
import com.google.firebase.example.fireeats.java.util.RestaurantUtil;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.ListenerRegistration;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.Transaction;
|
@Override
public void onStart() {
super.onStart();
mRatingAdapter.startListening();
mRestaurantRegistration = mRestaurantRef.addSnapshotListener(this);
}
@Override
public void onStop() {
super.onStop();
mRatingAdapter.stopListening();
if (mRestaurantRegistration != null) {
mRestaurantRegistration.remove();
mRestaurantRegistration = null;
}
}
/**
* Listener for the Restaurant document ({@link #mRestaurantRef}).
*/
@Override
public void onEvent(DocumentSnapshot snapshot, FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "restaurant:onEvent", e);
return;
}
|
// Path: firestore/app/src/main/java/com/google/firebase/example/fireeats/java/model/Rating.java
// public class Rating {
//
// private String userId;
// private String userName;
// private double rating;
// private String text;
// private @ServerTimestamp Date timestamp;
//
// public Rating() {}
//
// public Rating(FirebaseUser user, double rating, String text) {
// this.userId = user.getUid();
// this.userName = user.getDisplayName();
// if (TextUtils.isEmpty(this.userName)) {
// this.userName = user.getEmail();
// }
//
// this.rating = rating;
// this.text = text;
// }
//
// public String getUserId() {
// return userId;
// }
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public double getRating() {
// return rating;
// }
//
// public void setRating(double rating) {
// this.rating = rating;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public Date getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Date timestamp) {
// this.timestamp = timestamp;
// }
// }
//
// Path: firestore/app/src/main/java/com/google/firebase/example/fireeats/java/model/Restaurant.java
// @IgnoreExtraProperties
// public class Restaurant {
//
// public static final String FIELD_CITY = "city";
// public static final String FIELD_CATEGORY = "category";
// public static final String FIELD_PRICE = "price";
// public static final String FIELD_POPULARITY = "numRatings";
// public static final String FIELD_AVG_RATING = "avgRating";
//
// private String name;
// private String city;
// private String category;
// private String photo;
// private int price;
// private int numRatings;
// private double avgRating;
//
// public Restaurant() {}
//
// public Restaurant(String name, String city, String category, String photo,
// int price, int numRatings, double avgRating) {
// this.name = name;
// this.city = city;
// this.category = category;
// this.photo = photo;
// this.price = price;
// this.numRatings = numRatings;
// this.avgRating = avgRating;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getCategory() {
// return category;
// }
//
// public void setCategory(String category) {
// this.category = category;
// }
//
// public String getPhoto() {
// return photo;
// }
//
// public void setPhoto(String photo) {
// this.photo = photo;
// }
//
// public int getPrice() {
// return price;
// }
//
// public void setPrice(int price) {
// this.price = price;
// }
//
// public int getNumRatings() {
// return numRatings;
// }
//
// public void setNumRatings(int numRatings) {
// this.numRatings = numRatings;
// }
//
// public double getAvgRating() {
// return avgRating;
// }
//
// public void setAvgRating(double avgRating) {
// this.avgRating = avgRating;
// }
// }
// Path: firestore/app/src/main/java/com/google/firebase/example/fireeats/java/RestaurantDetailFragment.java
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.example.fireeats.R;
import com.google.firebase.example.fireeats.databinding.FragmentRestaurantDetailBinding;
import com.google.firebase.example.fireeats.java.adapter.RatingAdapter;
import com.google.firebase.example.fireeats.java.model.Rating;
import com.google.firebase.example.fireeats.java.model.Restaurant;
import com.google.firebase.example.fireeats.java.util.RestaurantUtil;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.ListenerRegistration;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.Transaction;
@Override
public void onStart() {
super.onStart();
mRatingAdapter.startListening();
mRestaurantRegistration = mRestaurantRef.addSnapshotListener(this);
}
@Override
public void onStop() {
super.onStop();
mRatingAdapter.stopListening();
if (mRestaurantRegistration != null) {
mRestaurantRegistration.remove();
mRestaurantRegistration = null;
}
}
/**
* Listener for the Restaurant document ({@link #mRestaurantRef}).
*/
@Override
public void onEvent(DocumentSnapshot snapshot, FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "restaurant:onEvent", e);
return;
}
|
onRestaurantLoaded(snapshot.toObject(Restaurant.class));
|
firebase/quickstart-android
|
database/app/src/main/java/com/google/firebase/quickstart/database/java/SignInFragment.java
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/User.java
// @IgnoreExtraProperties
// public class User {
//
// public String username;
// public String email;
//
// public User() {
// // Default constructor required for calls to DataSnapshot.getValue(User.class)
// }
//
// public User(String username, String email) {
// this.username = username;
// this.email = email;
// }
//
// }
|
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentSignInBinding;
import com.google.firebase.quickstart.database.java.models.User;
|
}
private String usernameFromEmail(String email) {
if (email.contains("@")) {
return email.split("@")[0];
} else {
return email;
}
}
private boolean validateForm() {
boolean result = true;
if (TextUtils.isEmpty(binding.fieldEmail.getText().toString())) {
binding.fieldEmail.setError("Required");
result = false;
} else {
binding.fieldEmail.setError(null);
}
if (TextUtils.isEmpty(binding.fieldPassword.getText().toString())) {
binding.fieldPassword.setError("Required");
result = false;
} else {
binding.fieldPassword.setError(null);
}
return result;
}
private void writeNewUser(String userId, String name, String email) {
|
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/models/User.java
// @IgnoreExtraProperties
// public class User {
//
// public String username;
// public String email;
//
// public User() {
// // Default constructor required for calls to DataSnapshot.getValue(User.class)
// }
//
// public User(String username, String email) {
// this.username = username;
// this.email = email;
// }
//
// }
// Path: database/app/src/main/java/com/google/firebase/quickstart/database/java/SignInFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.databinding.FragmentSignInBinding;
import com.google.firebase.quickstart.database.java.models.User;
}
private String usernameFromEmail(String email) {
if (email.contains("@")) {
return email.split("@")[0];
} else {
return email;
}
}
private boolean validateForm() {
boolean result = true;
if (TextUtils.isEmpty(binding.fieldEmail.getText().toString())) {
binding.fieldEmail.setError("Required");
result = false;
} else {
binding.fieldEmail.setError(null);
}
if (TextUtils.isEmpty(binding.fieldPassword.getText().toString())) {
binding.fieldPassword.setError("Required");
result = false;
} else {
binding.fieldPassword.setError(null);
}
return result;
}
private void writeNewUser(String userId, String name, String email) {
|
User user = new User(name, email);
|
firebase/quickstart-android
|
firestore/app/src/main/java/com/google/firebase/example/fireeats/java/FilterDialogFragment.java
|
// Path: firestore/app/src/main/java/com/google/firebase/example/fireeats/java/model/Restaurant.java
// @IgnoreExtraProperties
// public class Restaurant {
//
// public static final String FIELD_CITY = "city";
// public static final String FIELD_CATEGORY = "category";
// public static final String FIELD_PRICE = "price";
// public static final String FIELD_POPULARITY = "numRatings";
// public static final String FIELD_AVG_RATING = "avgRating";
//
// private String name;
// private String city;
// private String category;
// private String photo;
// private int price;
// private int numRatings;
// private double avgRating;
//
// public Restaurant() {}
//
// public Restaurant(String name, String city, String category, String photo,
// int price, int numRatings, double avgRating) {
// this.name = name;
// this.city = city;
// this.category = category;
// this.photo = photo;
// this.price = price;
// this.numRatings = numRatings;
// this.avgRating = avgRating;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getCategory() {
// return category;
// }
//
// public void setCategory(String category) {
// this.category = category;
// }
//
// public String getPhoto() {
// return photo;
// }
//
// public void setPhoto(String photo) {
// this.photo = photo;
// }
//
// public int getPrice() {
// return price;
// }
//
// public void setPrice(int price) {
// this.price = price;
// }
//
// public int getNumRatings() {
// return numRatings;
// }
//
// public void setNumRatings(int numRatings) {
// this.numRatings = numRatings;
// }
//
// public double getAvgRating() {
// return avgRating;
// }
//
// public void setAvgRating(double avgRating) {
// this.avgRating = avgRating;
// }
// }
|
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Spinner;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import com.google.firebase.example.fireeats.R;
import com.google.firebase.example.fireeats.databinding.DialogFiltersBinding;
import com.google.firebase.example.fireeats.java.model.Restaurant;
import com.google.firebase.firestore.Query;
|
}
}
@Nullable
private String getSelectedCity() {
String selected = (String) mBinding.spinnerCity.getSelectedItem();
if (getString(R.string.value_any_city).equals(selected)) {
return null;
} else {
return selected;
}
}
private int getSelectedPrice() {
String selected = (String) mBinding.spinnerPrice.getSelectedItem();
if (selected.equals(getString(R.string.price_1))) {
return 1;
} else if (selected.equals(getString(R.string.price_2))) {
return 2;
} else if (selected.equals(getString(R.string.price_3))) {
return 3;
} else {
return -1;
}
}
@Nullable
private String getSelectedSortBy() {
String selected = (String) mBinding.spinnerSort.getSelectedItem();
if (getString(R.string.sort_by_rating).equals(selected)) {
|
// Path: firestore/app/src/main/java/com/google/firebase/example/fireeats/java/model/Restaurant.java
// @IgnoreExtraProperties
// public class Restaurant {
//
// public static final String FIELD_CITY = "city";
// public static final String FIELD_CATEGORY = "category";
// public static final String FIELD_PRICE = "price";
// public static final String FIELD_POPULARITY = "numRatings";
// public static final String FIELD_AVG_RATING = "avgRating";
//
// private String name;
// private String city;
// private String category;
// private String photo;
// private int price;
// private int numRatings;
// private double avgRating;
//
// public Restaurant() {}
//
// public Restaurant(String name, String city, String category, String photo,
// int price, int numRatings, double avgRating) {
// this.name = name;
// this.city = city;
// this.category = category;
// this.photo = photo;
// this.price = price;
// this.numRatings = numRatings;
// this.avgRating = avgRating;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getCity() {
// return city;
// }
//
// public void setCity(String city) {
// this.city = city;
// }
//
// public String getCategory() {
// return category;
// }
//
// public void setCategory(String category) {
// this.category = category;
// }
//
// public String getPhoto() {
// return photo;
// }
//
// public void setPhoto(String photo) {
// this.photo = photo;
// }
//
// public int getPrice() {
// return price;
// }
//
// public void setPrice(int price) {
// this.price = price;
// }
//
// public int getNumRatings() {
// return numRatings;
// }
//
// public void setNumRatings(int numRatings) {
// this.numRatings = numRatings;
// }
//
// public double getAvgRating() {
// return avgRating;
// }
//
// public void setAvgRating(double avgRating) {
// this.avgRating = avgRating;
// }
// }
// Path: firestore/app/src/main/java/com/google/firebase/example/fireeats/java/FilterDialogFragment.java
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Spinner;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import com.google.firebase.example.fireeats.R;
import com.google.firebase.example.fireeats.databinding.DialogFiltersBinding;
import com.google.firebase.example.fireeats.java.model.Restaurant;
import com.google.firebase.firestore.Query;
}
}
@Nullable
private String getSelectedCity() {
String selected = (String) mBinding.spinnerCity.getSelectedItem();
if (getString(R.string.value_any_city).equals(selected)) {
return null;
} else {
return selected;
}
}
private int getSelectedPrice() {
String selected = (String) mBinding.spinnerPrice.getSelectedItem();
if (selected.equals(getString(R.string.price_1))) {
return 1;
} else if (selected.equals(getString(R.string.price_2))) {
return 2;
} else if (selected.equals(getString(R.string.price_3))) {
return 3;
} else {
return -1;
}
}
@Nullable
private String getSelectedSortBy() {
String selected = (String) mBinding.spinnerSort.getSelectedItem();
if (getString(R.string.sort_by_rating).equals(selected)) {
|
return Restaurant.FIELD_AVG_RATING;
|
alex73/OSMemory
|
src/org/alex73/osmemory/XMLReader.java
|
// Path: src/osm/xmldatatypes/Member.java
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlType(name = "")
// @XmlRootElement(name = "member")
// public class Member {
//
// @XmlAttribute(name = "type", required = true)
// @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
// protected String type;
// @XmlAttribute(name = "ref", required = true)
// protected long ref;
// @XmlAttribute(name = "role")
// protected String role;
//
// /**
// * Gets the value of the type property.
// *
// * @return
// * possible object is
// * {@link String }
// *
// */
// public String getType() {
// return type;
// }
//
// /**
// * Sets the value of the type property.
// *
// * @param value
// * allowed object is
// * {@link String }
// *
// */
// public void setType(String value) {
// this.type = value;
// }
//
// /**
// * Gets the value of the ref property.
// *
// */
// public long getRef() {
// return ref;
// }
//
// /**
// * Sets the value of the ref property.
// *
// */
// public void setRef(long value) {
// this.ref = value;
// }
//
// /**
// * Gets the value of the role property.
// *
// * @return
// * possible object is
// * {@link String }
// *
// */
// public String getRole() {
// return role;
// }
//
// /**
// * Sets the value of the role property.
// *
// * @param value
// * allowed object is
// * {@link String }
// *
// */
// public void setRole(String value) {
// this.role = value;
// }
//
// }
|
import java.io.File;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import osm.xmldatatypes.Member;
import com.vividsolutions.jts.geom.Envelope;
|
ns[i] = nodes.get(i);
}
OsmWay result = new OsmWay(id, driver.tags.size(), ns, userCode);
boolean inside = false;
for (int i = 0; i < ns.length; i++) {
if (storage.getNodeById(ns[i]) != null) {
inside = true;
break;
}
}
if (inside) {
applyTags(driver, result);
storage.ways.add(result);
}
}
public void updateWay(UPDATE_MODE mode, long id, long[] nodes, Map<String, String> tags, String user) {
if (mode == UPDATE_MODE.DELETE) {
storage.removeWay(id);
} else {
short userCode = storage.getUsersPack().getTagCode(user);
OsmWay w = new OsmWay(id, tags.size(), nodes, userCode);
applyTags(tags, w);
storage.addWay(w);
}
}
/**
* Add all relations.
*/
|
// Path: src/osm/xmldatatypes/Member.java
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlType(name = "")
// @XmlRootElement(name = "member")
// public class Member {
//
// @XmlAttribute(name = "type", required = true)
// @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
// protected String type;
// @XmlAttribute(name = "ref", required = true)
// protected long ref;
// @XmlAttribute(name = "role")
// protected String role;
//
// /**
// * Gets the value of the type property.
// *
// * @return
// * possible object is
// * {@link String }
// *
// */
// public String getType() {
// return type;
// }
//
// /**
// * Sets the value of the type property.
// *
// * @param value
// * allowed object is
// * {@link String }
// *
// */
// public void setType(String value) {
// this.type = value;
// }
//
// /**
// * Gets the value of the ref property.
// *
// */
// public long getRef() {
// return ref;
// }
//
// /**
// * Sets the value of the ref property.
// *
// */
// public void setRef(long value) {
// this.ref = value;
// }
//
// /**
// * Gets the value of the role property.
// *
// * @return
// * possible object is
// * {@link String }
// *
// */
// public String getRole() {
// return role;
// }
//
// /**
// * Sets the value of the role property.
// *
// * @param value
// * allowed object is
// * {@link String }
// *
// */
// public void setRole(String value) {
// this.role = value;
// }
//
// }
// Path: src/org/alex73/osmemory/XMLReader.java
import java.io.File;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import osm.xmldatatypes.Member;
import com.vividsolutions.jts.geom.Envelope;
ns[i] = nodes.get(i);
}
OsmWay result = new OsmWay(id, driver.tags.size(), ns, userCode);
boolean inside = false;
for (int i = 0; i < ns.length; i++) {
if (storage.getNodeById(ns[i]) != null) {
inside = true;
break;
}
}
if (inside) {
applyTags(driver, result);
storage.ways.add(result);
}
}
public void updateWay(UPDATE_MODE mode, long id, long[] nodes, Map<String, String> tags, String user) {
if (mode == UPDATE_MODE.DELETE) {
storage.removeWay(id);
} else {
short userCode = storage.getUsersPack().getTagCode(user);
OsmWay w = new OsmWay(id, tags.size(), nodes, userCode);
applyTags(tags, w);
storage.addWay(w);
}
}
/**
* Add all relations.
*/
|
void createRelation(XMLDriver driver, long id, List<Member> members, String user) {
|
alex73/OSMemory
|
src/org/alex73/osmemory/geometry/Fast.java
|
// Path: src/org/alex73/osmemory/IOsmNode.java
// public interface IOsmNode extends IOsmObject {
// public static final double DIVIDER = 0.0000001;
//
// /**
// * Get latitude as int, i.e. multiplied by 10000000.
// */
// int getLat();
//
// /**
// * Get longitude as int, i.e. multiplied by 10000000.
// */
// int getLon();
//
// /**
// * Get latitude as double, like 53.9.
// */
// double getLatitude();
//
// /**
// * Get latitude as double, like 27.566667.
// */
// double getLongitude();
// }
|
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Polygon;
import org.alex73.osmemory.IOsmNode;
import com.vividsolutions.jts.geom.Envelope;
|
/**************************************************************************
OSMemory library for OSM data processing.
Copyright (C) 2014 Aleś Bułojčyk <[email protected]>
This 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 software 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 org.alex73.osmemory.geometry;
/**
* Some base operations for cells.
*/
public class Fast {
public static final int PARTS_COUNT_BYXY = 20;
protected final int minx, maxx, miny, maxy, stepx, stepy;
protected final Geometry polygon;
protected final Cell[][] cached;
public Fast(Geometry polygon) {
if (polygon == null) {
throw new IllegalArgumentException();
}
this.polygon = polygon;
Envelope bo = polygon.getEnvelopeInternal();
|
// Path: src/org/alex73/osmemory/IOsmNode.java
// public interface IOsmNode extends IOsmObject {
// public static final double DIVIDER = 0.0000001;
//
// /**
// * Get latitude as int, i.e. multiplied by 10000000.
// */
// int getLat();
//
// /**
// * Get longitude as int, i.e. multiplied by 10000000.
// */
// int getLon();
//
// /**
// * Get latitude as double, like 53.9.
// */
// double getLatitude();
//
// /**
// * Get latitude as double, like 27.566667.
// */
// double getLongitude();
// }
// Path: src/org/alex73/osmemory/geometry/Fast.java
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Polygon;
import org.alex73.osmemory.IOsmNode;
import com.vividsolutions.jts.geom.Envelope;
/**************************************************************************
OSMemory library for OSM data processing.
Copyright (C) 2014 Aleś Bułojčyk <[email protected]>
This 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 software 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 org.alex73.osmemory.geometry;
/**
* Some base operations for cells.
*/
public class Fast {
public static final int PARTS_COUNT_BYXY = 20;
protected final int minx, maxx, miny, maxy, stepx, stepy;
protected final Geometry polygon;
protected final Cell[][] cached;
public Fast(Geometry polygon) {
if (polygon == null) {
throw new IllegalArgumentException();
}
this.polygon = polygon;
Envelope bo = polygon.getEnvelopeInternal();
|
minx = (int) (bo.getMinX() / IOsmNode.DIVIDER) - 1;
|
alex73/OSMemory
|
src/org/alex73/osmemory/geometry/IExtendedObject.java
|
// Path: src/org/alex73/osmemory/IOsmNode.java
// public interface IOsmNode extends IOsmObject {
// public static final double DIVIDER = 0.0000001;
//
// /**
// * Get latitude as int, i.e. multiplied by 10000000.
// */
// int getLat();
//
// /**
// * Get longitude as int, i.e. multiplied by 10000000.
// */
// int getLon();
//
// /**
// * Get latitude as double, like 53.9.
// */
// double getLatitude();
//
// /**
// * Get latitude as double, like 27.566667.
// */
// double getLongitude();
// }
//
// Path: src/org/alex73/osmemory/IOsmObject.java
// public interface IOsmObject {
// public static final int TYPE_NODE = 1;
// public static final int TYPE_WAY = 2;
// public static final int TYPE_RELATION = 3;
//
// /**
// * Object type: 1-node, 2-way,3-relation. It should be int instead enum for performance optimization.
// */
// int getType();
//
// boolean isNode();
//
// boolean isWay();
//
// boolean isRelation();
//
// /**
// * Object ID.
// */
// long getId();
//
// /**
// * Object ID as object.
// */
// IOsmObjectID getObjectID();
//
// /**
// * Check if object has tag.
// */
// boolean hasTag(short tagKey);
//
// /**
// * Get tags list.
// */
// short[] getTags();
//
// /**
// * Check if object has tag. This operation is much slower than {@link #hasTag(short)}.
// */
// boolean hasTag(String tagName, MemoryStorage storage);
//
// /**
// * Get tag value.
// */
// String getTag(short tagKey);
//
// /**
// * Get tag value. This operation is much slower than {@link #getTag(short)}.
// */
// String getTag(String tagName, MemoryStorage storage);
//
// Map<String, String> extractTags(MemoryStorage storage);
//
// /**
// * Get object code, like n123, w75, r51.
// */
// String getObjectCode();
//
// /**
// * Get user code.
// */
// short getUser();
//
// /**
// * Get user name.
// */
// String getUser(MemoryStorage storage);
//
// static String getNodeCode(long nodeId) {
// return "n" + nodeId;
// }
//
// static String getWayCode(long wayId) {
// return "w" + wayId;
// }
//
// static String getRelationCode(long relationId) {
// return "r" + relationId;
// }
// }
|
import org.alex73.osmemory.IOsmNode;
import org.alex73.osmemory.IOsmObject;
|
/**************************************************************************
OSMemory library for OSM data processing.
Copyright (C) 2014 Aleś Bułojčyk <[email protected]>
This 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 software 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 org.alex73.osmemory.geometry;
/**
* Interface for all External... that have bounds.
*/
public interface IExtendedObject {
BoundingBox getBoundingBox();
|
// Path: src/org/alex73/osmemory/IOsmNode.java
// public interface IOsmNode extends IOsmObject {
// public static final double DIVIDER = 0.0000001;
//
// /**
// * Get latitude as int, i.e. multiplied by 10000000.
// */
// int getLat();
//
// /**
// * Get longitude as int, i.e. multiplied by 10000000.
// */
// int getLon();
//
// /**
// * Get latitude as double, like 53.9.
// */
// double getLatitude();
//
// /**
// * Get latitude as double, like 27.566667.
// */
// double getLongitude();
// }
//
// Path: src/org/alex73/osmemory/IOsmObject.java
// public interface IOsmObject {
// public static final int TYPE_NODE = 1;
// public static final int TYPE_WAY = 2;
// public static final int TYPE_RELATION = 3;
//
// /**
// * Object type: 1-node, 2-way,3-relation. It should be int instead enum for performance optimization.
// */
// int getType();
//
// boolean isNode();
//
// boolean isWay();
//
// boolean isRelation();
//
// /**
// * Object ID.
// */
// long getId();
//
// /**
// * Object ID as object.
// */
// IOsmObjectID getObjectID();
//
// /**
// * Check if object has tag.
// */
// boolean hasTag(short tagKey);
//
// /**
// * Get tags list.
// */
// short[] getTags();
//
// /**
// * Check if object has tag. This operation is much slower than {@link #hasTag(short)}.
// */
// boolean hasTag(String tagName, MemoryStorage storage);
//
// /**
// * Get tag value.
// */
// String getTag(short tagKey);
//
// /**
// * Get tag value. This operation is much slower than {@link #getTag(short)}.
// */
// String getTag(String tagName, MemoryStorage storage);
//
// Map<String, String> extractTags(MemoryStorage storage);
//
// /**
// * Get object code, like n123, w75, r51.
// */
// String getObjectCode();
//
// /**
// * Get user code.
// */
// short getUser();
//
// /**
// * Get user name.
// */
// String getUser(MemoryStorage storage);
//
// static String getNodeCode(long nodeId) {
// return "n" + nodeId;
// }
//
// static String getWayCode(long wayId) {
// return "w" + wayId;
// }
//
// static String getRelationCode(long relationId) {
// return "r" + relationId;
// }
// }
// Path: src/org/alex73/osmemory/geometry/IExtendedObject.java
import org.alex73.osmemory.IOsmNode;
import org.alex73.osmemory.IOsmObject;
/**************************************************************************
OSMemory library for OSM data processing.
Copyright (C) 2014 Aleś Bułojčyk <[email protected]>
This 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 software 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 org.alex73.osmemory.geometry;
/**
* Interface for all External... that have bounds.
*/
public interface IExtendedObject {
BoundingBox getBoundingBox();
|
IOsmObject getObject();
|
alex73/OSMemory
|
src/org/alex73/osmemory/geometry/IExtendedObject.java
|
// Path: src/org/alex73/osmemory/IOsmNode.java
// public interface IOsmNode extends IOsmObject {
// public static final double DIVIDER = 0.0000001;
//
// /**
// * Get latitude as int, i.e. multiplied by 10000000.
// */
// int getLat();
//
// /**
// * Get longitude as int, i.e. multiplied by 10000000.
// */
// int getLon();
//
// /**
// * Get latitude as double, like 53.9.
// */
// double getLatitude();
//
// /**
// * Get latitude as double, like 27.566667.
// */
// double getLongitude();
// }
//
// Path: src/org/alex73/osmemory/IOsmObject.java
// public interface IOsmObject {
// public static final int TYPE_NODE = 1;
// public static final int TYPE_WAY = 2;
// public static final int TYPE_RELATION = 3;
//
// /**
// * Object type: 1-node, 2-way,3-relation. It should be int instead enum for performance optimization.
// */
// int getType();
//
// boolean isNode();
//
// boolean isWay();
//
// boolean isRelation();
//
// /**
// * Object ID.
// */
// long getId();
//
// /**
// * Object ID as object.
// */
// IOsmObjectID getObjectID();
//
// /**
// * Check if object has tag.
// */
// boolean hasTag(short tagKey);
//
// /**
// * Get tags list.
// */
// short[] getTags();
//
// /**
// * Check if object has tag. This operation is much slower than {@link #hasTag(short)}.
// */
// boolean hasTag(String tagName, MemoryStorage storage);
//
// /**
// * Get tag value.
// */
// String getTag(short tagKey);
//
// /**
// * Get tag value. This operation is much slower than {@link #getTag(short)}.
// */
// String getTag(String tagName, MemoryStorage storage);
//
// Map<String, String> extractTags(MemoryStorage storage);
//
// /**
// * Get object code, like n123, w75, r51.
// */
// String getObjectCode();
//
// /**
// * Get user code.
// */
// short getUser();
//
// /**
// * Get user name.
// */
// String getUser(MemoryStorage storage);
//
// static String getNodeCode(long nodeId) {
// return "n" + nodeId;
// }
//
// static String getWayCode(long wayId) {
// return "w" + wayId;
// }
//
// static String getRelationCode(long relationId) {
// return "r" + relationId;
// }
// }
|
import org.alex73.osmemory.IOsmNode;
import org.alex73.osmemory.IOsmObject;
|
/**************************************************************************
OSMemory library for OSM data processing.
Copyright (C) 2014 Aleś Bułojčyk <[email protected]>
This 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 software 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 org.alex73.osmemory.geometry;
/**
* Interface for all External... that have bounds.
*/
public interface IExtendedObject {
BoundingBox getBoundingBox();
IOsmObject getObject();
Boolean iterateNodes(NodesIterator iterator);
interface NodesIterator {
|
// Path: src/org/alex73/osmemory/IOsmNode.java
// public interface IOsmNode extends IOsmObject {
// public static final double DIVIDER = 0.0000001;
//
// /**
// * Get latitude as int, i.e. multiplied by 10000000.
// */
// int getLat();
//
// /**
// * Get longitude as int, i.e. multiplied by 10000000.
// */
// int getLon();
//
// /**
// * Get latitude as double, like 53.9.
// */
// double getLatitude();
//
// /**
// * Get latitude as double, like 27.566667.
// */
// double getLongitude();
// }
//
// Path: src/org/alex73/osmemory/IOsmObject.java
// public interface IOsmObject {
// public static final int TYPE_NODE = 1;
// public static final int TYPE_WAY = 2;
// public static final int TYPE_RELATION = 3;
//
// /**
// * Object type: 1-node, 2-way,3-relation. It should be int instead enum for performance optimization.
// */
// int getType();
//
// boolean isNode();
//
// boolean isWay();
//
// boolean isRelation();
//
// /**
// * Object ID.
// */
// long getId();
//
// /**
// * Object ID as object.
// */
// IOsmObjectID getObjectID();
//
// /**
// * Check if object has tag.
// */
// boolean hasTag(short tagKey);
//
// /**
// * Get tags list.
// */
// short[] getTags();
//
// /**
// * Check if object has tag. This operation is much slower than {@link #hasTag(short)}.
// */
// boolean hasTag(String tagName, MemoryStorage storage);
//
// /**
// * Get tag value.
// */
// String getTag(short tagKey);
//
// /**
// * Get tag value. This operation is much slower than {@link #getTag(short)}.
// */
// String getTag(String tagName, MemoryStorage storage);
//
// Map<String, String> extractTags(MemoryStorage storage);
//
// /**
// * Get object code, like n123, w75, r51.
// */
// String getObjectCode();
//
// /**
// * Get user code.
// */
// short getUser();
//
// /**
// * Get user name.
// */
// String getUser(MemoryStorage storage);
//
// static String getNodeCode(long nodeId) {
// return "n" + nodeId;
// }
//
// static String getWayCode(long wayId) {
// return "w" + wayId;
// }
//
// static String getRelationCode(long relationId) {
// return "r" + relationId;
// }
// }
// Path: src/org/alex73/osmemory/geometry/IExtendedObject.java
import org.alex73.osmemory.IOsmNode;
import org.alex73.osmemory.IOsmObject;
/**************************************************************************
OSMemory library for OSM data processing.
Copyright (C) 2014 Aleś Bułojčyk <[email protected]>
This 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 software 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 org.alex73.osmemory.geometry;
/**
* Interface for all External... that have bounds.
*/
public interface IExtendedObject {
BoundingBox getBoundingBox();
IOsmObject getObject();
Boolean iterateNodes(NodesIterator iterator);
interface NodesIterator {
|
Boolean processNode(IOsmNode node);
|
siddharth-sahoo/MDXQueryGenerator
|
src/main/java/com/tfsinc/ilabs/mdx/builder/member/FormatString.java
|
// Path: src/main/java/com/tfsinc/ilabs/olap/references/MDXReferences.java
// public class MDXReferences {
//
// // Query key words.
// public static final String SELECT = "SELECT ";
// public static final String ON = " ON ";
// public static final String FROM = " FROM ";
// public static final String WHERE = " WHERE ";
// public static final String NON_EMPTY = " NON EMPTY ";
// public static final String ORDER = " ORDER ";
// public static final String FORMAT_STRING = " FORMAT_STRING =";
// public static final String MEMBER = " MEMBER ";
// public static final String AS = " AS ";
// public static final String WITH = " WITH ";
//
// public static final char SEPARATOR = ',';
// public static final char SEPARATOR_CROSS = '*';
// public static final char DEFAULT_AXIS = '0';
//
// // Member specifiers.
// public static final char MEMBER_START = '[';
// public static final char MEMBER_END = ']';
// public static final char MEMBER_SET_START = '{';
// public static final char MEMBER_SET_END = '}';
// public static final char MEMBER_HIERARCHY_SEPARATOR = '.';
// public static final char MEMBER_SPECIFIER = '&';
//
// public static final char FUNCTION_START = '(';
// public static final char FUNCTION_END = ')';
//
// // Standard member terminology.
// public static final String MEASURES = "[Measures].";
//
// // Sort order types.
// public static final String ORDER_ASCENDING = " ASC ";
// public static final String ORDER_DESCENDING = " DESC ";
// public static final String ORDER_CUSTOM_ASCENDING = " BASC ";
// public static final String ORDER_CUSTOM_DESCENDING = " BDESC ";
//
// // Format string types.
// public static final String FORMAT_STRING_GENERAL_NUMBER = " \"General Number\" ";
// public static final String FORMAT_STRING_CURRENCY = " \"Currency\" ";
// public static final String FORMAT_STRING_FIXED = " \"Fixed\" ";
// public static final String FORMAT_STRING_STANDARD = " \"Standard\" ";
// public static final String FORMAT_STRING_PERCENT = " \"Percent\" ";
// public static final String FORMAT_STRING_SCIENTIFIC = " \"Scientific\" ";
// public static final String FORMAT_STRING_YES_NO = " \"Yes/No\" ";
// public static final String FORMAT_STRING_TRUE_FALSE = " \"True/False\" ";
// public static final String FORMAT_STRING_ON_OFF = " \"On/Off\" ";
//
// }
|
import com.tfsinc.ilabs.olap.references.MDXReferences;
|
package com.tfsinc.ilabs.mdx.builder.member;
/**
* Format string types used in MDX queries, particularly in
* calculated member types.
* @author siddharth.s
*/
public enum FormatString {
/**
* Displays the number with no thousand separator.
*/
GENERAL_NUMBER,
/**
* Displays the number with a thousand separator, if appropriate.
* Displays two digits to the right of the decimal separator.
* Output is based on system locale settings.
*/
CURRENCY,
/**
* Displays at least one digit to the left and two digits to
* the right of the decimal separator.
*/
FIXED,
/**
* Displays the number with thousand separator, at least one
* digit to the left and two digits to the right of the decimal separator.
*/
STANDARD,
/**
* Displays the number multiplied by 100 with a percent sign (%)
* appended to the right. Always displays two digits to the right
* of the decimal separator.
*/
PERCENT,
/**
* Uses standard scientific notation.
*/
SCIENTIFIC,
/**
* Displays No if the number is 0; otherwise, displays Yes.
*/
YES_NO,
/**
* Displays False if the number is 0; otherwise, displays True.
*/
TRUE_FALSE,
/**
* Displays Off if the number is 0; otherwise, displays On.
*/
ON_OFF;
/**
* @param formatString Format string enumeration type.
* @return Format string as is should appear in the MDX query.
*/
public static final String getFormatString(final FormatString formatString) {
switch (formatString) {
case CURRENCY:
|
// Path: src/main/java/com/tfsinc/ilabs/olap/references/MDXReferences.java
// public class MDXReferences {
//
// // Query key words.
// public static final String SELECT = "SELECT ";
// public static final String ON = " ON ";
// public static final String FROM = " FROM ";
// public static final String WHERE = " WHERE ";
// public static final String NON_EMPTY = " NON EMPTY ";
// public static final String ORDER = " ORDER ";
// public static final String FORMAT_STRING = " FORMAT_STRING =";
// public static final String MEMBER = " MEMBER ";
// public static final String AS = " AS ";
// public static final String WITH = " WITH ";
//
// public static final char SEPARATOR = ',';
// public static final char SEPARATOR_CROSS = '*';
// public static final char DEFAULT_AXIS = '0';
//
// // Member specifiers.
// public static final char MEMBER_START = '[';
// public static final char MEMBER_END = ']';
// public static final char MEMBER_SET_START = '{';
// public static final char MEMBER_SET_END = '}';
// public static final char MEMBER_HIERARCHY_SEPARATOR = '.';
// public static final char MEMBER_SPECIFIER = '&';
//
// public static final char FUNCTION_START = '(';
// public static final char FUNCTION_END = ')';
//
// // Standard member terminology.
// public static final String MEASURES = "[Measures].";
//
// // Sort order types.
// public static final String ORDER_ASCENDING = " ASC ";
// public static final String ORDER_DESCENDING = " DESC ";
// public static final String ORDER_CUSTOM_ASCENDING = " BASC ";
// public static final String ORDER_CUSTOM_DESCENDING = " BDESC ";
//
// // Format string types.
// public static final String FORMAT_STRING_GENERAL_NUMBER = " \"General Number\" ";
// public static final String FORMAT_STRING_CURRENCY = " \"Currency\" ";
// public static final String FORMAT_STRING_FIXED = " \"Fixed\" ";
// public static final String FORMAT_STRING_STANDARD = " \"Standard\" ";
// public static final String FORMAT_STRING_PERCENT = " \"Percent\" ";
// public static final String FORMAT_STRING_SCIENTIFIC = " \"Scientific\" ";
// public static final String FORMAT_STRING_YES_NO = " \"Yes/No\" ";
// public static final String FORMAT_STRING_TRUE_FALSE = " \"True/False\" ";
// public static final String FORMAT_STRING_ON_OFF = " \"On/Off\" ";
//
// }
// Path: src/main/java/com/tfsinc/ilabs/mdx/builder/member/FormatString.java
import com.tfsinc.ilabs.olap.references.MDXReferences;
package com.tfsinc.ilabs.mdx.builder.member;
/**
* Format string types used in MDX queries, particularly in
* calculated member types.
* @author siddharth.s
*/
public enum FormatString {
/**
* Displays the number with no thousand separator.
*/
GENERAL_NUMBER,
/**
* Displays the number with a thousand separator, if appropriate.
* Displays two digits to the right of the decimal separator.
* Output is based on system locale settings.
*/
CURRENCY,
/**
* Displays at least one digit to the left and two digits to
* the right of the decimal separator.
*/
FIXED,
/**
* Displays the number with thousand separator, at least one
* digit to the left and two digits to the right of the decimal separator.
*/
STANDARD,
/**
* Displays the number multiplied by 100 with a percent sign (%)
* appended to the right. Always displays two digits to the right
* of the decimal separator.
*/
PERCENT,
/**
* Uses standard scientific notation.
*/
SCIENTIFIC,
/**
* Displays No if the number is 0; otherwise, displays Yes.
*/
YES_NO,
/**
* Displays False if the number is 0; otherwise, displays True.
*/
TRUE_FALSE,
/**
* Displays Off if the number is 0; otherwise, displays On.
*/
ON_OFF;
/**
* @param formatString Format string enumeration type.
* @return Format string as is should appear in the MDX query.
*/
public static final String getFormatString(final FormatString formatString) {
switch (formatString) {
case CURRENCY:
|
return MDXReferences.FORMAT_STRING_CURRENCY;
|
siddharth-sahoo/MDXQueryGenerator
|
src/test/java/com/tfsinc/ilabs/mdx/test/IterationExample2.java
|
// Path: src/main/java/com/tfsinc/ilabs/olap/OlapClientManager.java
// public class OlapClientManager {
//
// /**
// * Root logger instance.
// */
// private static final Logger LOGGER = Logger.getLogger(
// OlapClientManager.class);
//
// /**
// * Initializes everything.
// * @param configFile Name and path of configuration file.
// */
// public static final void initialize(final String configFile) {
// OlapConfigReferences.initialize(configFile);
// OlapConnectionPoolManager.initialize(configFile);
// }
//
// /**
// * Shuts down everything.
// * @param forceClose Whether to close active connections forcibly.
// */
// public static final void shutdown(final boolean forceClose) {
// OlapConnectionPoolManager.shutdown(forceClose);
// }
//
// /**
// * @return An OLAP connection from the POOL.
// */
// public static WrappedOlapConnection getConnection() {
// return OlapConnectionPoolManager.getConnection();
// }
//
// /**
// * @param connection OLAP connection to be returned to the pool.
// * @return Whether the connection was returned successfully.
// */
// public static final boolean returnConnection(
// final WrappedOlapConnection connection) {
// return OlapConnectionPoolManager.returnConnection(connection);
// }
//
// /**
// * @param query String MDX query to be executed.
// * @return Cell set of the query.
// */
// public static final CellSet executeMdxQuery(final String query) {
// final WrappedOlapConnection connection = getConnection();
// try {
// final long start = System.currentTimeMillis();
// final CellSet cellSet = connection.getResource()
// .createStatement().executeOlapQuery(query);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Query execution time: " + (System.currentTimeMillis() - start) + " ms.");
// }
//
// returnConnection(connection);
// return cellSet;
// } catch (OlapException e) {
// LOGGER.error("Unable to execute query.", e);
// returnConnection(connection);
// return null;
// }
// }
//
// /**
// * @param query Parsed select MDX query.
// * @return Cell set of the query.
// */
// public static final CellSet executeMdxQuery(final SelectNode query) {
// final WrappedOlapConnection connection = getConnection();
// try {
// final long start = System.currentTimeMillis();
// final CellSet cellSet = connection.getResource()
// .createStatement().executeOlapQuery(query);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Query execution time: " + (System.currentTimeMillis() - start) + " ms.");
// }
// returnConnection(connection);
// return cellSet;
// } catch (OlapException e) {
// LOGGER.error("Unable to execute query.", e);
// returnConnection(connection);
// return null;
// }
// }
//
// }
|
import java.io.PrintWriter;
import java.util.List;
import org.apache.log4j.Logger;
import org.olap4j.Axis;
import org.olap4j.Cell;
import org.olap4j.CellSet;
import org.olap4j.CellSetAxis;
import org.olap4j.Position;
import org.olap4j.layout.CellSetFormatter;
import org.olap4j.layout.RectangularCellSetFormatter;
import org.olap4j.metadata.Member;
import com.tfsinc.ilabs.olap.OlapClientManager;
|
package com.tfsinc.ilabs.mdx.test;
public class IterationExample2 {
private static final Logger LOGGER = Logger.getLogger(IterationExample2.class);
private static final String QUERY_LOCAL =
"SELECT "
+ "{[Measures].[Internet Average Sales Amount], "
+ "[Measures].[Internet Gross Profit]} "
+ "ON 0, "
+ "NON EMPTY "
+ "([Date].[Date].[Date], "
+ "[Product].[Product].[Product], "
+ "[Sales Territory].[Sales Territory Region].[Sales Territory Region]) "
+ "ON 1 "
+ "FROM "
+ "(SELECT [Date].[Date].&[20110101] ON 0 "
+ "FROM [Adventure Works])";
private static final String QUERY =
"SELECT {[Measures].[Chats],[Measures].[InteractiveChats],[Measures].[WaitTime]} ON 0," +
" NON EMPTY ([DimScenario].[Scenario].CHILDREN,[DimQueue].[Queue].CHILDREN,[DimRuleCategory].[RuleCategory].CHILDREN) ON 1" +
" FROM (SELECT [DimTime].[Calendermonth].&[2014]&[7] ON 0 FROM (SELECT [DimClient].[Client].&[1015] ON 0 FROM [247OLAP]))";
public static void main(String[] args) {
|
// Path: src/main/java/com/tfsinc/ilabs/olap/OlapClientManager.java
// public class OlapClientManager {
//
// /**
// * Root logger instance.
// */
// private static final Logger LOGGER = Logger.getLogger(
// OlapClientManager.class);
//
// /**
// * Initializes everything.
// * @param configFile Name and path of configuration file.
// */
// public static final void initialize(final String configFile) {
// OlapConfigReferences.initialize(configFile);
// OlapConnectionPoolManager.initialize(configFile);
// }
//
// /**
// * Shuts down everything.
// * @param forceClose Whether to close active connections forcibly.
// */
// public static final void shutdown(final boolean forceClose) {
// OlapConnectionPoolManager.shutdown(forceClose);
// }
//
// /**
// * @return An OLAP connection from the POOL.
// */
// public static WrappedOlapConnection getConnection() {
// return OlapConnectionPoolManager.getConnection();
// }
//
// /**
// * @param connection OLAP connection to be returned to the pool.
// * @return Whether the connection was returned successfully.
// */
// public static final boolean returnConnection(
// final WrappedOlapConnection connection) {
// return OlapConnectionPoolManager.returnConnection(connection);
// }
//
// /**
// * @param query String MDX query to be executed.
// * @return Cell set of the query.
// */
// public static final CellSet executeMdxQuery(final String query) {
// final WrappedOlapConnection connection = getConnection();
// try {
// final long start = System.currentTimeMillis();
// final CellSet cellSet = connection.getResource()
// .createStatement().executeOlapQuery(query);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Query execution time: " + (System.currentTimeMillis() - start) + " ms.");
// }
//
// returnConnection(connection);
// return cellSet;
// } catch (OlapException e) {
// LOGGER.error("Unable to execute query.", e);
// returnConnection(connection);
// return null;
// }
// }
//
// /**
// * @param query Parsed select MDX query.
// * @return Cell set of the query.
// */
// public static final CellSet executeMdxQuery(final SelectNode query) {
// final WrappedOlapConnection connection = getConnection();
// try {
// final long start = System.currentTimeMillis();
// final CellSet cellSet = connection.getResource()
// .createStatement().executeOlapQuery(query);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Query execution time: " + (System.currentTimeMillis() - start) + " ms.");
// }
// returnConnection(connection);
// return cellSet;
// } catch (OlapException e) {
// LOGGER.error("Unable to execute query.", e);
// returnConnection(connection);
// return null;
// }
// }
//
// }
// Path: src/test/java/com/tfsinc/ilabs/mdx/test/IterationExample2.java
import java.io.PrintWriter;
import java.util.List;
import org.apache.log4j.Logger;
import org.olap4j.Axis;
import org.olap4j.Cell;
import org.olap4j.CellSet;
import org.olap4j.CellSetAxis;
import org.olap4j.Position;
import org.olap4j.layout.CellSetFormatter;
import org.olap4j.layout.RectangularCellSetFormatter;
import org.olap4j.metadata.Member;
import com.tfsinc.ilabs.olap.OlapClientManager;
package com.tfsinc.ilabs.mdx.test;
public class IterationExample2 {
private static final Logger LOGGER = Logger.getLogger(IterationExample2.class);
private static final String QUERY_LOCAL =
"SELECT "
+ "{[Measures].[Internet Average Sales Amount], "
+ "[Measures].[Internet Gross Profit]} "
+ "ON 0, "
+ "NON EMPTY "
+ "([Date].[Date].[Date], "
+ "[Product].[Product].[Product], "
+ "[Sales Territory].[Sales Territory Region].[Sales Territory Region]) "
+ "ON 1 "
+ "FROM "
+ "(SELECT [Date].[Date].&[20110101] ON 0 "
+ "FROM [Adventure Works])";
private static final String QUERY =
"SELECT {[Measures].[Chats],[Measures].[InteractiveChats],[Measures].[WaitTime]} ON 0," +
" NON EMPTY ([DimScenario].[Scenario].CHILDREN,[DimQueue].[Queue].CHILDREN,[DimRuleCategory].[RuleCategory].CHILDREN) ON 1" +
" FROM (SELECT [DimTime].[Calendermonth].&[2014]&[7] ON 0 FROM (SELECT [DimClient].[Client].&[1015] ON 0 FROM [247OLAP]))";
public static void main(String[] args) {
|
OlapClientManager.initialize("olapconfig.properties");
|
siddharth-sahoo/MDXQueryGenerator
|
src/main/java/com/tfsinc/ilabs/mdx/builder/dimension/DimensionSort.java
|
// Path: src/main/java/com/tfsinc/ilabs/olap/references/MDXReferences.java
// public class MDXReferences {
//
// // Query key words.
// public static final String SELECT = "SELECT ";
// public static final String ON = " ON ";
// public static final String FROM = " FROM ";
// public static final String WHERE = " WHERE ";
// public static final String NON_EMPTY = " NON EMPTY ";
// public static final String ORDER = " ORDER ";
// public static final String FORMAT_STRING = " FORMAT_STRING =";
// public static final String MEMBER = " MEMBER ";
// public static final String AS = " AS ";
// public static final String WITH = " WITH ";
//
// public static final char SEPARATOR = ',';
// public static final char SEPARATOR_CROSS = '*';
// public static final char DEFAULT_AXIS = '0';
//
// // Member specifiers.
// public static final char MEMBER_START = '[';
// public static final char MEMBER_END = ']';
// public static final char MEMBER_SET_START = '{';
// public static final char MEMBER_SET_END = '}';
// public static final char MEMBER_HIERARCHY_SEPARATOR = '.';
// public static final char MEMBER_SPECIFIER = '&';
//
// public static final char FUNCTION_START = '(';
// public static final char FUNCTION_END = ')';
//
// // Standard member terminology.
// public static final String MEASURES = "[Measures].";
//
// // Sort order types.
// public static final String ORDER_ASCENDING = " ASC ";
// public static final String ORDER_DESCENDING = " DESC ";
// public static final String ORDER_CUSTOM_ASCENDING = " BASC ";
// public static final String ORDER_CUSTOM_DESCENDING = " BDESC ";
//
// // Format string types.
// public static final String FORMAT_STRING_GENERAL_NUMBER = " \"General Number\" ";
// public static final String FORMAT_STRING_CURRENCY = " \"Currency\" ";
// public static final String FORMAT_STRING_FIXED = " \"Fixed\" ";
// public static final String FORMAT_STRING_STANDARD = " \"Standard\" ";
// public static final String FORMAT_STRING_PERCENT = " \"Percent\" ";
// public static final String FORMAT_STRING_SCIENTIFIC = " \"Scientific\" ";
// public static final String FORMAT_STRING_YES_NO = " \"Yes/No\" ";
// public static final String FORMAT_STRING_TRUE_FALSE = " \"True/False\" ";
// public static final String FORMAT_STRING_ON_OFF = " \"On/Off\" ";
//
// }
|
import com.tfsinc.ilabs.olap.references.MDXReferences;
|
package com.tfsinc.ilabs.mdx.builder.dimension;
public enum DimensionSort {
/**
* In ascending order considering the dimension hierarchy.
*/
ASCENDING,
/**
* In descending order considering dimension hierarchy.
*/
DESCENDING,
/**
* In ascending order with respect to custom numerical values.
*/
CUSTOM_ASCENDING,
/**
* In descending order with respect to custom numerical values.
*/
CUSTOM_DESCENDING;
/**
* @param sort Sort order type.
* @return MDX query equivalent.
*/
public static final String getMDXEquivalent(final DimensionSort sort) {
switch (sort) {
case ASCENDING :
|
// Path: src/main/java/com/tfsinc/ilabs/olap/references/MDXReferences.java
// public class MDXReferences {
//
// // Query key words.
// public static final String SELECT = "SELECT ";
// public static final String ON = " ON ";
// public static final String FROM = " FROM ";
// public static final String WHERE = " WHERE ";
// public static final String NON_EMPTY = " NON EMPTY ";
// public static final String ORDER = " ORDER ";
// public static final String FORMAT_STRING = " FORMAT_STRING =";
// public static final String MEMBER = " MEMBER ";
// public static final String AS = " AS ";
// public static final String WITH = " WITH ";
//
// public static final char SEPARATOR = ',';
// public static final char SEPARATOR_CROSS = '*';
// public static final char DEFAULT_AXIS = '0';
//
// // Member specifiers.
// public static final char MEMBER_START = '[';
// public static final char MEMBER_END = ']';
// public static final char MEMBER_SET_START = '{';
// public static final char MEMBER_SET_END = '}';
// public static final char MEMBER_HIERARCHY_SEPARATOR = '.';
// public static final char MEMBER_SPECIFIER = '&';
//
// public static final char FUNCTION_START = '(';
// public static final char FUNCTION_END = ')';
//
// // Standard member terminology.
// public static final String MEASURES = "[Measures].";
//
// // Sort order types.
// public static final String ORDER_ASCENDING = " ASC ";
// public static final String ORDER_DESCENDING = " DESC ";
// public static final String ORDER_CUSTOM_ASCENDING = " BASC ";
// public static final String ORDER_CUSTOM_DESCENDING = " BDESC ";
//
// // Format string types.
// public static final String FORMAT_STRING_GENERAL_NUMBER = " \"General Number\" ";
// public static final String FORMAT_STRING_CURRENCY = " \"Currency\" ";
// public static final String FORMAT_STRING_FIXED = " \"Fixed\" ";
// public static final String FORMAT_STRING_STANDARD = " \"Standard\" ";
// public static final String FORMAT_STRING_PERCENT = " \"Percent\" ";
// public static final String FORMAT_STRING_SCIENTIFIC = " \"Scientific\" ";
// public static final String FORMAT_STRING_YES_NO = " \"Yes/No\" ";
// public static final String FORMAT_STRING_TRUE_FALSE = " \"True/False\" ";
// public static final String FORMAT_STRING_ON_OFF = " \"On/Off\" ";
//
// }
// Path: src/main/java/com/tfsinc/ilabs/mdx/builder/dimension/DimensionSort.java
import com.tfsinc.ilabs.olap.references.MDXReferences;
package com.tfsinc.ilabs.mdx.builder.dimension;
public enum DimensionSort {
/**
* In ascending order considering the dimension hierarchy.
*/
ASCENDING,
/**
* In descending order considering dimension hierarchy.
*/
DESCENDING,
/**
* In ascending order with respect to custom numerical values.
*/
CUSTOM_ASCENDING,
/**
* In descending order with respect to custom numerical values.
*/
CUSTOM_DESCENDING;
/**
* @param sort Sort order type.
* @return MDX query equivalent.
*/
public static final String getMDXEquivalent(final DimensionSort sort) {
switch (sort) {
case ASCENDING :
|
return MDXReferences.ORDER_ASCENDING;
|
siddharth-sahoo/MDXQueryGenerator
|
src/test/java/com/tfsinc/ilabs/mdx/test/IterationExample.java
|
// Path: src/main/java/com/tfsinc/ilabs/olap/OlapClientManager.java
// public class OlapClientManager {
//
// /**
// * Root logger instance.
// */
// private static final Logger LOGGER = Logger.getLogger(
// OlapClientManager.class);
//
// /**
// * Initializes everything.
// * @param configFile Name and path of configuration file.
// */
// public static final void initialize(final String configFile) {
// OlapConfigReferences.initialize(configFile);
// OlapConnectionPoolManager.initialize(configFile);
// }
//
// /**
// * Shuts down everything.
// * @param forceClose Whether to close active connections forcibly.
// */
// public static final void shutdown(final boolean forceClose) {
// OlapConnectionPoolManager.shutdown(forceClose);
// }
//
// /**
// * @return An OLAP connection from the POOL.
// */
// public static WrappedOlapConnection getConnection() {
// return OlapConnectionPoolManager.getConnection();
// }
//
// /**
// * @param connection OLAP connection to be returned to the pool.
// * @return Whether the connection was returned successfully.
// */
// public static final boolean returnConnection(
// final WrappedOlapConnection connection) {
// return OlapConnectionPoolManager.returnConnection(connection);
// }
//
// /**
// * @param query String MDX query to be executed.
// * @return Cell set of the query.
// */
// public static final CellSet executeMdxQuery(final String query) {
// final WrappedOlapConnection connection = getConnection();
// try {
// final long start = System.currentTimeMillis();
// final CellSet cellSet = connection.getResource()
// .createStatement().executeOlapQuery(query);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Query execution time: " + (System.currentTimeMillis() - start) + " ms.");
// }
//
// returnConnection(connection);
// return cellSet;
// } catch (OlapException e) {
// LOGGER.error("Unable to execute query.", e);
// returnConnection(connection);
// return null;
// }
// }
//
// /**
// * @param query Parsed select MDX query.
// * @return Cell set of the query.
// */
// public static final CellSet executeMdxQuery(final SelectNode query) {
// final WrappedOlapConnection connection = getConnection();
// try {
// final long start = System.currentTimeMillis();
// final CellSet cellSet = connection.getResource()
// .createStatement().executeOlapQuery(query);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Query execution time: " + (System.currentTimeMillis() - start) + " ms.");
// }
// returnConnection(connection);
// return cellSet;
// } catch (OlapException e) {
// LOGGER.error("Unable to execute query.", e);
// returnConnection(connection);
// return null;
// }
// }
//
// }
|
import java.sql.SQLException;
import java.util.List;
import org.apache.log4j.Logger;
import org.olap4j.Axis;
import org.olap4j.Cell;
import org.olap4j.CellSet;
import org.olap4j.CellSetAxis;
import org.olap4j.Position;
import org.olap4j.metadata.Member;
import com.tfsinc.ilabs.olap.OlapClientManager;
|
package com.tfsinc.ilabs.mdx.test;
public class IterationExample {
private static final Logger LOGGER = Logger.getLogger(
IterationExample.class);
private static final void start() {
|
// Path: src/main/java/com/tfsinc/ilabs/olap/OlapClientManager.java
// public class OlapClientManager {
//
// /**
// * Root logger instance.
// */
// private static final Logger LOGGER = Logger.getLogger(
// OlapClientManager.class);
//
// /**
// * Initializes everything.
// * @param configFile Name and path of configuration file.
// */
// public static final void initialize(final String configFile) {
// OlapConfigReferences.initialize(configFile);
// OlapConnectionPoolManager.initialize(configFile);
// }
//
// /**
// * Shuts down everything.
// * @param forceClose Whether to close active connections forcibly.
// */
// public static final void shutdown(final boolean forceClose) {
// OlapConnectionPoolManager.shutdown(forceClose);
// }
//
// /**
// * @return An OLAP connection from the POOL.
// */
// public static WrappedOlapConnection getConnection() {
// return OlapConnectionPoolManager.getConnection();
// }
//
// /**
// * @param connection OLAP connection to be returned to the pool.
// * @return Whether the connection was returned successfully.
// */
// public static final boolean returnConnection(
// final WrappedOlapConnection connection) {
// return OlapConnectionPoolManager.returnConnection(connection);
// }
//
// /**
// * @param query String MDX query to be executed.
// * @return Cell set of the query.
// */
// public static final CellSet executeMdxQuery(final String query) {
// final WrappedOlapConnection connection = getConnection();
// try {
// final long start = System.currentTimeMillis();
// final CellSet cellSet = connection.getResource()
// .createStatement().executeOlapQuery(query);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Query execution time: " + (System.currentTimeMillis() - start) + " ms.");
// }
//
// returnConnection(connection);
// return cellSet;
// } catch (OlapException e) {
// LOGGER.error("Unable to execute query.", e);
// returnConnection(connection);
// return null;
// }
// }
//
// /**
// * @param query Parsed select MDX query.
// * @return Cell set of the query.
// */
// public static final CellSet executeMdxQuery(final SelectNode query) {
// final WrappedOlapConnection connection = getConnection();
// try {
// final long start = System.currentTimeMillis();
// final CellSet cellSet = connection.getResource()
// .createStatement().executeOlapQuery(query);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Query execution time: " + (System.currentTimeMillis() - start) + " ms.");
// }
// returnConnection(connection);
// return cellSet;
// } catch (OlapException e) {
// LOGGER.error("Unable to execute query.", e);
// returnConnection(connection);
// return null;
// }
// }
//
// }
// Path: src/test/java/com/tfsinc/ilabs/mdx/test/IterationExample.java
import java.sql.SQLException;
import java.util.List;
import org.apache.log4j.Logger;
import org.olap4j.Axis;
import org.olap4j.Cell;
import org.olap4j.CellSet;
import org.olap4j.CellSetAxis;
import org.olap4j.Position;
import org.olap4j.metadata.Member;
import com.tfsinc.ilabs.olap.OlapClientManager;
package com.tfsinc.ilabs.mdx.test;
public class IterationExample {
private static final Logger LOGGER = Logger.getLogger(
IterationExample.class);
private static final void start() {
|
OlapClientManager.initialize("olapconfig.properties");
|
siddharth-sahoo/MDXQueryGenerator
|
src/main/java/com/tfsinc/ilabs/olap/OlapClientManager.java
|
// Path: src/main/java/com/tfsinc/ilabs/olap/references/OlapConfigReferences.java
// public class OlapConfigReferences {
//
// /**
// * Configurations read from property file.
// */
// public static PropertyFileUtility CONFIG = null;
//
// /**
// * Root logger instance.
// */
// private static final Logger LOGGER = Logger.getLogger(
// OlapConfigReferences.class);
//
// /**
// * Reads the specified configuration file and keeps it in memory.
// * @param configFile Name of the configuration file to read.
// */
// public static final void initialize(final String configFile) {
// if (CONFIG == null) {
// synchronized (OlapConfigReferences.class) {
// if (CONFIG == null) {
// if (configFile == null || configFile.length() == 0) {
// LOGGER.error("Configuration file name specified"
// + " is null or blank. Exiting.");
// System.exit(1);
// }
//
// CONFIG = new PropertyFileUtility(configFile);
// LOGGER.info("Populated base configurations for OLAP cube.");
//
// loadDriver();
// }
// }
// }
// }
//
// /**
// * Loads the specified OLAP driver. Exits if the class is not found.
// */
// private static final void loadDriver() {
// try {
// Class.forName(CONFIG.getStringValue(
// PROPERTY_OLAP_DRIVER_CLASS,
// DEFAULT_OLAP_DRIVER_CLASS));
// } catch (ClassNotFoundException e) {
// LOGGER.error("Specified driver class is not found. Exiting.", e);
// System.exit(1);
// }
// }
//
// // Configuration properties
// public static final String PROPERTY_OLAP_DRIVER_CLASS = "OlapDriverClass";
// public static final String PROPERTY_OLAP_CONNECTION_URL = "OlapConnectionUrl";
// public static final String PROPERTY_VALIDATE_QUERY = "ValidateQuery";
// public static final String PROPERTY_DISPLAY_QUERY = "DisplayQuery";
// public static final String PROPERTY_MEASURE_AXIS = "MeasureAxis";
//
// // Default configurations
// public static final String DEFAULT_OLAP_DRIVER_CLASS = "org.olap4j.driver.xmla.XmlaOlap4jDriver";
// public static final String DEFAULT_OLAP_CONNECTION_URL = "jdbc:xmla:Server=http://"
// + "localhost/olap/msmdpump.dll";
// public static final boolean DEFAULT_VALIDATE_QUERY = true;
// public static final boolean DEFAULT_DISPLAY_QUERY = true;
// public static final String DEFAULT_MEASURE_AXIS = "COLUMNS";
//
// // Standard axes.
// private static final String AXIS_COLUMNS = "COLUMNS";
// private static final String AXIS_ROWS = "ROWS";
// private static final int AXIS_INDEX_COLUMNS = 0;
// private static final int AXIS_INDEX_ROWS = 1;
//
// /**
// * @param axis Standard axis name.
// * @return Corresponding axis index.
// */
// public static final int getAxisIndex(final String axis) {
// switch (axis.toUpperCase()) {
// case AXIS_COLUMNS :
// return AXIS_INDEX_COLUMNS;
// case AXIS_ROWS :
// return AXIS_INDEX_ROWS;
// default :
// throw new IllegalArgumentException("Unknown axis: " + axis);
// }
// }
//
// /**
// * @return Measure axis from configuration file.
// */
// public static final int getMeasureAxisIndex() {
// return getAxisIndex(CONFIG.getStringValue(
// PROPERTY_MEASURE_AXIS, DEFAULT_MEASURE_AXIS));
// }
//
// /**
// * @return Whether to validate the MDX query generated.
// */
// public static final boolean shouldValidateMdx() {
// return CONFIG.getBooleanValue(PROPERTY_VALIDATE_QUERY,
// DEFAULT_VALIDATE_QUERY);
// }
//
// /**
// * @return Whether to display the generated MDX query.
// */
// public static final boolean shouldDisplayMdx() {
// return CONFIG.getBooleanValue(PROPERTY_DISPLAY_QUERY,
// DEFAULT_DISPLAY_QUERY);
// }
//
// }
|
import org.apache.log4j.Logger;
import org.olap4j.CellSet;
import org.olap4j.OlapException;
import org.olap4j.mdx.SelectNode;
import com.tfsinc.ilabs.olap.references.OlapConfigReferences;
|
package com.tfsinc.ilabs.olap;
/**
* Base class for MDX query generator.
* @author siddharth.s
*/
public class OlapClientManager {
/**
* Root logger instance.
*/
private static final Logger LOGGER = Logger.getLogger(
OlapClientManager.class);
/**
* Initializes everything.
* @param configFile Name and path of configuration file.
*/
public static final void initialize(final String configFile) {
|
// Path: src/main/java/com/tfsinc/ilabs/olap/references/OlapConfigReferences.java
// public class OlapConfigReferences {
//
// /**
// * Configurations read from property file.
// */
// public static PropertyFileUtility CONFIG = null;
//
// /**
// * Root logger instance.
// */
// private static final Logger LOGGER = Logger.getLogger(
// OlapConfigReferences.class);
//
// /**
// * Reads the specified configuration file and keeps it in memory.
// * @param configFile Name of the configuration file to read.
// */
// public static final void initialize(final String configFile) {
// if (CONFIG == null) {
// synchronized (OlapConfigReferences.class) {
// if (CONFIG == null) {
// if (configFile == null || configFile.length() == 0) {
// LOGGER.error("Configuration file name specified"
// + " is null or blank. Exiting.");
// System.exit(1);
// }
//
// CONFIG = new PropertyFileUtility(configFile);
// LOGGER.info("Populated base configurations for OLAP cube.");
//
// loadDriver();
// }
// }
// }
// }
//
// /**
// * Loads the specified OLAP driver. Exits if the class is not found.
// */
// private static final void loadDriver() {
// try {
// Class.forName(CONFIG.getStringValue(
// PROPERTY_OLAP_DRIVER_CLASS,
// DEFAULT_OLAP_DRIVER_CLASS));
// } catch (ClassNotFoundException e) {
// LOGGER.error("Specified driver class is not found. Exiting.", e);
// System.exit(1);
// }
// }
//
// // Configuration properties
// public static final String PROPERTY_OLAP_DRIVER_CLASS = "OlapDriverClass";
// public static final String PROPERTY_OLAP_CONNECTION_URL = "OlapConnectionUrl";
// public static final String PROPERTY_VALIDATE_QUERY = "ValidateQuery";
// public static final String PROPERTY_DISPLAY_QUERY = "DisplayQuery";
// public static final String PROPERTY_MEASURE_AXIS = "MeasureAxis";
//
// // Default configurations
// public static final String DEFAULT_OLAP_DRIVER_CLASS = "org.olap4j.driver.xmla.XmlaOlap4jDriver";
// public static final String DEFAULT_OLAP_CONNECTION_URL = "jdbc:xmla:Server=http://"
// + "localhost/olap/msmdpump.dll";
// public static final boolean DEFAULT_VALIDATE_QUERY = true;
// public static final boolean DEFAULT_DISPLAY_QUERY = true;
// public static final String DEFAULT_MEASURE_AXIS = "COLUMNS";
//
// // Standard axes.
// private static final String AXIS_COLUMNS = "COLUMNS";
// private static final String AXIS_ROWS = "ROWS";
// private static final int AXIS_INDEX_COLUMNS = 0;
// private static final int AXIS_INDEX_ROWS = 1;
//
// /**
// * @param axis Standard axis name.
// * @return Corresponding axis index.
// */
// public static final int getAxisIndex(final String axis) {
// switch (axis.toUpperCase()) {
// case AXIS_COLUMNS :
// return AXIS_INDEX_COLUMNS;
// case AXIS_ROWS :
// return AXIS_INDEX_ROWS;
// default :
// throw new IllegalArgumentException("Unknown axis: " + axis);
// }
// }
//
// /**
// * @return Measure axis from configuration file.
// */
// public static final int getMeasureAxisIndex() {
// return getAxisIndex(CONFIG.getStringValue(
// PROPERTY_MEASURE_AXIS, DEFAULT_MEASURE_AXIS));
// }
//
// /**
// * @return Whether to validate the MDX query generated.
// */
// public static final boolean shouldValidateMdx() {
// return CONFIG.getBooleanValue(PROPERTY_VALIDATE_QUERY,
// DEFAULT_VALIDATE_QUERY);
// }
//
// /**
// * @return Whether to display the generated MDX query.
// */
// public static final boolean shouldDisplayMdx() {
// return CONFIG.getBooleanValue(PROPERTY_DISPLAY_QUERY,
// DEFAULT_DISPLAY_QUERY);
// }
//
// }
// Path: src/main/java/com/tfsinc/ilabs/olap/OlapClientManager.java
import org.apache.log4j.Logger;
import org.olap4j.CellSet;
import org.olap4j.OlapException;
import org.olap4j.mdx.SelectNode;
import com.tfsinc.ilabs.olap.references.OlapConfigReferences;
package com.tfsinc.ilabs.olap;
/**
* Base class for MDX query generator.
* @author siddharth.s
*/
public class OlapClientManager {
/**
* Root logger instance.
*/
private static final Logger LOGGER = Logger.getLogger(
OlapClientManager.class);
/**
* Initializes everything.
* @param configFile Name and path of configuration file.
*/
public static final void initialize(final String configFile) {
|
OlapConfigReferences.initialize(configFile);
|
siddharth-sahoo/MDXQueryGenerator
|
src/main/java/com/tfsinc/ilabs/mdx/builder/MDXValidator.java
|
// Path: src/main/java/com/tfsinc/ilabs/olap/OlapClientManager.java
// public class OlapClientManager {
//
// /**
// * Root logger instance.
// */
// private static final Logger LOGGER = Logger.getLogger(
// OlapClientManager.class);
//
// /**
// * Initializes everything.
// * @param configFile Name and path of configuration file.
// */
// public static final void initialize(final String configFile) {
// OlapConfigReferences.initialize(configFile);
// OlapConnectionPoolManager.initialize(configFile);
// }
//
// /**
// * Shuts down everything.
// * @param forceClose Whether to close active connections forcibly.
// */
// public static final void shutdown(final boolean forceClose) {
// OlapConnectionPoolManager.shutdown(forceClose);
// }
//
// /**
// * @return An OLAP connection from the POOL.
// */
// public static WrappedOlapConnection getConnection() {
// return OlapConnectionPoolManager.getConnection();
// }
//
// /**
// * @param connection OLAP connection to be returned to the pool.
// * @return Whether the connection was returned successfully.
// */
// public static final boolean returnConnection(
// final WrappedOlapConnection connection) {
// return OlapConnectionPoolManager.returnConnection(connection);
// }
//
// /**
// * @param query String MDX query to be executed.
// * @return Cell set of the query.
// */
// public static final CellSet executeMdxQuery(final String query) {
// final WrappedOlapConnection connection = getConnection();
// try {
// final long start = System.currentTimeMillis();
// final CellSet cellSet = connection.getResource()
// .createStatement().executeOlapQuery(query);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Query execution time: " + (System.currentTimeMillis() - start) + " ms.");
// }
//
// returnConnection(connection);
// return cellSet;
// } catch (OlapException e) {
// LOGGER.error("Unable to execute query.", e);
// returnConnection(connection);
// return null;
// }
// }
//
// /**
// * @param query Parsed select MDX query.
// * @return Cell set of the query.
// */
// public static final CellSet executeMdxQuery(final SelectNode query) {
// final WrappedOlapConnection connection = getConnection();
// try {
// final long start = System.currentTimeMillis();
// final CellSet cellSet = connection.getResource()
// .createStatement().executeOlapQuery(query);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Query execution time: " + (System.currentTimeMillis() - start) + " ms.");
// }
// returnConnection(connection);
// return cellSet;
// } catch (OlapException e) {
// LOGGER.error("Unable to execute query.", e);
// returnConnection(connection);
// return null;
// }
// }
//
// }
//
// Path: src/main/java/com/tfsinc/ilabs/olap/WrappedOlapConnection.java
// public final class WrappedOlapConnection implements WrappedResource<OlapConnection> {
//
// /**
// * OLAP connection which is wrapped.
// */
// private final OlapConnection connection;
//
// /**
// * Root logger instance.
// */
// private static final Logger LOGGER = Logger.getLogger(
// WrappedOlapConnection.class);
//
// // Constructor.
// public WrappedOlapConnection(final OlapConnection olapConnection) {
// connection = olapConnection;
// }
//
// /* (non-Javadoc)
// * @see com.awesome.pro.pool.WrappedResource#close()
// */
// public void close() {
// try {
// connection.close();
// } catch (SQLException e) {
// LOGGER.error("Error in closing OLAP connection.");
// System.exit(1);
// }
// }
//
// /* (non-Javadoc)
// * @see com.awesome.pro.pool.WrappedResource#isClosed()
// */
// public boolean isClosed() {
// try {
// return connection.isClosed();
// } catch (SQLException e) {
// return true;
// }
// }
//
// /* (non-Javadoc)
// * @see com.awesome.pro.pool.WrappedResource#getResource()
// */
// public OlapConnection getResource() {
// return connection;
// }
//
// }
|
import org.apache.log4j.Logger;
import org.olap4j.OlapException;
import org.olap4j.mdx.SelectNode;
import org.olap4j.mdx.parser.MdxParser;
import org.olap4j.mdx.parser.MdxValidator;
import com.tfsinc.ilabs.olap.OlapClientManager;
import com.tfsinc.ilabs.olap.WrappedOlapConnection;
|
package com.tfsinc.ilabs.mdx.builder;
/**
* Validates an MDX query.
* @author siddharth.s
*/
public class MDXValidator {
/**
* Root logger instance.
*/
private static final Logger LOGGER = Logger.getLogger(MDXValidator.class);
/**
* @param mdx MDX query to be validated.
* @return Parsed select node of the query;
* @throws OlapException When there is an error in validating the query.
*/
public static final SelectNode validateQuery(final String mdx) throws OlapException {
|
// Path: src/main/java/com/tfsinc/ilabs/olap/OlapClientManager.java
// public class OlapClientManager {
//
// /**
// * Root logger instance.
// */
// private static final Logger LOGGER = Logger.getLogger(
// OlapClientManager.class);
//
// /**
// * Initializes everything.
// * @param configFile Name and path of configuration file.
// */
// public static final void initialize(final String configFile) {
// OlapConfigReferences.initialize(configFile);
// OlapConnectionPoolManager.initialize(configFile);
// }
//
// /**
// * Shuts down everything.
// * @param forceClose Whether to close active connections forcibly.
// */
// public static final void shutdown(final boolean forceClose) {
// OlapConnectionPoolManager.shutdown(forceClose);
// }
//
// /**
// * @return An OLAP connection from the POOL.
// */
// public static WrappedOlapConnection getConnection() {
// return OlapConnectionPoolManager.getConnection();
// }
//
// /**
// * @param connection OLAP connection to be returned to the pool.
// * @return Whether the connection was returned successfully.
// */
// public static final boolean returnConnection(
// final WrappedOlapConnection connection) {
// return OlapConnectionPoolManager.returnConnection(connection);
// }
//
// /**
// * @param query String MDX query to be executed.
// * @return Cell set of the query.
// */
// public static final CellSet executeMdxQuery(final String query) {
// final WrappedOlapConnection connection = getConnection();
// try {
// final long start = System.currentTimeMillis();
// final CellSet cellSet = connection.getResource()
// .createStatement().executeOlapQuery(query);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Query execution time: " + (System.currentTimeMillis() - start) + " ms.");
// }
//
// returnConnection(connection);
// return cellSet;
// } catch (OlapException e) {
// LOGGER.error("Unable to execute query.", e);
// returnConnection(connection);
// return null;
// }
// }
//
// /**
// * @param query Parsed select MDX query.
// * @return Cell set of the query.
// */
// public static final CellSet executeMdxQuery(final SelectNode query) {
// final WrappedOlapConnection connection = getConnection();
// try {
// final long start = System.currentTimeMillis();
// final CellSet cellSet = connection.getResource()
// .createStatement().executeOlapQuery(query);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Query execution time: " + (System.currentTimeMillis() - start) + " ms.");
// }
// returnConnection(connection);
// return cellSet;
// } catch (OlapException e) {
// LOGGER.error("Unable to execute query.", e);
// returnConnection(connection);
// return null;
// }
// }
//
// }
//
// Path: src/main/java/com/tfsinc/ilabs/olap/WrappedOlapConnection.java
// public final class WrappedOlapConnection implements WrappedResource<OlapConnection> {
//
// /**
// * OLAP connection which is wrapped.
// */
// private final OlapConnection connection;
//
// /**
// * Root logger instance.
// */
// private static final Logger LOGGER = Logger.getLogger(
// WrappedOlapConnection.class);
//
// // Constructor.
// public WrappedOlapConnection(final OlapConnection olapConnection) {
// connection = olapConnection;
// }
//
// /* (non-Javadoc)
// * @see com.awesome.pro.pool.WrappedResource#close()
// */
// public void close() {
// try {
// connection.close();
// } catch (SQLException e) {
// LOGGER.error("Error in closing OLAP connection.");
// System.exit(1);
// }
// }
//
// /* (non-Javadoc)
// * @see com.awesome.pro.pool.WrappedResource#isClosed()
// */
// public boolean isClosed() {
// try {
// return connection.isClosed();
// } catch (SQLException e) {
// return true;
// }
// }
//
// /* (non-Javadoc)
// * @see com.awesome.pro.pool.WrappedResource#getResource()
// */
// public OlapConnection getResource() {
// return connection;
// }
//
// }
// Path: src/main/java/com/tfsinc/ilabs/mdx/builder/MDXValidator.java
import org.apache.log4j.Logger;
import org.olap4j.OlapException;
import org.olap4j.mdx.SelectNode;
import org.olap4j.mdx.parser.MdxParser;
import org.olap4j.mdx.parser.MdxValidator;
import com.tfsinc.ilabs.olap.OlapClientManager;
import com.tfsinc.ilabs.olap.WrappedOlapConnection;
package com.tfsinc.ilabs.mdx.builder;
/**
* Validates an MDX query.
* @author siddharth.s
*/
public class MDXValidator {
/**
* Root logger instance.
*/
private static final Logger LOGGER = Logger.getLogger(MDXValidator.class);
/**
* @param mdx MDX query to be validated.
* @return Parsed select node of the query;
* @throws OlapException When there is an error in validating the query.
*/
public static final SelectNode validateQuery(final String mdx) throws OlapException {
|
final WrappedOlapConnection connection = OlapClientManager
|
siddharth-sahoo/MDXQueryGenerator
|
src/main/java/com/tfsinc/ilabs/mdx/builder/MDXValidator.java
|
// Path: src/main/java/com/tfsinc/ilabs/olap/OlapClientManager.java
// public class OlapClientManager {
//
// /**
// * Root logger instance.
// */
// private static final Logger LOGGER = Logger.getLogger(
// OlapClientManager.class);
//
// /**
// * Initializes everything.
// * @param configFile Name and path of configuration file.
// */
// public static final void initialize(final String configFile) {
// OlapConfigReferences.initialize(configFile);
// OlapConnectionPoolManager.initialize(configFile);
// }
//
// /**
// * Shuts down everything.
// * @param forceClose Whether to close active connections forcibly.
// */
// public static final void shutdown(final boolean forceClose) {
// OlapConnectionPoolManager.shutdown(forceClose);
// }
//
// /**
// * @return An OLAP connection from the POOL.
// */
// public static WrappedOlapConnection getConnection() {
// return OlapConnectionPoolManager.getConnection();
// }
//
// /**
// * @param connection OLAP connection to be returned to the pool.
// * @return Whether the connection was returned successfully.
// */
// public static final boolean returnConnection(
// final WrappedOlapConnection connection) {
// return OlapConnectionPoolManager.returnConnection(connection);
// }
//
// /**
// * @param query String MDX query to be executed.
// * @return Cell set of the query.
// */
// public static final CellSet executeMdxQuery(final String query) {
// final WrappedOlapConnection connection = getConnection();
// try {
// final long start = System.currentTimeMillis();
// final CellSet cellSet = connection.getResource()
// .createStatement().executeOlapQuery(query);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Query execution time: " + (System.currentTimeMillis() - start) + " ms.");
// }
//
// returnConnection(connection);
// return cellSet;
// } catch (OlapException e) {
// LOGGER.error("Unable to execute query.", e);
// returnConnection(connection);
// return null;
// }
// }
//
// /**
// * @param query Parsed select MDX query.
// * @return Cell set of the query.
// */
// public static final CellSet executeMdxQuery(final SelectNode query) {
// final WrappedOlapConnection connection = getConnection();
// try {
// final long start = System.currentTimeMillis();
// final CellSet cellSet = connection.getResource()
// .createStatement().executeOlapQuery(query);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Query execution time: " + (System.currentTimeMillis() - start) + " ms.");
// }
// returnConnection(connection);
// return cellSet;
// } catch (OlapException e) {
// LOGGER.error("Unable to execute query.", e);
// returnConnection(connection);
// return null;
// }
// }
//
// }
//
// Path: src/main/java/com/tfsinc/ilabs/olap/WrappedOlapConnection.java
// public final class WrappedOlapConnection implements WrappedResource<OlapConnection> {
//
// /**
// * OLAP connection which is wrapped.
// */
// private final OlapConnection connection;
//
// /**
// * Root logger instance.
// */
// private static final Logger LOGGER = Logger.getLogger(
// WrappedOlapConnection.class);
//
// // Constructor.
// public WrappedOlapConnection(final OlapConnection olapConnection) {
// connection = olapConnection;
// }
//
// /* (non-Javadoc)
// * @see com.awesome.pro.pool.WrappedResource#close()
// */
// public void close() {
// try {
// connection.close();
// } catch (SQLException e) {
// LOGGER.error("Error in closing OLAP connection.");
// System.exit(1);
// }
// }
//
// /* (non-Javadoc)
// * @see com.awesome.pro.pool.WrappedResource#isClosed()
// */
// public boolean isClosed() {
// try {
// return connection.isClosed();
// } catch (SQLException e) {
// return true;
// }
// }
//
// /* (non-Javadoc)
// * @see com.awesome.pro.pool.WrappedResource#getResource()
// */
// public OlapConnection getResource() {
// return connection;
// }
//
// }
|
import org.apache.log4j.Logger;
import org.olap4j.OlapException;
import org.olap4j.mdx.SelectNode;
import org.olap4j.mdx.parser.MdxParser;
import org.olap4j.mdx.parser.MdxValidator;
import com.tfsinc.ilabs.olap.OlapClientManager;
import com.tfsinc.ilabs.olap.WrappedOlapConnection;
|
package com.tfsinc.ilabs.mdx.builder;
/**
* Validates an MDX query.
* @author siddharth.s
*/
public class MDXValidator {
/**
* Root logger instance.
*/
private static final Logger LOGGER = Logger.getLogger(MDXValidator.class);
/**
* @param mdx MDX query to be validated.
* @return Parsed select node of the query;
* @throws OlapException When there is an error in validating the query.
*/
public static final SelectNode validateQuery(final String mdx) throws OlapException {
|
// Path: src/main/java/com/tfsinc/ilabs/olap/OlapClientManager.java
// public class OlapClientManager {
//
// /**
// * Root logger instance.
// */
// private static final Logger LOGGER = Logger.getLogger(
// OlapClientManager.class);
//
// /**
// * Initializes everything.
// * @param configFile Name and path of configuration file.
// */
// public static final void initialize(final String configFile) {
// OlapConfigReferences.initialize(configFile);
// OlapConnectionPoolManager.initialize(configFile);
// }
//
// /**
// * Shuts down everything.
// * @param forceClose Whether to close active connections forcibly.
// */
// public static final void shutdown(final boolean forceClose) {
// OlapConnectionPoolManager.shutdown(forceClose);
// }
//
// /**
// * @return An OLAP connection from the POOL.
// */
// public static WrappedOlapConnection getConnection() {
// return OlapConnectionPoolManager.getConnection();
// }
//
// /**
// * @param connection OLAP connection to be returned to the pool.
// * @return Whether the connection was returned successfully.
// */
// public static final boolean returnConnection(
// final WrappedOlapConnection connection) {
// return OlapConnectionPoolManager.returnConnection(connection);
// }
//
// /**
// * @param query String MDX query to be executed.
// * @return Cell set of the query.
// */
// public static final CellSet executeMdxQuery(final String query) {
// final WrappedOlapConnection connection = getConnection();
// try {
// final long start = System.currentTimeMillis();
// final CellSet cellSet = connection.getResource()
// .createStatement().executeOlapQuery(query);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Query execution time: " + (System.currentTimeMillis() - start) + " ms.");
// }
//
// returnConnection(connection);
// return cellSet;
// } catch (OlapException e) {
// LOGGER.error("Unable to execute query.", e);
// returnConnection(connection);
// return null;
// }
// }
//
// /**
// * @param query Parsed select MDX query.
// * @return Cell set of the query.
// */
// public static final CellSet executeMdxQuery(final SelectNode query) {
// final WrappedOlapConnection connection = getConnection();
// try {
// final long start = System.currentTimeMillis();
// final CellSet cellSet = connection.getResource()
// .createStatement().executeOlapQuery(query);
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("Query execution time: " + (System.currentTimeMillis() - start) + " ms.");
// }
// returnConnection(connection);
// return cellSet;
// } catch (OlapException e) {
// LOGGER.error("Unable to execute query.", e);
// returnConnection(connection);
// return null;
// }
// }
//
// }
//
// Path: src/main/java/com/tfsinc/ilabs/olap/WrappedOlapConnection.java
// public final class WrappedOlapConnection implements WrappedResource<OlapConnection> {
//
// /**
// * OLAP connection which is wrapped.
// */
// private final OlapConnection connection;
//
// /**
// * Root logger instance.
// */
// private static final Logger LOGGER = Logger.getLogger(
// WrappedOlapConnection.class);
//
// // Constructor.
// public WrappedOlapConnection(final OlapConnection olapConnection) {
// connection = olapConnection;
// }
//
// /* (non-Javadoc)
// * @see com.awesome.pro.pool.WrappedResource#close()
// */
// public void close() {
// try {
// connection.close();
// } catch (SQLException e) {
// LOGGER.error("Error in closing OLAP connection.");
// System.exit(1);
// }
// }
//
// /* (non-Javadoc)
// * @see com.awesome.pro.pool.WrappedResource#isClosed()
// */
// public boolean isClosed() {
// try {
// return connection.isClosed();
// } catch (SQLException e) {
// return true;
// }
// }
//
// /* (non-Javadoc)
// * @see com.awesome.pro.pool.WrappedResource#getResource()
// */
// public OlapConnection getResource() {
// return connection;
// }
//
// }
// Path: src/main/java/com/tfsinc/ilabs/mdx/builder/MDXValidator.java
import org.apache.log4j.Logger;
import org.olap4j.OlapException;
import org.olap4j.mdx.SelectNode;
import org.olap4j.mdx.parser.MdxParser;
import org.olap4j.mdx.parser.MdxValidator;
import com.tfsinc.ilabs.olap.OlapClientManager;
import com.tfsinc.ilabs.olap.WrappedOlapConnection;
package com.tfsinc.ilabs.mdx.builder;
/**
* Validates an MDX query.
* @author siddharth.s
*/
public class MDXValidator {
/**
* Root logger instance.
*/
private static final Logger LOGGER = Logger.getLogger(MDXValidator.class);
/**
* @param mdx MDX query to be validated.
* @return Parsed select node of the query;
* @throws OlapException When there is an error in validating the query.
*/
public static final SelectNode validateQuery(final String mdx) throws OlapException {
|
final WrappedOlapConnection connection = OlapClientManager
|
siddharth-sahoo/MDXQueryGenerator
|
src/main/java/com/tfsinc/ilabs/mdx/builder/member/CalculatedMemberBuilder.java
|
// Path: src/main/java/com/tfsinc/ilabs/olap/references/MDXReferences.java
// public class MDXReferences {
//
// // Query key words.
// public static final String SELECT = "SELECT ";
// public static final String ON = " ON ";
// public static final String FROM = " FROM ";
// public static final String WHERE = " WHERE ";
// public static final String NON_EMPTY = " NON EMPTY ";
// public static final String ORDER = " ORDER ";
// public static final String FORMAT_STRING = " FORMAT_STRING =";
// public static final String MEMBER = " MEMBER ";
// public static final String AS = " AS ";
// public static final String WITH = " WITH ";
//
// public static final char SEPARATOR = ',';
// public static final char SEPARATOR_CROSS = '*';
// public static final char DEFAULT_AXIS = '0';
//
// // Member specifiers.
// public static final char MEMBER_START = '[';
// public static final char MEMBER_END = ']';
// public static final char MEMBER_SET_START = '{';
// public static final char MEMBER_SET_END = '}';
// public static final char MEMBER_HIERARCHY_SEPARATOR = '.';
// public static final char MEMBER_SPECIFIER = '&';
//
// public static final char FUNCTION_START = '(';
// public static final char FUNCTION_END = ')';
//
// // Standard member terminology.
// public static final String MEASURES = "[Measures].";
//
// // Sort order types.
// public static final String ORDER_ASCENDING = " ASC ";
// public static final String ORDER_DESCENDING = " DESC ";
// public static final String ORDER_CUSTOM_ASCENDING = " BASC ";
// public static final String ORDER_CUSTOM_DESCENDING = " BDESC ";
//
// // Format string types.
// public static final String FORMAT_STRING_GENERAL_NUMBER = " \"General Number\" ";
// public static final String FORMAT_STRING_CURRENCY = " \"Currency\" ";
// public static final String FORMAT_STRING_FIXED = " \"Fixed\" ";
// public static final String FORMAT_STRING_STANDARD = " \"Standard\" ";
// public static final String FORMAT_STRING_PERCENT = " \"Percent\" ";
// public static final String FORMAT_STRING_SCIENTIFIC = " \"Scientific\" ";
// public static final String FORMAT_STRING_YES_NO = " \"Yes/No\" ";
// public static final String FORMAT_STRING_TRUE_FALSE = " \"True/False\" ";
// public static final String FORMAT_STRING_ON_OFF = " \"On/Off\" ";
//
// }
|
import org.apache.log4j.Logger;
import com.tfsinc.ilabs.olap.references.MDXReferences;
|
package com.tfsinc.ilabs.mdx.builder.member;
/**
* Builder class calculated members.
* @author siddharth.s
*/
public class CalculatedMemberBuilder implements MemberBuilderSetName,
MemberBuilderSetExpression, MemberBuilderSetFormatString {
/**
* Root logger instance.
*/
private static final Logger LOGGER = Logger.getLogger(
CalculatedMemberBuilder.class);
/**
* Name of the calculated member.
*/
private String memberName;
/**
* Expression for the calculated member.
*/
private String memberExpression;
/**
* Optional formatting of the values.
*/
private String memberFormatString;
/**
* @return Calculated member builder instance.
*/
public static final MemberBuilderSetName getBuilder() {
return new CalculatedMemberBuilder();
}
// Private constructor.
private CalculatedMemberBuilder() { }
/* (non-Javadoc)
* @see com.tfsinc.ilabs.mdx.builder.member.MemberBuilderSetFormatString#setFormatString(com.tfsinc.ilabs.mdx.builder.member.FormatString)
*/
@Override
public MemberBuilderSetFormatString setFormatString(
final FormatString formatString) {
if (formatString == null) {
LOGGER.warn("Specified format string is null, ignoring.");
return this;
}
if (memberFormatString != null) {
LOGGER.warn("Overwriting format string.");
}
memberFormatString = FormatString.getFormatString(formatString);
return this;
}
/* (non-Javadoc)
* @see com.tfsinc.ilabs.mdx.builder.member.MemberBuilderSetFormatString#build()
*/
@Override
public String build() {
|
// Path: src/main/java/com/tfsinc/ilabs/olap/references/MDXReferences.java
// public class MDXReferences {
//
// // Query key words.
// public static final String SELECT = "SELECT ";
// public static final String ON = " ON ";
// public static final String FROM = " FROM ";
// public static final String WHERE = " WHERE ";
// public static final String NON_EMPTY = " NON EMPTY ";
// public static final String ORDER = " ORDER ";
// public static final String FORMAT_STRING = " FORMAT_STRING =";
// public static final String MEMBER = " MEMBER ";
// public static final String AS = " AS ";
// public static final String WITH = " WITH ";
//
// public static final char SEPARATOR = ',';
// public static final char SEPARATOR_CROSS = '*';
// public static final char DEFAULT_AXIS = '0';
//
// // Member specifiers.
// public static final char MEMBER_START = '[';
// public static final char MEMBER_END = ']';
// public static final char MEMBER_SET_START = '{';
// public static final char MEMBER_SET_END = '}';
// public static final char MEMBER_HIERARCHY_SEPARATOR = '.';
// public static final char MEMBER_SPECIFIER = '&';
//
// public static final char FUNCTION_START = '(';
// public static final char FUNCTION_END = ')';
//
// // Standard member terminology.
// public static final String MEASURES = "[Measures].";
//
// // Sort order types.
// public static final String ORDER_ASCENDING = " ASC ";
// public static final String ORDER_DESCENDING = " DESC ";
// public static final String ORDER_CUSTOM_ASCENDING = " BASC ";
// public static final String ORDER_CUSTOM_DESCENDING = " BDESC ";
//
// // Format string types.
// public static final String FORMAT_STRING_GENERAL_NUMBER = " \"General Number\" ";
// public static final String FORMAT_STRING_CURRENCY = " \"Currency\" ";
// public static final String FORMAT_STRING_FIXED = " \"Fixed\" ";
// public static final String FORMAT_STRING_STANDARD = " \"Standard\" ";
// public static final String FORMAT_STRING_PERCENT = " \"Percent\" ";
// public static final String FORMAT_STRING_SCIENTIFIC = " \"Scientific\" ";
// public static final String FORMAT_STRING_YES_NO = " \"Yes/No\" ";
// public static final String FORMAT_STRING_TRUE_FALSE = " \"True/False\" ";
// public static final String FORMAT_STRING_ON_OFF = " \"On/Off\" ";
//
// }
// Path: src/main/java/com/tfsinc/ilabs/mdx/builder/member/CalculatedMemberBuilder.java
import org.apache.log4j.Logger;
import com.tfsinc.ilabs.olap.references.MDXReferences;
package com.tfsinc.ilabs.mdx.builder.member;
/**
* Builder class calculated members.
* @author siddharth.s
*/
public class CalculatedMemberBuilder implements MemberBuilderSetName,
MemberBuilderSetExpression, MemberBuilderSetFormatString {
/**
* Root logger instance.
*/
private static final Logger LOGGER = Logger.getLogger(
CalculatedMemberBuilder.class);
/**
* Name of the calculated member.
*/
private String memberName;
/**
* Expression for the calculated member.
*/
private String memberExpression;
/**
* Optional formatting of the values.
*/
private String memberFormatString;
/**
* @return Calculated member builder instance.
*/
public static final MemberBuilderSetName getBuilder() {
return new CalculatedMemberBuilder();
}
// Private constructor.
private CalculatedMemberBuilder() { }
/* (non-Javadoc)
* @see com.tfsinc.ilabs.mdx.builder.member.MemberBuilderSetFormatString#setFormatString(com.tfsinc.ilabs.mdx.builder.member.FormatString)
*/
@Override
public MemberBuilderSetFormatString setFormatString(
final FormatString formatString) {
if (formatString == null) {
LOGGER.warn("Specified format string is null, ignoring.");
return this;
}
if (memberFormatString != null) {
LOGGER.warn("Overwriting format string.");
}
memberFormatString = FormatString.getFormatString(formatString);
return this;
}
/* (non-Javadoc)
* @see com.tfsinc.ilabs.mdx.builder.member.MemberBuilderSetFormatString#build()
*/
@Override
public String build() {
|
String member = MDXReferences.MEMBER + memberName
|
siddharth-sahoo/MDXQueryGenerator
|
src/main/java/com/tfsinc/ilabs/mdx/builder/dimension/DimensionBuilder.java
|
// Path: src/main/java/com/tfsinc/ilabs/olap/references/MDXReferences.java
// public class MDXReferences {
//
// // Query key words.
// public static final String SELECT = "SELECT ";
// public static final String ON = " ON ";
// public static final String FROM = " FROM ";
// public static final String WHERE = " WHERE ";
// public static final String NON_EMPTY = " NON EMPTY ";
// public static final String ORDER = " ORDER ";
// public static final String FORMAT_STRING = " FORMAT_STRING =";
// public static final String MEMBER = " MEMBER ";
// public static final String AS = " AS ";
// public static final String WITH = " WITH ";
//
// public static final char SEPARATOR = ',';
// public static final char SEPARATOR_CROSS = '*';
// public static final char DEFAULT_AXIS = '0';
//
// // Member specifiers.
// public static final char MEMBER_START = '[';
// public static final char MEMBER_END = ']';
// public static final char MEMBER_SET_START = '{';
// public static final char MEMBER_SET_END = '}';
// public static final char MEMBER_HIERARCHY_SEPARATOR = '.';
// public static final char MEMBER_SPECIFIER = '&';
//
// public static final char FUNCTION_START = '(';
// public static final char FUNCTION_END = ')';
//
// // Standard member terminology.
// public static final String MEASURES = "[Measures].";
//
// // Sort order types.
// public static final String ORDER_ASCENDING = " ASC ";
// public static final String ORDER_DESCENDING = " DESC ";
// public static final String ORDER_CUSTOM_ASCENDING = " BASC ";
// public static final String ORDER_CUSTOM_DESCENDING = " BDESC ";
//
// // Format string types.
// public static final String FORMAT_STRING_GENERAL_NUMBER = " \"General Number\" ";
// public static final String FORMAT_STRING_CURRENCY = " \"Currency\" ";
// public static final String FORMAT_STRING_FIXED = " \"Fixed\" ";
// public static final String FORMAT_STRING_STANDARD = " \"Standard\" ";
// public static final String FORMAT_STRING_PERCENT = " \"Percent\" ";
// public static final String FORMAT_STRING_SCIENTIFIC = " \"Scientific\" ";
// public static final String FORMAT_STRING_YES_NO = " \"Yes/No\" ";
// public static final String FORMAT_STRING_TRUE_FALSE = " \"True/False\" ";
// public static final String FORMAT_STRING_ON_OFF = " \"On/Off\" ";
//
// }
|
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;
import com.tfsinc.ilabs.olap.references.MDXReferences;
|
}
this.sortOrder = type;
this.customSortEntity = customEntity;
return this;
}
/* (non-Javadoc)
* @see com.tfsinc.ilabs.mdx.builder.dimension.DimensionBuilderAddMember#addMembers(java.lang.String[])
*/
@Override
public DimensionBuilderAddMember addMembers(final String... members) {
if (members == null || members.length == 0) {
throw new IllegalArgumentException("No members were specified.");
}
this.members.addAll(Arrays.asList(members));
return this;
}
/* (non-Javadoc)
* @see com.tfsinc.ilabs.mdx.builder.dimension.DimensionBuilderAddMember#build()
*/
@Override
public String build() {
if (members == null || members.size() == 0) {
throw new IllegalStateException("No members are present.");
}
String query = "";
if (this.isNonEmpty) {
|
// Path: src/main/java/com/tfsinc/ilabs/olap/references/MDXReferences.java
// public class MDXReferences {
//
// // Query key words.
// public static final String SELECT = "SELECT ";
// public static final String ON = " ON ";
// public static final String FROM = " FROM ";
// public static final String WHERE = " WHERE ";
// public static final String NON_EMPTY = " NON EMPTY ";
// public static final String ORDER = " ORDER ";
// public static final String FORMAT_STRING = " FORMAT_STRING =";
// public static final String MEMBER = " MEMBER ";
// public static final String AS = " AS ";
// public static final String WITH = " WITH ";
//
// public static final char SEPARATOR = ',';
// public static final char SEPARATOR_CROSS = '*';
// public static final char DEFAULT_AXIS = '0';
//
// // Member specifiers.
// public static final char MEMBER_START = '[';
// public static final char MEMBER_END = ']';
// public static final char MEMBER_SET_START = '{';
// public static final char MEMBER_SET_END = '}';
// public static final char MEMBER_HIERARCHY_SEPARATOR = '.';
// public static final char MEMBER_SPECIFIER = '&';
//
// public static final char FUNCTION_START = '(';
// public static final char FUNCTION_END = ')';
//
// // Standard member terminology.
// public static final String MEASURES = "[Measures].";
//
// // Sort order types.
// public static final String ORDER_ASCENDING = " ASC ";
// public static final String ORDER_DESCENDING = " DESC ";
// public static final String ORDER_CUSTOM_ASCENDING = " BASC ";
// public static final String ORDER_CUSTOM_DESCENDING = " BDESC ";
//
// // Format string types.
// public static final String FORMAT_STRING_GENERAL_NUMBER = " \"General Number\" ";
// public static final String FORMAT_STRING_CURRENCY = " \"Currency\" ";
// public static final String FORMAT_STRING_FIXED = " \"Fixed\" ";
// public static final String FORMAT_STRING_STANDARD = " \"Standard\" ";
// public static final String FORMAT_STRING_PERCENT = " \"Percent\" ";
// public static final String FORMAT_STRING_SCIENTIFIC = " \"Scientific\" ";
// public static final String FORMAT_STRING_YES_NO = " \"Yes/No\" ";
// public static final String FORMAT_STRING_TRUE_FALSE = " \"True/False\" ";
// public static final String FORMAT_STRING_ON_OFF = " \"On/Off\" ";
//
// }
// Path: src/main/java/com/tfsinc/ilabs/mdx/builder/dimension/DimensionBuilder.java
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;
import com.tfsinc.ilabs.olap.references.MDXReferences;
}
this.sortOrder = type;
this.customSortEntity = customEntity;
return this;
}
/* (non-Javadoc)
* @see com.tfsinc.ilabs.mdx.builder.dimension.DimensionBuilderAddMember#addMembers(java.lang.String[])
*/
@Override
public DimensionBuilderAddMember addMembers(final String... members) {
if (members == null || members.length == 0) {
throw new IllegalArgumentException("No members were specified.");
}
this.members.addAll(Arrays.asList(members));
return this;
}
/* (non-Javadoc)
* @see com.tfsinc.ilabs.mdx.builder.dimension.DimensionBuilderAddMember#build()
*/
@Override
public String build() {
if (members == null || members.size() == 0) {
throw new IllegalStateException("No members are present.");
}
String query = "";
if (this.isNonEmpty) {
|
query = query + MDXReferences.NON_EMPTY;
|
siddharth-sahoo/MDXQueryGenerator
|
src/main/java/com/tfsinc/ilabs/olap/AcquireOlapConnection.java
|
// Path: src/main/java/com/tfsinc/ilabs/olap/references/OlapConfigReferences.java
// public class OlapConfigReferences {
//
// /**
// * Configurations read from property file.
// */
// public static PropertyFileUtility CONFIG = null;
//
// /**
// * Root logger instance.
// */
// private static final Logger LOGGER = Logger.getLogger(
// OlapConfigReferences.class);
//
// /**
// * Reads the specified configuration file and keeps it in memory.
// * @param configFile Name of the configuration file to read.
// */
// public static final void initialize(final String configFile) {
// if (CONFIG == null) {
// synchronized (OlapConfigReferences.class) {
// if (CONFIG == null) {
// if (configFile == null || configFile.length() == 0) {
// LOGGER.error("Configuration file name specified"
// + " is null or blank. Exiting.");
// System.exit(1);
// }
//
// CONFIG = new PropertyFileUtility(configFile);
// LOGGER.info("Populated base configurations for OLAP cube.");
//
// loadDriver();
// }
// }
// }
// }
//
// /**
// * Loads the specified OLAP driver. Exits if the class is not found.
// */
// private static final void loadDriver() {
// try {
// Class.forName(CONFIG.getStringValue(
// PROPERTY_OLAP_DRIVER_CLASS,
// DEFAULT_OLAP_DRIVER_CLASS));
// } catch (ClassNotFoundException e) {
// LOGGER.error("Specified driver class is not found. Exiting.", e);
// System.exit(1);
// }
// }
//
// // Configuration properties
// public static final String PROPERTY_OLAP_DRIVER_CLASS = "OlapDriverClass";
// public static final String PROPERTY_OLAP_CONNECTION_URL = "OlapConnectionUrl";
// public static final String PROPERTY_VALIDATE_QUERY = "ValidateQuery";
// public static final String PROPERTY_DISPLAY_QUERY = "DisplayQuery";
// public static final String PROPERTY_MEASURE_AXIS = "MeasureAxis";
//
// // Default configurations
// public static final String DEFAULT_OLAP_DRIVER_CLASS = "org.olap4j.driver.xmla.XmlaOlap4jDriver";
// public static final String DEFAULT_OLAP_CONNECTION_URL = "jdbc:xmla:Server=http://"
// + "localhost/olap/msmdpump.dll";
// public static final boolean DEFAULT_VALIDATE_QUERY = true;
// public static final boolean DEFAULT_DISPLAY_QUERY = true;
// public static final String DEFAULT_MEASURE_AXIS = "COLUMNS";
//
// // Standard axes.
// private static final String AXIS_COLUMNS = "COLUMNS";
// private static final String AXIS_ROWS = "ROWS";
// private static final int AXIS_INDEX_COLUMNS = 0;
// private static final int AXIS_INDEX_ROWS = 1;
//
// /**
// * @param axis Standard axis name.
// * @return Corresponding axis index.
// */
// public static final int getAxisIndex(final String axis) {
// switch (axis.toUpperCase()) {
// case AXIS_COLUMNS :
// return AXIS_INDEX_COLUMNS;
// case AXIS_ROWS :
// return AXIS_INDEX_ROWS;
// default :
// throw new IllegalArgumentException("Unknown axis: " + axis);
// }
// }
//
// /**
// * @return Measure axis from configuration file.
// */
// public static final int getMeasureAxisIndex() {
// return getAxisIndex(CONFIG.getStringValue(
// PROPERTY_MEASURE_AXIS, DEFAULT_MEASURE_AXIS));
// }
//
// /**
// * @return Whether to validate the MDX query generated.
// */
// public static final boolean shouldValidateMdx() {
// return CONFIG.getBooleanValue(PROPERTY_VALIDATE_QUERY,
// DEFAULT_VALIDATE_QUERY);
// }
//
// /**
// * @return Whether to display the generated MDX query.
// */
// public static final boolean shouldDisplayMdx() {
// return CONFIG.getBooleanValue(PROPERTY_DISPLAY_QUERY,
// DEFAULT_DISPLAY_QUERY);
// }
//
// }
|
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import org.olap4j.OlapConnection;
import com.awesome.pro.pool.AcquireResource;
import com.tfsinc.ilabs.olap.references.OlapConfigReferences;
|
package com.tfsinc.ilabs.olap;
/**
* Specifies the procedure to acquire a new OLAP connection.
* @author siddharth.s
*/
final class AcquireOlapConnection implements AcquireResource<WrappedOlapConnection> {
/**
* Root logger instance.
*/
private static final Logger LOGGER = Logger.getLogger(
AcquireOlapConnection.class);
/* (non-Javadoc)
* @see com.awesome.pro.pool.AcquireResource#acquireResource()
*/
public WrappedOlapConnection acquireResource() {
try {
final OlapConnection connection = DriverManager.getConnection(
|
// Path: src/main/java/com/tfsinc/ilabs/olap/references/OlapConfigReferences.java
// public class OlapConfigReferences {
//
// /**
// * Configurations read from property file.
// */
// public static PropertyFileUtility CONFIG = null;
//
// /**
// * Root logger instance.
// */
// private static final Logger LOGGER = Logger.getLogger(
// OlapConfigReferences.class);
//
// /**
// * Reads the specified configuration file and keeps it in memory.
// * @param configFile Name of the configuration file to read.
// */
// public static final void initialize(final String configFile) {
// if (CONFIG == null) {
// synchronized (OlapConfigReferences.class) {
// if (CONFIG == null) {
// if (configFile == null || configFile.length() == 0) {
// LOGGER.error("Configuration file name specified"
// + " is null or blank. Exiting.");
// System.exit(1);
// }
//
// CONFIG = new PropertyFileUtility(configFile);
// LOGGER.info("Populated base configurations for OLAP cube.");
//
// loadDriver();
// }
// }
// }
// }
//
// /**
// * Loads the specified OLAP driver. Exits if the class is not found.
// */
// private static final void loadDriver() {
// try {
// Class.forName(CONFIG.getStringValue(
// PROPERTY_OLAP_DRIVER_CLASS,
// DEFAULT_OLAP_DRIVER_CLASS));
// } catch (ClassNotFoundException e) {
// LOGGER.error("Specified driver class is not found. Exiting.", e);
// System.exit(1);
// }
// }
//
// // Configuration properties
// public static final String PROPERTY_OLAP_DRIVER_CLASS = "OlapDriverClass";
// public static final String PROPERTY_OLAP_CONNECTION_URL = "OlapConnectionUrl";
// public static final String PROPERTY_VALIDATE_QUERY = "ValidateQuery";
// public static final String PROPERTY_DISPLAY_QUERY = "DisplayQuery";
// public static final String PROPERTY_MEASURE_AXIS = "MeasureAxis";
//
// // Default configurations
// public static final String DEFAULT_OLAP_DRIVER_CLASS = "org.olap4j.driver.xmla.XmlaOlap4jDriver";
// public static final String DEFAULT_OLAP_CONNECTION_URL = "jdbc:xmla:Server=http://"
// + "localhost/olap/msmdpump.dll";
// public static final boolean DEFAULT_VALIDATE_QUERY = true;
// public static final boolean DEFAULT_DISPLAY_QUERY = true;
// public static final String DEFAULT_MEASURE_AXIS = "COLUMNS";
//
// // Standard axes.
// private static final String AXIS_COLUMNS = "COLUMNS";
// private static final String AXIS_ROWS = "ROWS";
// private static final int AXIS_INDEX_COLUMNS = 0;
// private static final int AXIS_INDEX_ROWS = 1;
//
// /**
// * @param axis Standard axis name.
// * @return Corresponding axis index.
// */
// public static final int getAxisIndex(final String axis) {
// switch (axis.toUpperCase()) {
// case AXIS_COLUMNS :
// return AXIS_INDEX_COLUMNS;
// case AXIS_ROWS :
// return AXIS_INDEX_ROWS;
// default :
// throw new IllegalArgumentException("Unknown axis: " + axis);
// }
// }
//
// /**
// * @return Measure axis from configuration file.
// */
// public static final int getMeasureAxisIndex() {
// return getAxisIndex(CONFIG.getStringValue(
// PROPERTY_MEASURE_AXIS, DEFAULT_MEASURE_AXIS));
// }
//
// /**
// * @return Whether to validate the MDX query generated.
// */
// public static final boolean shouldValidateMdx() {
// return CONFIG.getBooleanValue(PROPERTY_VALIDATE_QUERY,
// DEFAULT_VALIDATE_QUERY);
// }
//
// /**
// * @return Whether to display the generated MDX query.
// */
// public static final boolean shouldDisplayMdx() {
// return CONFIG.getBooleanValue(PROPERTY_DISPLAY_QUERY,
// DEFAULT_DISPLAY_QUERY);
// }
//
// }
// Path: src/main/java/com/tfsinc/ilabs/olap/AcquireOlapConnection.java
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import org.olap4j.OlapConnection;
import com.awesome.pro.pool.AcquireResource;
import com.tfsinc.ilabs.olap.references.OlapConfigReferences;
package com.tfsinc.ilabs.olap;
/**
* Specifies the procedure to acquire a new OLAP connection.
* @author siddharth.s
*/
final class AcquireOlapConnection implements AcquireResource<WrappedOlapConnection> {
/**
* Root logger instance.
*/
private static final Logger LOGGER = Logger.getLogger(
AcquireOlapConnection.class);
/* (non-Javadoc)
* @see com.awesome.pro.pool.AcquireResource#acquireResource()
*/
public WrappedOlapConnection acquireResource() {
try {
final OlapConnection connection = DriverManager.getConnection(
|
OlapConfigReferences.CONFIG.getStringValue(
|
Hatzen/EasyPeasyVPN
|
src/main/java/de/hartz/vpn/utilities/GeneralUtilities.java
|
// Path: src/main/java/de/hartz/vpn/helper/OutputStreamHandler.java
// public class OutputStreamHandler extends Thread {
// private InputStream inputStream;
// private Logger listener;
// private StringBuilder output = new StringBuilder();
//
// public OutputStreamHandler(InputStream inputStream) {
// this.inputStream = inputStream;
// }
//
// public OutputStreamHandler(InputStream inputStream, Logger listener) {
// this.listener = listener;
// this.inputStream = inputStream;
// }
//
// public void run() {
// try (Scanner br = new Scanner(new InputStreamReader(inputStream))) {
// String line;
// while (br.hasNextLine()) {
// line = br.nextLine();
// output.append(line).append(System.getProperty("line.separator"));
// if (listener != null)
// listener.addLogLine(line);
// }
// }
// }
//
// public StringBuilder getOutput() {
// /*
// TODO: Check if this works always.
// try {
// inputStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }*/
// return output;
// }
// }
|
import de.hartz.vpn.helper.Linux;
import de.hartz.vpn.helper.OutputStreamHandler;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.prefs.Preferences;
|
try {
// SecurityException on Windows.
preferences.put("foo", "bar");
preferences.remove("foo");
// BackingStoreException on Linux.
preferences.flush();
return true;
} catch(Exception e) {
return false;
} finally{
System.setErr(systemErr);
}
}
}
/**
* Function that indicates whether the system uses apt as packet manager.
* @return
*/
@Linux
public static boolean hasAPT() {
ProcessBuilder pb = new ProcessBuilder("whereis", "apt");
pb.redirectErrorStream(true);
Process process = null;
try {
process = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
|
// Path: src/main/java/de/hartz/vpn/helper/OutputStreamHandler.java
// public class OutputStreamHandler extends Thread {
// private InputStream inputStream;
// private Logger listener;
// private StringBuilder output = new StringBuilder();
//
// public OutputStreamHandler(InputStream inputStream) {
// this.inputStream = inputStream;
// }
//
// public OutputStreamHandler(InputStream inputStream, Logger listener) {
// this.listener = listener;
// this.inputStream = inputStream;
// }
//
// public void run() {
// try (Scanner br = new Scanner(new InputStreamReader(inputStream))) {
// String line;
// while (br.hasNextLine()) {
// line = br.nextLine();
// output.append(line).append(System.getProperty("line.separator"));
// if (listener != null)
// listener.addLogLine(line);
// }
// }
// }
//
// public StringBuilder getOutput() {
// /*
// TODO: Check if this works always.
// try {
// inputStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }*/
// return output;
// }
// }
// Path: src/main/java/de/hartz/vpn/utilities/GeneralUtilities.java
import de.hartz.vpn.helper.Linux;
import de.hartz.vpn.helper.OutputStreamHandler;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.prefs.Preferences;
try {
// SecurityException on Windows.
preferences.put("foo", "bar");
preferences.remove("foo");
// BackingStoreException on Linux.
preferences.flush();
return true;
} catch(Exception e) {
return false;
} finally{
System.setErr(systemErr);
}
}
}
/**
* Function that indicates whether the system uses apt as packet manager.
* @return
*/
@Linux
public static boolean hasAPT() {
ProcessBuilder pb = new ProcessBuilder("whereis", "apt");
pb.redirectErrorStream(true);
Process process = null;
try {
process = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
|
OutputStreamHandler outputHandler = new OutputStreamHandler(process.getInputStream());
|
Hatzen/EasyPeasyVPN
|
src/main/java/de/hartz/vpn/utilities/OpenVPNUtilities.java
|
// Path: src/main/java/de/hartz/vpn/helper/OutputStreamHandler.java
// public class OutputStreamHandler extends Thread {
// private InputStream inputStream;
// private Logger listener;
// private StringBuilder output = new StringBuilder();
//
// public OutputStreamHandler(InputStream inputStream) {
// this.inputStream = inputStream;
// }
//
// public OutputStreamHandler(InputStream inputStream, Logger listener) {
// this.listener = listener;
// this.inputStream = inputStream;
// }
//
// public void run() {
// try (Scanner br = new Scanner(new InputStreamReader(inputStream))) {
// String line;
// while (br.hasNextLine()) {
// line = br.nextLine();
// output.append(line).append(System.getProperty("line.separator"));
// if (listener != null)
// listener.addLogLine(line);
// }
// }
// }
//
// public StringBuilder getOutput() {
// /*
// TODO: Check if this works always.
// try {
// inputStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }*/
// return output;
// }
// }
|
import de.hartz.vpn.helper.OutputStreamHandler;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
|
package de.hartz.vpn.utilities;
/**
* Created by kaiha on 31.08.2017.
*/
public final class OpenVPNUtilities {
//TODO: If possible get rid off..
// @Windows
public static String openVPNBinPath;
/**
* TODO: TIDY UP!!!! MODULARIZE.
* TODO: Get working under linux?! And maybe same concept to find openssl?
* Finds the installation path of openvpn through the environment variables.
* @return The installation path or null if not found.
*/
public static String getOpenVPNInstallationPath() {
if (GeneralUtilities.isWindows()) {
String findValue = "OpenVPN";
// After installations getenv() returns old values, missing openvpn...
// HACK AROUND THIS;
// https://stackoverflow.com/questions/10434065/how-to-retrieve-the-modified-value-of-an-environment-variable-which-is-modified
ProcessBuilder pb = new ProcessBuilder( "cmd.exe");
pb.redirectErrorStream(true);
Process process = null;
try {
process = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
|
// Path: src/main/java/de/hartz/vpn/helper/OutputStreamHandler.java
// public class OutputStreamHandler extends Thread {
// private InputStream inputStream;
// private Logger listener;
// private StringBuilder output = new StringBuilder();
//
// public OutputStreamHandler(InputStream inputStream) {
// this.inputStream = inputStream;
// }
//
// public OutputStreamHandler(InputStream inputStream, Logger listener) {
// this.listener = listener;
// this.inputStream = inputStream;
// }
//
// public void run() {
// try (Scanner br = new Scanner(new InputStreamReader(inputStream))) {
// String line;
// while (br.hasNextLine()) {
// line = br.nextLine();
// output.append(line).append(System.getProperty("line.separator"));
// if (listener != null)
// listener.addLogLine(line);
// }
// }
// }
//
// public StringBuilder getOutput() {
// /*
// TODO: Check if this works always.
// try {
// inputStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }*/
// return output;
// }
// }
// Path: src/main/java/de/hartz/vpn/utilities/OpenVPNUtilities.java
import de.hartz.vpn.helper.OutputStreamHandler;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
package de.hartz.vpn.utilities;
/**
* Created by kaiha on 31.08.2017.
*/
public final class OpenVPNUtilities {
//TODO: If possible get rid off..
// @Windows
public static String openVPNBinPath;
/**
* TODO: TIDY UP!!!! MODULARIZE.
* TODO: Get working under linux?! And maybe same concept to find openssl?
* Finds the installation path of openvpn through the environment variables.
* @return The installation path or null if not found.
*/
public static String getOpenVPNInstallationPath() {
if (GeneralUtilities.isWindows()) {
String findValue = "OpenVPN";
// After installations getenv() returns old values, missing openvpn...
// HACK AROUND THIS;
// https://stackoverflow.com/questions/10434065/how-to-retrieve-the-modified-value-of-an-environment-variable-which-is-modified
ProcessBuilder pb = new ProcessBuilder( "cmd.exe");
pb.redirectErrorStream(true);
Process process = null;
try {
process = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
|
OutputStreamHandler outputHandler = new OutputStreamHandler(process.getInputStream());
|
Hatzen/EasyPeasyVPN
|
src/main/java/de/hartz/vpn/main/UserData.java
|
// Path: src/main/java/de/hartz/vpn/main/server/ConfigState.java
// public class ConfigState implements Serializable {
//
// public enum Adapter {
// OpenVPN,
// IPsec,
// FreeLan
// }
//
// // TODO: Tcp not supported by mediator.
// public enum Protocol {
// TCP,
// UDP
// }
//
// // TODO: Closed tunnel not supported by software. Needs networkbridge between adapters (?)
// public enum Tunnel {
// CLOSED,
// SPLIT
// }
//
// // TODO: Site connections needs traffic redirection by every computer or the gateway to vpn-gateway. Not really supported by Software.
// public enum NetworkType {
// SITE_TO_SITE,
// SITE_TO_END,
// END_TO_END,
// }
//
// private String networkName;
// private Protocol protocol;
//
// private Mediator mediator;
//
// private Tunnel tunnel;
// private Adapter adapter;
// private NetworkType networkType;
//
// private boolean needsAuthentication;
//
// private String netaddress;
// private short subnetmask;
//
// /**
// * Default Constructor for Express Configuration.
// */
// public ConfigState() {
// tunnel = Tunnel.SPLIT;
// adapter = Adapter.OpenVPN;
// networkType = NetworkType.END_TO_END;
// protocol = UDP;
// netaddress = NetworkUtilities.getRecommendedIp();
// subnetmask = 24;
//
// needsAuthentication = false;
// }
//
// public String getNetworkName() {
// return networkName;
// }
//
// public void setNetworkName(String networkName) {
// this.networkName = networkName;
// }
//
// public Tunnel getTunnel() {
// return tunnel;
// }
//
// public void setTunnel(Tunnel tunnel) {
// this.tunnel = tunnel;
// }
//
// public Adapter getAdapter() {
// return adapter;
// }
//
// public void setAdapter(Adapter adapter) {
// this.adapter = adapter;
// }
//
// public NetworkType getNetworkType() {
// return networkType;
// }
//
// public void setNetworkType(NetworkType networkType) {
// this.networkType = networkType;
// }
//
// public boolean isNeedsAuthentication() {
// return needsAuthentication;
// }
//
// public void setNeedsAuthentication(boolean needsAuthentication) {
// this.needsAuthentication = needsAuthentication;
// }
//
// public String getNetaddress() {
// return netaddress;
// }
//
// public String getProtocol() {
// return protocol.name().toLowerCase();
// }
//
// public void setNetaddress(String netaddress) {
// this.netaddress = netaddress;
// }
//
// public int getSubnetmask() {
// return subnetmask;
// }
//
// public void setSubnetmask(short subnetmask) {
// this.subnetmask = subnetmask;
// }
//
// public Mediator getMediator() {
// return mediator;
// }
//
// public void setMediator(Mediator mediator) {
// this.mediator = mediator;
// }
//
// }
//
// Path: src/main/java/de/hartz/vpn/mediation/Mediator.java
// public class Mediator implements Serializable {
//
// private String mediatorName;
// private String url;
// // Only needed if mediationserver hosts network specific files.
// private int metaServerPort;
// private int udpHolePunchingPort;
//
// // If true the url is a rest api showing the original ip of the mediator, needed for dynamic ips.
// private boolean redirectFromUrl;
//
// public Mediator(String mediatorName,String url, int metaServerPort, int udpHolePunchingPort, boolean redirectFromUrl) {
// this.mediatorName = mediatorName;
// this.url = url;
// this.metaServerPort = metaServerPort;
// this.udpHolePunchingPort = udpHolePunchingPort;
// this.redirectFromUrl = redirectFromUrl;
// }
//
// public String getMediatorName() {
// return mediatorName;
// }
//
// public int getMetaServerPort() {
// return metaServerPort;
// }
//
// public int getUdpHolePunchingPort() {
// return udpHolePunchingPort;
// }
//
// public boolean isRedirectFromUrl() {
// return redirectFromUrl;
// }
//
// /**
// * Get the real url or ip of the mediator server.
// * @returns the url of the mediator.
// */
// public String getUrl() {
// if (!redirectFromUrl) {
// return url;
// }
// try {
// URL whatIsMyIp = new URL(url);
// BufferedReader in = new BufferedReader(new InputStreamReader(whatIsMyIp.openStream()));
// String ip = in.readLine();
// return ip;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
//
// Path: src/main/java/de/hartz/vpn/utilities/Constants.java
// public static final String USER_DATA_FILE_PATH = System.getProperty("user.home") + File.separator + "." + SOFTWARE_NAME + File.separator + "userData.ser";
|
import de.hartz.vpn.main.server.ConfigState;
import de.hartz.vpn.mediation.Mediator;
import java.io.*;
import java.util.ArrayList;
import static de.hartz.vpn.utilities.Constants.USER_DATA_FILE_PATH;
|
package de.hartz.vpn.main;
/**
* Hold the data for the current session of this user.
*/
public class UserData implements Serializable{
private static UserData instance;
private UserList userList = new UserList();
|
// Path: src/main/java/de/hartz/vpn/main/server/ConfigState.java
// public class ConfigState implements Serializable {
//
// public enum Adapter {
// OpenVPN,
// IPsec,
// FreeLan
// }
//
// // TODO: Tcp not supported by mediator.
// public enum Protocol {
// TCP,
// UDP
// }
//
// // TODO: Closed tunnel not supported by software. Needs networkbridge between adapters (?)
// public enum Tunnel {
// CLOSED,
// SPLIT
// }
//
// // TODO: Site connections needs traffic redirection by every computer or the gateway to vpn-gateway. Not really supported by Software.
// public enum NetworkType {
// SITE_TO_SITE,
// SITE_TO_END,
// END_TO_END,
// }
//
// private String networkName;
// private Protocol protocol;
//
// private Mediator mediator;
//
// private Tunnel tunnel;
// private Adapter adapter;
// private NetworkType networkType;
//
// private boolean needsAuthentication;
//
// private String netaddress;
// private short subnetmask;
//
// /**
// * Default Constructor for Express Configuration.
// */
// public ConfigState() {
// tunnel = Tunnel.SPLIT;
// adapter = Adapter.OpenVPN;
// networkType = NetworkType.END_TO_END;
// protocol = UDP;
// netaddress = NetworkUtilities.getRecommendedIp();
// subnetmask = 24;
//
// needsAuthentication = false;
// }
//
// public String getNetworkName() {
// return networkName;
// }
//
// public void setNetworkName(String networkName) {
// this.networkName = networkName;
// }
//
// public Tunnel getTunnel() {
// return tunnel;
// }
//
// public void setTunnel(Tunnel tunnel) {
// this.tunnel = tunnel;
// }
//
// public Adapter getAdapter() {
// return adapter;
// }
//
// public void setAdapter(Adapter adapter) {
// this.adapter = adapter;
// }
//
// public NetworkType getNetworkType() {
// return networkType;
// }
//
// public void setNetworkType(NetworkType networkType) {
// this.networkType = networkType;
// }
//
// public boolean isNeedsAuthentication() {
// return needsAuthentication;
// }
//
// public void setNeedsAuthentication(boolean needsAuthentication) {
// this.needsAuthentication = needsAuthentication;
// }
//
// public String getNetaddress() {
// return netaddress;
// }
//
// public String getProtocol() {
// return protocol.name().toLowerCase();
// }
//
// public void setNetaddress(String netaddress) {
// this.netaddress = netaddress;
// }
//
// public int getSubnetmask() {
// return subnetmask;
// }
//
// public void setSubnetmask(short subnetmask) {
// this.subnetmask = subnetmask;
// }
//
// public Mediator getMediator() {
// return mediator;
// }
//
// public void setMediator(Mediator mediator) {
// this.mediator = mediator;
// }
//
// }
//
// Path: src/main/java/de/hartz/vpn/mediation/Mediator.java
// public class Mediator implements Serializable {
//
// private String mediatorName;
// private String url;
// // Only needed if mediationserver hosts network specific files.
// private int metaServerPort;
// private int udpHolePunchingPort;
//
// // If true the url is a rest api showing the original ip of the mediator, needed for dynamic ips.
// private boolean redirectFromUrl;
//
// public Mediator(String mediatorName,String url, int metaServerPort, int udpHolePunchingPort, boolean redirectFromUrl) {
// this.mediatorName = mediatorName;
// this.url = url;
// this.metaServerPort = metaServerPort;
// this.udpHolePunchingPort = udpHolePunchingPort;
// this.redirectFromUrl = redirectFromUrl;
// }
//
// public String getMediatorName() {
// return mediatorName;
// }
//
// public int getMetaServerPort() {
// return metaServerPort;
// }
//
// public int getUdpHolePunchingPort() {
// return udpHolePunchingPort;
// }
//
// public boolean isRedirectFromUrl() {
// return redirectFromUrl;
// }
//
// /**
// * Get the real url or ip of the mediator server.
// * @returns the url of the mediator.
// */
// public String getUrl() {
// if (!redirectFromUrl) {
// return url;
// }
// try {
// URL whatIsMyIp = new URL(url);
// BufferedReader in = new BufferedReader(new InputStreamReader(whatIsMyIp.openStream()));
// String ip = in.readLine();
// return ip;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
//
// Path: src/main/java/de/hartz/vpn/utilities/Constants.java
// public static final String USER_DATA_FILE_PATH = System.getProperty("user.home") + File.separator + "." + SOFTWARE_NAME + File.separator + "userData.ser";
// Path: src/main/java/de/hartz/vpn/main/UserData.java
import de.hartz.vpn.main.server.ConfigState;
import de.hartz.vpn.mediation.Mediator;
import java.io.*;
import java.util.ArrayList;
import static de.hartz.vpn.utilities.Constants.USER_DATA_FILE_PATH;
package de.hartz.vpn.main;
/**
* Hold the data for the current session of this user.
*/
public class UserData implements Serializable{
private static UserData instance;
private UserList userList = new UserList();
|
private ArrayList<Mediator> mediatorList = new ArrayList<>();
|
Hatzen/EasyPeasyVPN
|
src/main/java/de/hartz/vpn/main/UserData.java
|
// Path: src/main/java/de/hartz/vpn/main/server/ConfigState.java
// public class ConfigState implements Serializable {
//
// public enum Adapter {
// OpenVPN,
// IPsec,
// FreeLan
// }
//
// // TODO: Tcp not supported by mediator.
// public enum Protocol {
// TCP,
// UDP
// }
//
// // TODO: Closed tunnel not supported by software. Needs networkbridge between adapters (?)
// public enum Tunnel {
// CLOSED,
// SPLIT
// }
//
// // TODO: Site connections needs traffic redirection by every computer or the gateway to vpn-gateway. Not really supported by Software.
// public enum NetworkType {
// SITE_TO_SITE,
// SITE_TO_END,
// END_TO_END,
// }
//
// private String networkName;
// private Protocol protocol;
//
// private Mediator mediator;
//
// private Tunnel tunnel;
// private Adapter adapter;
// private NetworkType networkType;
//
// private boolean needsAuthentication;
//
// private String netaddress;
// private short subnetmask;
//
// /**
// * Default Constructor for Express Configuration.
// */
// public ConfigState() {
// tunnel = Tunnel.SPLIT;
// adapter = Adapter.OpenVPN;
// networkType = NetworkType.END_TO_END;
// protocol = UDP;
// netaddress = NetworkUtilities.getRecommendedIp();
// subnetmask = 24;
//
// needsAuthentication = false;
// }
//
// public String getNetworkName() {
// return networkName;
// }
//
// public void setNetworkName(String networkName) {
// this.networkName = networkName;
// }
//
// public Tunnel getTunnel() {
// return tunnel;
// }
//
// public void setTunnel(Tunnel tunnel) {
// this.tunnel = tunnel;
// }
//
// public Adapter getAdapter() {
// return adapter;
// }
//
// public void setAdapter(Adapter adapter) {
// this.adapter = adapter;
// }
//
// public NetworkType getNetworkType() {
// return networkType;
// }
//
// public void setNetworkType(NetworkType networkType) {
// this.networkType = networkType;
// }
//
// public boolean isNeedsAuthentication() {
// return needsAuthentication;
// }
//
// public void setNeedsAuthentication(boolean needsAuthentication) {
// this.needsAuthentication = needsAuthentication;
// }
//
// public String getNetaddress() {
// return netaddress;
// }
//
// public String getProtocol() {
// return protocol.name().toLowerCase();
// }
//
// public void setNetaddress(String netaddress) {
// this.netaddress = netaddress;
// }
//
// public int getSubnetmask() {
// return subnetmask;
// }
//
// public void setSubnetmask(short subnetmask) {
// this.subnetmask = subnetmask;
// }
//
// public Mediator getMediator() {
// return mediator;
// }
//
// public void setMediator(Mediator mediator) {
// this.mediator = mediator;
// }
//
// }
//
// Path: src/main/java/de/hartz/vpn/mediation/Mediator.java
// public class Mediator implements Serializable {
//
// private String mediatorName;
// private String url;
// // Only needed if mediationserver hosts network specific files.
// private int metaServerPort;
// private int udpHolePunchingPort;
//
// // If true the url is a rest api showing the original ip of the mediator, needed for dynamic ips.
// private boolean redirectFromUrl;
//
// public Mediator(String mediatorName,String url, int metaServerPort, int udpHolePunchingPort, boolean redirectFromUrl) {
// this.mediatorName = mediatorName;
// this.url = url;
// this.metaServerPort = metaServerPort;
// this.udpHolePunchingPort = udpHolePunchingPort;
// this.redirectFromUrl = redirectFromUrl;
// }
//
// public String getMediatorName() {
// return mediatorName;
// }
//
// public int getMetaServerPort() {
// return metaServerPort;
// }
//
// public int getUdpHolePunchingPort() {
// return udpHolePunchingPort;
// }
//
// public boolean isRedirectFromUrl() {
// return redirectFromUrl;
// }
//
// /**
// * Get the real url or ip of the mediator server.
// * @returns the url of the mediator.
// */
// public String getUrl() {
// if (!redirectFromUrl) {
// return url;
// }
// try {
// URL whatIsMyIp = new URL(url);
// BufferedReader in = new BufferedReader(new InputStreamReader(whatIsMyIp.openStream()));
// String ip = in.readLine();
// return ip;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
//
// Path: src/main/java/de/hartz/vpn/utilities/Constants.java
// public static final String USER_DATA_FILE_PATH = System.getProperty("user.home") + File.separator + "." + SOFTWARE_NAME + File.separator + "userData.ser";
|
import de.hartz.vpn.main.server.ConfigState;
import de.hartz.vpn.mediation.Mediator;
import java.io.*;
import java.util.ArrayList;
import static de.hartz.vpn.utilities.Constants.USER_DATA_FILE_PATH;
|
package de.hartz.vpn.main;
/**
* Hold the data for the current session of this user.
*/
public class UserData implements Serializable{
private static UserData instance;
private UserList userList = new UserList();
private ArrayList<Mediator> mediatorList = new ArrayList<>();
//client only.
public static String serverIp;
public static Integer serverPort;
//END OF: client only.
private boolean clientInstallation = true;
|
// Path: src/main/java/de/hartz/vpn/main/server/ConfigState.java
// public class ConfigState implements Serializable {
//
// public enum Adapter {
// OpenVPN,
// IPsec,
// FreeLan
// }
//
// // TODO: Tcp not supported by mediator.
// public enum Protocol {
// TCP,
// UDP
// }
//
// // TODO: Closed tunnel not supported by software. Needs networkbridge between adapters (?)
// public enum Tunnel {
// CLOSED,
// SPLIT
// }
//
// // TODO: Site connections needs traffic redirection by every computer or the gateway to vpn-gateway. Not really supported by Software.
// public enum NetworkType {
// SITE_TO_SITE,
// SITE_TO_END,
// END_TO_END,
// }
//
// private String networkName;
// private Protocol protocol;
//
// private Mediator mediator;
//
// private Tunnel tunnel;
// private Adapter adapter;
// private NetworkType networkType;
//
// private boolean needsAuthentication;
//
// private String netaddress;
// private short subnetmask;
//
// /**
// * Default Constructor for Express Configuration.
// */
// public ConfigState() {
// tunnel = Tunnel.SPLIT;
// adapter = Adapter.OpenVPN;
// networkType = NetworkType.END_TO_END;
// protocol = UDP;
// netaddress = NetworkUtilities.getRecommendedIp();
// subnetmask = 24;
//
// needsAuthentication = false;
// }
//
// public String getNetworkName() {
// return networkName;
// }
//
// public void setNetworkName(String networkName) {
// this.networkName = networkName;
// }
//
// public Tunnel getTunnel() {
// return tunnel;
// }
//
// public void setTunnel(Tunnel tunnel) {
// this.tunnel = tunnel;
// }
//
// public Adapter getAdapter() {
// return adapter;
// }
//
// public void setAdapter(Adapter adapter) {
// this.adapter = adapter;
// }
//
// public NetworkType getNetworkType() {
// return networkType;
// }
//
// public void setNetworkType(NetworkType networkType) {
// this.networkType = networkType;
// }
//
// public boolean isNeedsAuthentication() {
// return needsAuthentication;
// }
//
// public void setNeedsAuthentication(boolean needsAuthentication) {
// this.needsAuthentication = needsAuthentication;
// }
//
// public String getNetaddress() {
// return netaddress;
// }
//
// public String getProtocol() {
// return protocol.name().toLowerCase();
// }
//
// public void setNetaddress(String netaddress) {
// this.netaddress = netaddress;
// }
//
// public int getSubnetmask() {
// return subnetmask;
// }
//
// public void setSubnetmask(short subnetmask) {
// this.subnetmask = subnetmask;
// }
//
// public Mediator getMediator() {
// return mediator;
// }
//
// public void setMediator(Mediator mediator) {
// this.mediator = mediator;
// }
//
// }
//
// Path: src/main/java/de/hartz/vpn/mediation/Mediator.java
// public class Mediator implements Serializable {
//
// private String mediatorName;
// private String url;
// // Only needed if mediationserver hosts network specific files.
// private int metaServerPort;
// private int udpHolePunchingPort;
//
// // If true the url is a rest api showing the original ip of the mediator, needed for dynamic ips.
// private boolean redirectFromUrl;
//
// public Mediator(String mediatorName,String url, int metaServerPort, int udpHolePunchingPort, boolean redirectFromUrl) {
// this.mediatorName = mediatorName;
// this.url = url;
// this.metaServerPort = metaServerPort;
// this.udpHolePunchingPort = udpHolePunchingPort;
// this.redirectFromUrl = redirectFromUrl;
// }
//
// public String getMediatorName() {
// return mediatorName;
// }
//
// public int getMetaServerPort() {
// return metaServerPort;
// }
//
// public int getUdpHolePunchingPort() {
// return udpHolePunchingPort;
// }
//
// public boolean isRedirectFromUrl() {
// return redirectFromUrl;
// }
//
// /**
// * Get the real url or ip of the mediator server.
// * @returns the url of the mediator.
// */
// public String getUrl() {
// if (!redirectFromUrl) {
// return url;
// }
// try {
// URL whatIsMyIp = new URL(url);
// BufferedReader in = new BufferedReader(new InputStreamReader(whatIsMyIp.openStream()));
// String ip = in.readLine();
// return ip;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
//
// Path: src/main/java/de/hartz/vpn/utilities/Constants.java
// public static final String USER_DATA_FILE_PATH = System.getProperty("user.home") + File.separator + "." + SOFTWARE_NAME + File.separator + "userData.ser";
// Path: src/main/java/de/hartz/vpn/main/UserData.java
import de.hartz.vpn.main.server.ConfigState;
import de.hartz.vpn.mediation.Mediator;
import java.io.*;
import java.util.ArrayList;
import static de.hartz.vpn.utilities.Constants.USER_DATA_FILE_PATH;
package de.hartz.vpn.main;
/**
* Hold the data for the current session of this user.
*/
public class UserData implements Serializable{
private static UserData instance;
private UserList userList = new UserList();
private ArrayList<Mediator> mediatorList = new ArrayList<>();
//client only.
public static String serverIp;
public static Integer serverPort;
//END OF: client only.
private boolean clientInstallation = true;
|
private ConfigState vpnConfigState;
|
Hatzen/EasyPeasyVPN
|
src/main/java/de/hartz/vpn/main/UserData.java
|
// Path: src/main/java/de/hartz/vpn/main/server/ConfigState.java
// public class ConfigState implements Serializable {
//
// public enum Adapter {
// OpenVPN,
// IPsec,
// FreeLan
// }
//
// // TODO: Tcp not supported by mediator.
// public enum Protocol {
// TCP,
// UDP
// }
//
// // TODO: Closed tunnel not supported by software. Needs networkbridge between adapters (?)
// public enum Tunnel {
// CLOSED,
// SPLIT
// }
//
// // TODO: Site connections needs traffic redirection by every computer or the gateway to vpn-gateway. Not really supported by Software.
// public enum NetworkType {
// SITE_TO_SITE,
// SITE_TO_END,
// END_TO_END,
// }
//
// private String networkName;
// private Protocol protocol;
//
// private Mediator mediator;
//
// private Tunnel tunnel;
// private Adapter adapter;
// private NetworkType networkType;
//
// private boolean needsAuthentication;
//
// private String netaddress;
// private short subnetmask;
//
// /**
// * Default Constructor for Express Configuration.
// */
// public ConfigState() {
// tunnel = Tunnel.SPLIT;
// adapter = Adapter.OpenVPN;
// networkType = NetworkType.END_TO_END;
// protocol = UDP;
// netaddress = NetworkUtilities.getRecommendedIp();
// subnetmask = 24;
//
// needsAuthentication = false;
// }
//
// public String getNetworkName() {
// return networkName;
// }
//
// public void setNetworkName(String networkName) {
// this.networkName = networkName;
// }
//
// public Tunnel getTunnel() {
// return tunnel;
// }
//
// public void setTunnel(Tunnel tunnel) {
// this.tunnel = tunnel;
// }
//
// public Adapter getAdapter() {
// return adapter;
// }
//
// public void setAdapter(Adapter adapter) {
// this.adapter = adapter;
// }
//
// public NetworkType getNetworkType() {
// return networkType;
// }
//
// public void setNetworkType(NetworkType networkType) {
// this.networkType = networkType;
// }
//
// public boolean isNeedsAuthentication() {
// return needsAuthentication;
// }
//
// public void setNeedsAuthentication(boolean needsAuthentication) {
// this.needsAuthentication = needsAuthentication;
// }
//
// public String getNetaddress() {
// return netaddress;
// }
//
// public String getProtocol() {
// return protocol.name().toLowerCase();
// }
//
// public void setNetaddress(String netaddress) {
// this.netaddress = netaddress;
// }
//
// public int getSubnetmask() {
// return subnetmask;
// }
//
// public void setSubnetmask(short subnetmask) {
// this.subnetmask = subnetmask;
// }
//
// public Mediator getMediator() {
// return mediator;
// }
//
// public void setMediator(Mediator mediator) {
// this.mediator = mediator;
// }
//
// }
//
// Path: src/main/java/de/hartz/vpn/mediation/Mediator.java
// public class Mediator implements Serializable {
//
// private String mediatorName;
// private String url;
// // Only needed if mediationserver hosts network specific files.
// private int metaServerPort;
// private int udpHolePunchingPort;
//
// // If true the url is a rest api showing the original ip of the mediator, needed for dynamic ips.
// private boolean redirectFromUrl;
//
// public Mediator(String mediatorName,String url, int metaServerPort, int udpHolePunchingPort, boolean redirectFromUrl) {
// this.mediatorName = mediatorName;
// this.url = url;
// this.metaServerPort = metaServerPort;
// this.udpHolePunchingPort = udpHolePunchingPort;
// this.redirectFromUrl = redirectFromUrl;
// }
//
// public String getMediatorName() {
// return mediatorName;
// }
//
// public int getMetaServerPort() {
// return metaServerPort;
// }
//
// public int getUdpHolePunchingPort() {
// return udpHolePunchingPort;
// }
//
// public boolean isRedirectFromUrl() {
// return redirectFromUrl;
// }
//
// /**
// * Get the real url or ip of the mediator server.
// * @returns the url of the mediator.
// */
// public String getUrl() {
// if (!redirectFromUrl) {
// return url;
// }
// try {
// URL whatIsMyIp = new URL(url);
// BufferedReader in = new BufferedReader(new InputStreamReader(whatIsMyIp.openStream()));
// String ip = in.readLine();
// return ip;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
//
// Path: src/main/java/de/hartz/vpn/utilities/Constants.java
// public static final String USER_DATA_FILE_PATH = System.getProperty("user.home") + File.separator + "." + SOFTWARE_NAME + File.separator + "userData.ser";
|
import de.hartz.vpn.main.server.ConfigState;
import de.hartz.vpn.mediation.Mediator;
import java.io.*;
import java.util.ArrayList;
import static de.hartz.vpn.utilities.Constants.USER_DATA_FILE_PATH;
|
this.clientInstallation = clientInstallation;
}
/**
* Sets the current vpn config state and saves it persistent.
*/
public ConfigState getVpnConfigState() {
return vpnConfigState;
}
/**
* Sets the current vpn config state and saves it persistent.
*/
public void setVpnConfigState(ConfigState configState) {
vpnConfigState = configState;
writeUserData();
}
private UserData() {
if (mediatorList.size() == 0) {
mediatorList.add(new Mediator("DEFAULT","http://hartzkai.freehostia.com/thesis/", -1, -1, true));
}
}
/**
* Loads an old user data object.
* @returns true if the data was loaded successfully.
*/
private static boolean loadUserData() {
try {
|
// Path: src/main/java/de/hartz/vpn/main/server/ConfigState.java
// public class ConfigState implements Serializable {
//
// public enum Adapter {
// OpenVPN,
// IPsec,
// FreeLan
// }
//
// // TODO: Tcp not supported by mediator.
// public enum Protocol {
// TCP,
// UDP
// }
//
// // TODO: Closed tunnel not supported by software. Needs networkbridge between adapters (?)
// public enum Tunnel {
// CLOSED,
// SPLIT
// }
//
// // TODO: Site connections needs traffic redirection by every computer or the gateway to vpn-gateway. Not really supported by Software.
// public enum NetworkType {
// SITE_TO_SITE,
// SITE_TO_END,
// END_TO_END,
// }
//
// private String networkName;
// private Protocol protocol;
//
// private Mediator mediator;
//
// private Tunnel tunnel;
// private Adapter adapter;
// private NetworkType networkType;
//
// private boolean needsAuthentication;
//
// private String netaddress;
// private short subnetmask;
//
// /**
// * Default Constructor for Express Configuration.
// */
// public ConfigState() {
// tunnel = Tunnel.SPLIT;
// adapter = Adapter.OpenVPN;
// networkType = NetworkType.END_TO_END;
// protocol = UDP;
// netaddress = NetworkUtilities.getRecommendedIp();
// subnetmask = 24;
//
// needsAuthentication = false;
// }
//
// public String getNetworkName() {
// return networkName;
// }
//
// public void setNetworkName(String networkName) {
// this.networkName = networkName;
// }
//
// public Tunnel getTunnel() {
// return tunnel;
// }
//
// public void setTunnel(Tunnel tunnel) {
// this.tunnel = tunnel;
// }
//
// public Adapter getAdapter() {
// return adapter;
// }
//
// public void setAdapter(Adapter adapter) {
// this.adapter = adapter;
// }
//
// public NetworkType getNetworkType() {
// return networkType;
// }
//
// public void setNetworkType(NetworkType networkType) {
// this.networkType = networkType;
// }
//
// public boolean isNeedsAuthentication() {
// return needsAuthentication;
// }
//
// public void setNeedsAuthentication(boolean needsAuthentication) {
// this.needsAuthentication = needsAuthentication;
// }
//
// public String getNetaddress() {
// return netaddress;
// }
//
// public String getProtocol() {
// return protocol.name().toLowerCase();
// }
//
// public void setNetaddress(String netaddress) {
// this.netaddress = netaddress;
// }
//
// public int getSubnetmask() {
// return subnetmask;
// }
//
// public void setSubnetmask(short subnetmask) {
// this.subnetmask = subnetmask;
// }
//
// public Mediator getMediator() {
// return mediator;
// }
//
// public void setMediator(Mediator mediator) {
// this.mediator = mediator;
// }
//
// }
//
// Path: src/main/java/de/hartz/vpn/mediation/Mediator.java
// public class Mediator implements Serializable {
//
// private String mediatorName;
// private String url;
// // Only needed if mediationserver hosts network specific files.
// private int metaServerPort;
// private int udpHolePunchingPort;
//
// // If true the url is a rest api showing the original ip of the mediator, needed for dynamic ips.
// private boolean redirectFromUrl;
//
// public Mediator(String mediatorName,String url, int metaServerPort, int udpHolePunchingPort, boolean redirectFromUrl) {
// this.mediatorName = mediatorName;
// this.url = url;
// this.metaServerPort = metaServerPort;
// this.udpHolePunchingPort = udpHolePunchingPort;
// this.redirectFromUrl = redirectFromUrl;
// }
//
// public String getMediatorName() {
// return mediatorName;
// }
//
// public int getMetaServerPort() {
// return metaServerPort;
// }
//
// public int getUdpHolePunchingPort() {
// return udpHolePunchingPort;
// }
//
// public boolean isRedirectFromUrl() {
// return redirectFromUrl;
// }
//
// /**
// * Get the real url or ip of the mediator server.
// * @returns the url of the mediator.
// */
// public String getUrl() {
// if (!redirectFromUrl) {
// return url;
// }
// try {
// URL whatIsMyIp = new URL(url);
// BufferedReader in = new BufferedReader(new InputStreamReader(whatIsMyIp.openStream()));
// String ip = in.readLine();
// return ip;
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
//
// Path: src/main/java/de/hartz/vpn/utilities/Constants.java
// public static final String USER_DATA_FILE_PATH = System.getProperty("user.home") + File.separator + "." + SOFTWARE_NAME + File.separator + "userData.ser";
// Path: src/main/java/de/hartz/vpn/main/UserData.java
import de.hartz.vpn.main.server.ConfigState;
import de.hartz.vpn.mediation.Mediator;
import java.io.*;
import java.util.ArrayList;
import static de.hartz.vpn.utilities.Constants.USER_DATA_FILE_PATH;
this.clientInstallation = clientInstallation;
}
/**
* Sets the current vpn config state and saves it persistent.
*/
public ConfigState getVpnConfigState() {
return vpnConfigState;
}
/**
* Sets the current vpn config state and saves it persistent.
*/
public void setVpnConfigState(ConfigState configState) {
vpnConfigState = configState;
writeUserData();
}
private UserData() {
if (mediatorList.size() == 0) {
mediatorList.add(new Mediator("DEFAULT","http://hartzkai.freehostia.com/thesis/", -1, -1, true));
}
}
/**
* Loads an old user data object.
* @returns true if the data was loaded successfully.
*/
private static boolean loadUserData() {
try {
|
FileInputStream fin = new FileInputStream(USER_DATA_FILE_PATH);
|
Hatzen/EasyPeasyVPN
|
src/main/java/de/hartz/vpn/main/installation/InstallationFrame.java
|
// Path: src/main/java/de/hartz/vpn/utilities/UiUtilities.java
// public final class UiUtilities {
//
// /**
// * Shows an error window to inform the user.
// * https://stackoverflow.com/questions/9119481/how-to-present-a-simple-alert-message-in-java
// * @param text The text that will be displayed in the window.
// */
// public static void showAlert(String text) {
// // TODO: Respect show gui and maybe write it to the console.
// Toolkit.getDefaultToolkit().beep();
// JOptionPane optionPane = new JOptionPane(text,JOptionPane.ERROR_MESSAGE);
// JDialog dialog = optionPane.createDialog("Error");
// dialog.setAlwaysOnTop(true);
// dialog.setVisible(true);
// }
//
// /**
// * Sets the icon and look and feel of a jframe. Because its needed at serveral places.
// * @param frame the frame to setup.
// */
// public static void setLookAndFeelAndIcon(JFrame frame) {
// try {
// File file = GeneralUtilities.getResourceAsFile("icon.png");
// Image image = ImageIO.read( file );
// frame.setIconImage(image);
// } catch (IOException | NullPointerException e) {
// e.printStackTrace();
// }
// try {
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// } catch (ClassNotFoundException | UnsupportedLookAndFeelException | InstantiationException | IllegalAccessException e) {
// e.printStackTrace();
// }
// }
//
// /**
// * Needed for sizing components.
// * @param component to respect his size.
// * @returns the wrapper to simply add.
// */
// public static JPanel getComponentWrapper(JComponent component) {
// JPanel wrapper = new JPanel();
// wrapper.setLayout(new BoxLayout(wrapper, BoxLayout.Y_AXIS));
// wrapper.add(component);
// return wrapper;
// }
//
// }
|
import de.hartz.vpn.utilities.UiUtilities;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
|
package de.hartz.vpn.main.installation;
/**
* The gui for the {@link InstallationController}.
*/
public class InstallationFrame extends JFrame implements ActionListener {
private JPanel content;
private InstallationPanel currentContentPanel;
private JButton nextButton;
private JButton previousButton;
public InstallationFrame(String title) {
setTitle(title);
setMinimumSize(new Dimension(500,500));
setLocationRelativeTo(null);
setLayout(new BorderLayout());
setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
|
// Path: src/main/java/de/hartz/vpn/utilities/UiUtilities.java
// public final class UiUtilities {
//
// /**
// * Shows an error window to inform the user.
// * https://stackoverflow.com/questions/9119481/how-to-present-a-simple-alert-message-in-java
// * @param text The text that will be displayed in the window.
// */
// public static void showAlert(String text) {
// // TODO: Respect show gui and maybe write it to the console.
// Toolkit.getDefaultToolkit().beep();
// JOptionPane optionPane = new JOptionPane(text,JOptionPane.ERROR_MESSAGE);
// JDialog dialog = optionPane.createDialog("Error");
// dialog.setAlwaysOnTop(true);
// dialog.setVisible(true);
// }
//
// /**
// * Sets the icon and look and feel of a jframe. Because its needed at serveral places.
// * @param frame the frame to setup.
// */
// public static void setLookAndFeelAndIcon(JFrame frame) {
// try {
// File file = GeneralUtilities.getResourceAsFile("icon.png");
// Image image = ImageIO.read( file );
// frame.setIconImage(image);
// } catch (IOException | NullPointerException e) {
// e.printStackTrace();
// }
// try {
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// } catch (ClassNotFoundException | UnsupportedLookAndFeelException | InstantiationException | IllegalAccessException e) {
// e.printStackTrace();
// }
// }
//
// /**
// * Needed for sizing components.
// * @param component to respect his size.
// * @returns the wrapper to simply add.
// */
// public static JPanel getComponentWrapper(JComponent component) {
// JPanel wrapper = new JPanel();
// wrapper.setLayout(new BoxLayout(wrapper, BoxLayout.Y_AXIS));
// wrapper.add(component);
// return wrapper;
// }
//
// }
// Path: src/main/java/de/hartz/vpn/main/installation/InstallationFrame.java
import de.hartz.vpn.utilities.UiUtilities;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
package de.hartz.vpn.main.installation;
/**
* The gui for the {@link InstallationController}.
*/
public class InstallationFrame extends JFrame implements ActionListener {
private JPanel content;
private InstallationPanel currentContentPanel;
private JButton nextButton;
private JButton previousButton;
public InstallationFrame(String title) {
setTitle(title);
setMinimumSize(new Dimension(500,500));
setLocationRelativeTo(null);
setLayout(new BorderLayout());
setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
|
UiUtilities.setLookAndFeelAndIcon(this);
|
yacy/cider
|
src/org/dspace/foresite/jena/GraphResource.java
|
// Path: src/org/dspace/foresite/OREException.java
// public class OREException extends Exception
// {
// /**
// *
// */
// private static final long serialVersionUID = -6100509872905859495L;
//
// public OREException()
// {
// super();
// }
//
// public OREException(String s)
// {
// super(s);
// }
//
// public OREException(String s, Throwable throwable)
// {
// super(s, throwable);
// }
//
// public OREException(Throwable throwable)
// {
// super(throwable);
// }
// }
|
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.AnonId;
import java.net.URI;
import org.dspace.foresite.OREException;
|
/*
* GraphResource.java
*
* Copyright (c) 2008, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.foresite.jena;
/**
* @Author Richard Jones
*/
public interface GraphResource
{
Resource getResource();
void setResource(Resource resource);
Model getModel();
|
// Path: src/org/dspace/foresite/OREException.java
// public class OREException extends Exception
// {
// /**
// *
// */
// private static final long serialVersionUID = -6100509872905859495L;
//
// public OREException()
// {
// super();
// }
//
// public OREException(String s)
// {
// super(s);
// }
//
// public OREException(String s, Throwable throwable)
// {
// super(s, throwable);
// }
//
// public OREException(Throwable throwable)
// {
// super(throwable);
// }
// }
// Path: src/org/dspace/foresite/jena/GraphResource.java
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.AnonId;
import java.net.URI;
import org.dspace.foresite.OREException;
/*
* GraphResource.java
*
* Copyright (c) 2008, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.foresite.jena;
/**
* @Author Richard Jones
*/
public interface GraphResource
{
Resource getResource();
void setResource(Resource resource);
Model getModel();
|
void setModel(Model model, URI resourceURI) throws OREException;
|
asciidoctor/asciidoctorj
|
asciidoctorj-springboot-integration-test/src/test/java/org/asciidoctor/it/springboot/SpringBootTest.java
|
// Path: asciidoctorj-springboot-integration-test/src/test/java/org/asciidoctor/it/springboot/ProcessHelper.java
// static ProcessOutput run(Map<String, String> env, String... command) throws IOException, InterruptedException {
// ProcessBuilder processBuilder = new ProcessBuilder(command)
// .directory(new File("springboot-app"));
//
// processBuilder.environment().clear();
// String javaHome = System.getProperty("java.home");
// processBuilder.environment().put("JAVA_HOME", javaHome);
// processBuilder.environment().put("PATH", javaHome + "/bin");
// processBuilder.environment().putAll(env);
//
// Process process = processBuilder.start();
//
// final InputStream is = process.getInputStream();
// final InputStream es = process.getErrorStream();
// boolean status = process.waitFor(10l, TimeUnit.SECONDS);
// if (!status) {
// byte[] buffer = new byte[1800];
// IOUtils.read(is, buffer);
// return new ProcessOutput(process, new String(buffer), new String());
// }
//
// return new ProcessOutput(IOUtils.toString(es), IOUtils.toString(is));
// }
|
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import kotlin.collections.ArrayDeque;
import okhttp3.*;
import org.awaitility.Awaitility;
import org.junit.After;
import org.junit.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
import static org.asciidoctor.it.springboot.ProcessHelper.run;
import static org.assertj.core.api.Assertions.assertThat;
|
@After
public void cleanup() {
testProcesses.forEach(Process::destroy);
}
private Map<String, String> convertDocument(String asciidocDocument, int serverPort) throws IOException {
String body = "{\"data\":\"" + base64Encode(asciidocDocument) + "\"}";
Request request = new Request.Builder()
.url("http://localhost:" + serverPort + "/asciidoc")
.post(RequestBody.create(body, MediaType.parse("application/json")))
.build();
Response response = new OkHttpClient()
.newCall(request)
.execute();
return new Gson()
.fromJson(response.body().string(), new TypeToken<Map<String, String>>() {}.getType());
}
private String base64Encode(String asciidocDocument) {
return new String(Base64.getEncoder().encode(asciidocDocument.getBytes(StandardCharsets.UTF_8)));
}
private String base64Decode(String value) {
return new String(Base64.getDecoder().decode(value));
}
private void startSpringBootApp(int serverPort) throws IOException, InterruptedException {
|
// Path: asciidoctorj-springboot-integration-test/src/test/java/org/asciidoctor/it/springboot/ProcessHelper.java
// static ProcessOutput run(Map<String, String> env, String... command) throws IOException, InterruptedException {
// ProcessBuilder processBuilder = new ProcessBuilder(command)
// .directory(new File("springboot-app"));
//
// processBuilder.environment().clear();
// String javaHome = System.getProperty("java.home");
// processBuilder.environment().put("JAVA_HOME", javaHome);
// processBuilder.environment().put("PATH", javaHome + "/bin");
// processBuilder.environment().putAll(env);
//
// Process process = processBuilder.start();
//
// final InputStream is = process.getInputStream();
// final InputStream es = process.getErrorStream();
// boolean status = process.waitFor(10l, TimeUnit.SECONDS);
// if (!status) {
// byte[] buffer = new byte[1800];
// IOUtils.read(is, buffer);
// return new ProcessOutput(process, new String(buffer), new String());
// }
//
// return new ProcessOutput(IOUtils.toString(es), IOUtils.toString(is));
// }
// Path: asciidoctorj-springboot-integration-test/src/test/java/org/asciidoctor/it/springboot/SpringBootTest.java
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import kotlin.collections.ArrayDeque;
import okhttp3.*;
import org.awaitility.Awaitility;
import org.junit.After;
import org.junit.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
import static org.asciidoctor.it.springboot.ProcessHelper.run;
import static org.assertj.core.api.Assertions.assertThat;
@After
public void cleanup() {
testProcesses.forEach(Process::destroy);
}
private Map<String, String> convertDocument(String asciidocDocument, int serverPort) throws IOException {
String body = "{\"data\":\"" + base64Encode(asciidocDocument) + "\"}";
Request request = new Request.Builder()
.url("http://localhost:" + serverPort + "/asciidoc")
.post(RequestBody.create(body, MediaType.parse("application/json")))
.build();
Response response = new OkHttpClient()
.newCall(request)
.execute();
return new Gson()
.fromJson(response.body().string(), new TypeToken<Map<String, String>>() {}.getType());
}
private String base64Encode(String asciidocDocument) {
return new String(Base64.getEncoder().encode(asciidocDocument.getBytes(StandardCharsets.UTF_8)));
}
private String base64Decode(String value) {
return new String(Base64.getDecoder().decode(value));
}
private void startSpringBootApp(int serverPort) throws IOException, InterruptedException {
|
ProcessHelper.ProcessOutput run = run(singletonMap("SERVER_PORT", String.valueOf(serverPort)),
|
asciidoctor/asciidoctorj
|
asciidoctorj-core/src/main/java/org/asciidoctor/jruby/ast/impl/DocumentHeaderImpl.java
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/DocumentHeader.java
// @Deprecated
// public interface DocumentHeader {
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// List<Author> getAuthors();
//
// /**
// * @deprecated Use {@link Document#getStructuredDoctitle()} instead.
// */
// @Deprecated
// Title getDocumentTitle();
//
// /**
// * @deprecated Use {@link Document#getDoctitle()} instead.
// */
// @Deprecated
// String getPageTitle();
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// Author getAuthor();
//
// /**
// * @deprecated Use {@link Document#getRevisionInfo()} instead.
// */
// @Deprecated
// RevisionInfo getRevisionInfo();
//
// /**
// * @deprecated Use {@link Document#getAttributes()} instead.
// */
// @Deprecated
// Map<String, Object> getAttributes();
// }
//
// Path: asciidoctorj-core/src/main/java/org/asciidoctor/jruby/internal/CaseInsensitiveMap.java
// public class CaseInsensitiveMap<K extends String, V> implements Map<K, V> {
//
// private Map<K, V> map;
//
// public CaseInsensitiveMap() {
// this(new HashMap<K, V>());
// }
//
// public CaseInsensitiveMap(Map<K, V> map) {
// this.map = map;
// }
//
// @Override
// public void clear() {
// map.clear();
// }
//
// @Override
// public boolean containsKey(Object key) {
// if (key instanceof String) {
// return map.containsKey(((String) key).toLowerCase());
// } else {
// return map.containsKey(key);
// }
// }
//
// @Override
// public boolean containsValue(Object value) {
// return map.containsValue(value);
// }
//
// @Override
// public Set<java.util.Map.Entry<K, V>> entrySet() {
// return map.entrySet();
// }
//
// @Override
// public V get(Object key) {
// if (key instanceof String) {
// return map.get(((String) key).toLowerCase());
// } else {
// return map.get(key);
// }
// }
//
// @Override
// public boolean isEmpty() {
// return map.isEmpty();
// }
//
// @Override
// public Set<K> keySet() {
// return map.keySet();
// }
//
// @Override
// public V put(K key, V value) {
// return map.put((K) key.toLowerCase(), value);
// }
//
// @Override
// public void putAll(Map<? extends K, ? extends V> m) {
// for (Entry<? extends String, ? extends V> entry : m.entrySet()) {
// map.put((K) entry.getKey().toLowerCase(), entry.getValue());
// }
// }
//
// @Override
// public V remove(Object key) {
// if (key instanceof String) {
// return map.remove(((String) key).toLowerCase());
// } else {
// return map.remove(key);
// }
// }
//
// @Override
// public int size() {
// return map.size();
// }
//
// @Override
// public Collection<V> values() {
// return map.values();
// }
//
// }
|
import org.asciidoctor.ast.Author;
import org.asciidoctor.ast.DocumentHeader;
import org.asciidoctor.ast.RevisionInfo;
import org.asciidoctor.ast.Title;
import org.asciidoctor.jruby.internal.CaseInsensitiveMap;
import java.util.List;
import java.util.Map;
|
return this.authors;
}
public Title getDocumentTitle() {
return documentTitle;
}
public String getPageTitle() {
return pageTitle;
}
public Author getAuthor() {
return authors == null || authors.size() == 0 ? null : authors.get(0);
}
public RevisionInfo getRevisionInfo() {
return revisionInfo;
}
public Map<String, Object> getAttributes() {
return attributes;
}
public static DocumentHeaderImpl createDocumentHeader(Title documentTitle, String pageTitle,
List<Author> authors, Map<String, Object> attributes) {
DocumentHeaderImpl documentHeader = new DocumentHeaderImpl();
documentHeader.documentTitle = documentTitle;
documentHeader.pageTitle = pageTitle;
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/DocumentHeader.java
// @Deprecated
// public interface DocumentHeader {
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// List<Author> getAuthors();
//
// /**
// * @deprecated Use {@link Document#getStructuredDoctitle()} instead.
// */
// @Deprecated
// Title getDocumentTitle();
//
// /**
// * @deprecated Use {@link Document#getDoctitle()} instead.
// */
// @Deprecated
// String getPageTitle();
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// Author getAuthor();
//
// /**
// * @deprecated Use {@link Document#getRevisionInfo()} instead.
// */
// @Deprecated
// RevisionInfo getRevisionInfo();
//
// /**
// * @deprecated Use {@link Document#getAttributes()} instead.
// */
// @Deprecated
// Map<String, Object> getAttributes();
// }
//
// Path: asciidoctorj-core/src/main/java/org/asciidoctor/jruby/internal/CaseInsensitiveMap.java
// public class CaseInsensitiveMap<K extends String, V> implements Map<K, V> {
//
// private Map<K, V> map;
//
// public CaseInsensitiveMap() {
// this(new HashMap<K, V>());
// }
//
// public CaseInsensitiveMap(Map<K, V> map) {
// this.map = map;
// }
//
// @Override
// public void clear() {
// map.clear();
// }
//
// @Override
// public boolean containsKey(Object key) {
// if (key instanceof String) {
// return map.containsKey(((String) key).toLowerCase());
// } else {
// return map.containsKey(key);
// }
// }
//
// @Override
// public boolean containsValue(Object value) {
// return map.containsValue(value);
// }
//
// @Override
// public Set<java.util.Map.Entry<K, V>> entrySet() {
// return map.entrySet();
// }
//
// @Override
// public V get(Object key) {
// if (key instanceof String) {
// return map.get(((String) key).toLowerCase());
// } else {
// return map.get(key);
// }
// }
//
// @Override
// public boolean isEmpty() {
// return map.isEmpty();
// }
//
// @Override
// public Set<K> keySet() {
// return map.keySet();
// }
//
// @Override
// public V put(K key, V value) {
// return map.put((K) key.toLowerCase(), value);
// }
//
// @Override
// public void putAll(Map<? extends K, ? extends V> m) {
// for (Entry<? extends String, ? extends V> entry : m.entrySet()) {
// map.put((K) entry.getKey().toLowerCase(), entry.getValue());
// }
// }
//
// @Override
// public V remove(Object key) {
// if (key instanceof String) {
// return map.remove(((String) key).toLowerCase());
// } else {
// return map.remove(key);
// }
// }
//
// @Override
// public int size() {
// return map.size();
// }
//
// @Override
// public Collection<V> values() {
// return map.values();
// }
//
// }
// Path: asciidoctorj-core/src/main/java/org/asciidoctor/jruby/ast/impl/DocumentHeaderImpl.java
import org.asciidoctor.ast.Author;
import org.asciidoctor.ast.DocumentHeader;
import org.asciidoctor.ast.RevisionInfo;
import org.asciidoctor.ast.Title;
import org.asciidoctor.jruby.internal.CaseInsensitiveMap;
import java.util.List;
import java.util.Map;
return this.authors;
}
public Title getDocumentTitle() {
return documentTitle;
}
public String getPageTitle() {
return pageTitle;
}
public Author getAuthor() {
return authors == null || authors.size() == 0 ? null : authors.get(0);
}
public RevisionInfo getRevisionInfo() {
return revisionInfo;
}
public Map<String, Object> getAttributes() {
return attributes;
}
public static DocumentHeaderImpl createDocumentHeader(Title documentTitle, String pageTitle,
List<Author> authors, Map<String, Object> attributes) {
DocumentHeaderImpl documentHeader = new DocumentHeaderImpl();
documentHeader.documentTitle = documentTitle;
documentHeader.pageTitle = pageTitle;
|
documentHeader.attributes = new CaseInsensitiveMap<>(attributes);
|
asciidoctor/asciidoctorj
|
asciidoctorj-core/src/test/java/org/asciidoctor/extension/WhenRubyExtensionIsRegistered.java
|
// Path: asciidoctorj-core/src/main/java/org/asciidoctor/jruby/AsciidoctorJRuby.java
// public interface AsciidoctorJRuby extends Asciidoctor {
//
//
// /**
// * Factory for creating a new instance of Asciidoctor interface.
// *
// * @author lordofthejars
// */
// public static final class Factory {
//
// private Factory() {
// }
//
// /**
// * Creates a new instance of Asciidoctor.
// *
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create() {
// return JRubyAsciidoctor.create();
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets GEM_PATH environment
// * variable to provided gemPath. This method is mostly used in OSGi
// * environments.
// *
// * @param gemPath where gems are located.
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create(String gemPath) {
// return JRubyAsciidoctor.create(gemPath);
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets loadPath to provided paths. This method is mostly used in OSGi
// * environments.
// *
// * @param loadPaths where Ruby libraries are located.
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create(List<String> loadPaths) {
// return JRubyAsciidoctor.create(loadPaths);
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets a specific classloader for the JRuby runtime to use.
// * This method is for use in environments like OSGi.
// * To initialize Asciidoctor in OSGi create the Asciidoctor instance like this:
// *
// * <pre>
// * org.jruby.javasupport.JavaEmbedUtils.initialize(Arrays.asList("uri:classloader:/gems/asciidoctor-1.5.8/lib"));
// * Asciidoctor asciidoctor = Asciidoctor.Factory.create(this.getClass().getClassLoader());
// * </pre>
// *
// * @param classloader
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create(ClassLoader classloader) {
// return JRubyAsciidoctor.create(classloader);
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets a specific classloader and gempath for the JRuby runtime to use.
// * This method is for use in environments like OSGi.
// * To initialize Asciidoctor in OSGi create the Asciidoctor instance like this:
// *
// * <pre>
// * org.jruby.javasupport.JavaEmbedUtils.initialize(Arrays.asList("uri:classloader:/gems/asciidoctor-1.5.8/lib"));
// * Asciidoctor asciidoctor = Asciidoctor.Factory.create(this.getClass().getClassLoader());
// * </pre>
// *
// * @param classloader
// * @param gemPath
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// */
// public static AsciidoctorJRuby create(ClassLoader classloader, String gemPath) {
// return JRubyAsciidoctor.create(classloader, gemPath);
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets loadPath to provided paths.
// * The gem path of the Ruby instance is set to the gemPath parameter.
// *
// * @param loadPaths where Ruby libraries are located.
// * @param gemPath where gems are located.
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create(List<String> loadPaths, String gemPath) {
// return JRubyAsciidoctor.create(loadPaths, gemPath);
// }
//
// }
//
//
// }
|
import org.asciidoctor.SafeMode;
import org.asciidoctor.arquillian.api.Unshared;
import org.asciidoctor.jruby.AsciidoctorJRuby;
import org.asciidoctor.util.ClasspathResources;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Iterator;
import static java.util.Collections.singletonList;
import static org.asciidoctor.OptionsBuilder.options;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
|
package org.asciidoctor.extension;
@RunWith(Arquillian.class)
public class WhenRubyExtensionIsRegistered {
@ArquillianResource
private ClasspathResources classpath;
@ArquillianResource(Unshared.class)
|
// Path: asciidoctorj-core/src/main/java/org/asciidoctor/jruby/AsciidoctorJRuby.java
// public interface AsciidoctorJRuby extends Asciidoctor {
//
//
// /**
// * Factory for creating a new instance of Asciidoctor interface.
// *
// * @author lordofthejars
// */
// public static final class Factory {
//
// private Factory() {
// }
//
// /**
// * Creates a new instance of Asciidoctor.
// *
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create() {
// return JRubyAsciidoctor.create();
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets GEM_PATH environment
// * variable to provided gemPath. This method is mostly used in OSGi
// * environments.
// *
// * @param gemPath where gems are located.
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create(String gemPath) {
// return JRubyAsciidoctor.create(gemPath);
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets loadPath to provided paths. This method is mostly used in OSGi
// * environments.
// *
// * @param loadPaths where Ruby libraries are located.
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create(List<String> loadPaths) {
// return JRubyAsciidoctor.create(loadPaths);
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets a specific classloader for the JRuby runtime to use.
// * This method is for use in environments like OSGi.
// * To initialize Asciidoctor in OSGi create the Asciidoctor instance like this:
// *
// * <pre>
// * org.jruby.javasupport.JavaEmbedUtils.initialize(Arrays.asList("uri:classloader:/gems/asciidoctor-1.5.8/lib"));
// * Asciidoctor asciidoctor = Asciidoctor.Factory.create(this.getClass().getClassLoader());
// * </pre>
// *
// * @param classloader
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create(ClassLoader classloader) {
// return JRubyAsciidoctor.create(classloader);
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets a specific classloader and gempath for the JRuby runtime to use.
// * This method is for use in environments like OSGi.
// * To initialize Asciidoctor in OSGi create the Asciidoctor instance like this:
// *
// * <pre>
// * org.jruby.javasupport.JavaEmbedUtils.initialize(Arrays.asList("uri:classloader:/gems/asciidoctor-1.5.8/lib"));
// * Asciidoctor asciidoctor = Asciidoctor.Factory.create(this.getClass().getClassLoader());
// * </pre>
// *
// * @param classloader
// * @param gemPath
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// */
// public static AsciidoctorJRuby create(ClassLoader classloader, String gemPath) {
// return JRubyAsciidoctor.create(classloader, gemPath);
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets loadPath to provided paths.
// * The gem path of the Ruby instance is set to the gemPath parameter.
// *
// * @param loadPaths where Ruby libraries are located.
// * @param gemPath where gems are located.
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create(List<String> loadPaths, String gemPath) {
// return JRubyAsciidoctor.create(loadPaths, gemPath);
// }
//
// }
//
//
// }
// Path: asciidoctorj-core/src/test/java/org/asciidoctor/extension/WhenRubyExtensionIsRegistered.java
import org.asciidoctor.SafeMode;
import org.asciidoctor.arquillian.api.Unshared;
import org.asciidoctor.jruby.AsciidoctorJRuby;
import org.asciidoctor.util.ClasspathResources;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Iterator;
import static java.util.Collections.singletonList;
import static org.asciidoctor.OptionsBuilder.options;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
package org.asciidoctor.extension;
@RunWith(Arquillian.class)
public class WhenRubyExtensionIsRegistered {
@ArquillianResource
private ClasspathResources classpath;
@ArquillianResource(Unshared.class)
|
private AsciidoctorJRuby asciidoctor;
|
asciidoctor/asciidoctorj
|
asciidoctorj-core/src/test/java/org/asciidoctor/WhenAnAsciidoctorJInstanceIsRequired.java
|
// Path: asciidoctorj-core/src/main/java/org/asciidoctor/jruby/AsciidoctorJRuby.java
// public interface AsciidoctorJRuby extends Asciidoctor {
//
//
// /**
// * Factory for creating a new instance of Asciidoctor interface.
// *
// * @author lordofthejars
// */
// public static final class Factory {
//
// private Factory() {
// }
//
// /**
// * Creates a new instance of Asciidoctor.
// *
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create() {
// return JRubyAsciidoctor.create();
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets GEM_PATH environment
// * variable to provided gemPath. This method is mostly used in OSGi
// * environments.
// *
// * @param gemPath where gems are located.
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create(String gemPath) {
// return JRubyAsciidoctor.create(gemPath);
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets loadPath to provided paths. This method is mostly used in OSGi
// * environments.
// *
// * @param loadPaths where Ruby libraries are located.
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create(List<String> loadPaths) {
// return JRubyAsciidoctor.create(loadPaths);
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets a specific classloader for the JRuby runtime to use.
// * This method is for use in environments like OSGi.
// * To initialize Asciidoctor in OSGi create the Asciidoctor instance like this:
// *
// * <pre>
// * org.jruby.javasupport.JavaEmbedUtils.initialize(Arrays.asList("uri:classloader:/gems/asciidoctor-1.5.8/lib"));
// * Asciidoctor asciidoctor = Asciidoctor.Factory.create(this.getClass().getClassLoader());
// * </pre>
// *
// * @param classloader
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create(ClassLoader classloader) {
// return JRubyAsciidoctor.create(classloader);
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets a specific classloader and gempath for the JRuby runtime to use.
// * This method is for use in environments like OSGi.
// * To initialize Asciidoctor in OSGi create the Asciidoctor instance like this:
// *
// * <pre>
// * org.jruby.javasupport.JavaEmbedUtils.initialize(Arrays.asList("uri:classloader:/gems/asciidoctor-1.5.8/lib"));
// * Asciidoctor asciidoctor = Asciidoctor.Factory.create(this.getClass().getClassLoader());
// * </pre>
// *
// * @param classloader
// * @param gemPath
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// */
// public static AsciidoctorJRuby create(ClassLoader classloader, String gemPath) {
// return JRubyAsciidoctor.create(classloader, gemPath);
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets loadPath to provided paths.
// * The gem path of the Ruby instance is set to the gemPath parameter.
// *
// * @param loadPaths where Ruby libraries are located.
// * @param gemPath where gems are located.
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create(List<String> loadPaths, String gemPath) {
// return JRubyAsciidoctor.create(loadPaths, gemPath);
// }
//
// }
//
//
// }
|
import org.asciidoctor.jruby.AsciidoctorJRuby;
import org.junit.Test;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
|
package org.asciidoctor;
public class WhenAnAsciidoctorJInstanceIsRequired {
private static final String DOC = "[yell]\nHello World";
@Test
public void shouldUnwrapAsciidoctorInstanceAndRegisterRubyExtension() throws Exception {
|
// Path: asciidoctorj-core/src/main/java/org/asciidoctor/jruby/AsciidoctorJRuby.java
// public interface AsciidoctorJRuby extends Asciidoctor {
//
//
// /**
// * Factory for creating a new instance of Asciidoctor interface.
// *
// * @author lordofthejars
// */
// public static final class Factory {
//
// private Factory() {
// }
//
// /**
// * Creates a new instance of Asciidoctor.
// *
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create() {
// return JRubyAsciidoctor.create();
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets GEM_PATH environment
// * variable to provided gemPath. This method is mostly used in OSGi
// * environments.
// *
// * @param gemPath where gems are located.
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create(String gemPath) {
// return JRubyAsciidoctor.create(gemPath);
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets loadPath to provided paths. This method is mostly used in OSGi
// * environments.
// *
// * @param loadPaths where Ruby libraries are located.
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create(List<String> loadPaths) {
// return JRubyAsciidoctor.create(loadPaths);
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets a specific classloader for the JRuby runtime to use.
// * This method is for use in environments like OSGi.
// * To initialize Asciidoctor in OSGi create the Asciidoctor instance like this:
// *
// * <pre>
// * org.jruby.javasupport.JavaEmbedUtils.initialize(Arrays.asList("uri:classloader:/gems/asciidoctor-1.5.8/lib"));
// * Asciidoctor asciidoctor = Asciidoctor.Factory.create(this.getClass().getClassLoader());
// * </pre>
// *
// * @param classloader
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create(ClassLoader classloader) {
// return JRubyAsciidoctor.create(classloader);
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets a specific classloader and gempath for the JRuby runtime to use.
// * This method is for use in environments like OSGi.
// * To initialize Asciidoctor in OSGi create the Asciidoctor instance like this:
// *
// * <pre>
// * org.jruby.javasupport.JavaEmbedUtils.initialize(Arrays.asList("uri:classloader:/gems/asciidoctor-1.5.8/lib"));
// * Asciidoctor asciidoctor = Asciidoctor.Factory.create(this.getClass().getClassLoader());
// * </pre>
// *
// * @param classloader
// * @param gemPath
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// */
// public static AsciidoctorJRuby create(ClassLoader classloader, String gemPath) {
// return JRubyAsciidoctor.create(classloader, gemPath);
// }
//
// /**
// * Creates a new instance of Asciidoctor and sets loadPath to provided paths.
// * The gem path of the Ruby instance is set to the gemPath parameter.
// *
// * @param loadPaths where Ruby libraries are located.
// * @param gemPath where gems are located.
// * @return Asciidoctor instance which uses JRuby to wraps Asciidoctor
// * Ruby calls.
// */
// public static AsciidoctorJRuby create(List<String> loadPaths, String gemPath) {
// return JRubyAsciidoctor.create(loadPaths, gemPath);
// }
//
// }
//
//
// }
// Path: asciidoctorj-core/src/test/java/org/asciidoctor/WhenAnAsciidoctorJInstanceIsRequired.java
import org.asciidoctor.jruby.AsciidoctorJRuby;
import org.junit.Test;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
package org.asciidoctor;
public class WhenAnAsciidoctorJInstanceIsRequired {
private static final String DOC = "[yell]\nHello World";
@Test
public void shouldUnwrapAsciidoctorInstanceAndRegisterRubyExtension() throws Exception {
|
AsciidoctorJRuby asciidoctorj = Asciidoctor.Factory.create().unwrap(AsciidoctorJRuby.class);
|
asciidoctor/asciidoctorj
|
asciidoctorj-core/src/test/java/org/asciidoctor/extension/CustomFooterPostProcessor.java
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
|
import org.asciidoctor.ast.Document;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import java.util.Map;
|
package org.asciidoctor.extension;
public class CustomFooterPostProcessor extends Postprocessor {
public CustomFooterPostProcessor(Map<String, Object> config) {
super(config);
}
@Override
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
// Path: asciidoctorj-core/src/test/java/org/asciidoctor/extension/CustomFooterPostProcessor.java
import org.asciidoctor.ast.Document;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import java.util.Map;
package org.asciidoctor.extension;
public class CustomFooterPostProcessor extends Postprocessor {
public CustomFooterPostProcessor(Map<String, Object> config) {
super(config);
}
@Override
|
public String process(Document document, String output) {
|
asciidoctor/asciidoctorj
|
asciidoctorj-documentation/src/test/java/org/asciidoctor/integrationguide/extension/LsIncludeProcessor.java
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
|
import org.asciidoctor.ast.Document;
import org.asciidoctor.extension.IncludeProcessor;
import org.asciidoctor.extension.PreprocessorReader;
import java.io.File;
import java.util.Map;
|
package org.asciidoctor.integrationguide.extension;
//tag::include[]
public class LsIncludeProcessor extends IncludeProcessor { // <1>
@Override
public boolean handles(String target) { // <2>
return "ls".equals(target);
}
@Override
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
// Path: asciidoctorj-documentation/src/test/java/org/asciidoctor/integrationguide/extension/LsIncludeProcessor.java
import org.asciidoctor.ast.Document;
import org.asciidoctor.extension.IncludeProcessor;
import org.asciidoctor.extension.PreprocessorReader;
import java.io.File;
import java.util.Map;
package org.asciidoctor.integrationguide.extension;
//tag::include[]
public class LsIncludeProcessor extends IncludeProcessor { // <1>
@Override
public boolean handles(String target) { // <2>
return "ls".equals(target);
}
@Override
|
public void process(Document document, // <3>
|
asciidoctor/asciidoctorj
|
asciidoctorj-api/src/main/java/org/asciidoctor/extension/Postprocessor.java
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
|
import java.util.HashMap;
import java.util.Map;
import org.asciidoctor.ast.Document;
|
package org.asciidoctor.extension;
public abstract class Postprocessor extends BaseProcessor {
public Postprocessor() {
this(new HashMap<>());
}
public Postprocessor(Map<String, Object> config) {
super(config);
}
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/extension/Postprocessor.java
import java.util.HashMap;
import java.util.Map;
import org.asciidoctor.ast.Document;
package org.asciidoctor.extension;
public abstract class Postprocessor extends BaseProcessor {
public Postprocessor() {
this(new HashMap<>());
}
public Postprocessor(Map<String, Object> config) {
super(config);
}
|
public abstract String process(Document document, String output);
|
asciidoctor/asciidoctorj
|
asciidoctorj-core/src/test/java/org/asciidoctor/extension/NextLineEmptyPreprocessor.java
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
|
import org.asciidoctor.ast.Document;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
|
package org.asciidoctor.extension;
public class NextLineEmptyPreprocessor extends Preprocessor {
public NextLineEmptyPreprocessor(Map<String, Object> config) {
super(config);
}
@Override
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
// Path: asciidoctorj-core/src/test/java/org/asciidoctor/extension/NextLineEmptyPreprocessor.java
import org.asciidoctor.ast.Document;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
package org.asciidoctor.extension;
public class NextLineEmptyPreprocessor extends Preprocessor {
public NextLineEmptyPreprocessor(Map<String, Object> config) {
super(config);
}
@Override
|
public void process(Document document,
|
asciidoctor/asciidoctorj
|
asciidoctorj-core/src/test/java/org/asciidoctor/WhenAttributesAreUsedInAsciidoctor.java
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/AttributesBuilder.java
// @Deprecated
// public static AttributesBuilder attributes() {
// return new AttributesBuilder();
// }
|
import com.google.common.io.CharStreams;
import org.asciidoctor.arquillian.api.Unshared;
import org.asciidoctor.util.ClasspathResources;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import static org.asciidoctor.AttributesBuilder.attributes;
import static org.asciidoctor.OptionsBuilder.options;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.collection.IsArrayContaining.hasItemInArray;
import static org.junit.Assert.assertEquals;
import static org.xmlmatchers.xpath.HasXPath.hasXPath;
|
package org.asciidoctor;
@RunWith(Arquillian.class)
public class WhenAttributesAreUsedInAsciidoctor {
@ArquillianResource
private ClasspathResources classpath = new ClasspathResources();
@ArquillianResource
private TemporaryFolder testFolder;
@ArquillianResource(Unshared.class)
private Asciidoctor asciidoctor;
@Test
public void qualified_http_url_inline_with_hide_uri_scheme_set() throws IOException {
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/AttributesBuilder.java
// @Deprecated
// public static AttributesBuilder attributes() {
// return new AttributesBuilder();
// }
// Path: asciidoctorj-core/src/test/java/org/asciidoctor/WhenAttributesAreUsedInAsciidoctor.java
import com.google.common.io.CharStreams;
import org.asciidoctor.arquillian.api.Unshared;
import org.asciidoctor.util.ClasspathResources;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import static org.asciidoctor.AttributesBuilder.attributes;
import static org.asciidoctor.OptionsBuilder.options;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.collection.IsArrayContaining.hasItemInArray;
import static org.junit.Assert.assertEquals;
import static org.xmlmatchers.xpath.HasXPath.hasXPath;
package org.asciidoctor;
@RunWith(Arquillian.class)
public class WhenAttributesAreUsedInAsciidoctor {
@ArquillianResource
private ClasspathResources classpath = new ClasspathResources();
@ArquillianResource
private TemporaryFolder testFolder;
@ArquillianResource(Unshared.class)
private Asciidoctor asciidoctor;
@Test
public void qualified_http_url_inline_with_hide_uri_scheme_set() throws IOException {
|
Attributes attributes = attributes().hiddenUriScheme(true).get();
|
asciidoctor/asciidoctorj
|
asciidoctorj-core/src/main/java/org/asciidoctor/jruby/log/internal/JavaLogger.java
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/log/LogHandler.java
// public interface LogHandler {
//
// /**
// * Process a log record.
// * This method is called during conversion and will abort completely
// * if an exception is thrown from within.
// *
// * @param logRecord
// */
// void log(LogRecord logRecord);
//
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/log/LogRecord.java
// public class LogRecord {
//
// private final Severity severity;
//
// private Cursor cursor;
//
// private final String message;
//
// private String sourceFileName;
//
// private String sourceMethodName;
//
// public LogRecord(Severity severity, String message) {
// this.severity = severity;
// this.message = message;
// }
//
// public LogRecord(Severity severity, Cursor cursor, String message) {
// this.severity = severity;
// this.cursor = cursor;
// this.message = message;
// }
//
// public LogRecord(Severity severity, Cursor cursor, String message, String sourceFileName, String sourceMethodName) {
// this.severity = severity;
// this.cursor = cursor;
// this.message = message;
// this.sourceFileName = sourceFileName;
// this.sourceMethodName = sourceMethodName;
// }
//
// /**
// * @return Severity level of the current record.
// */
// public Severity getSeverity() {
// return severity;
// }
//
// /**
// * @return Information about the location of the event.
// */
// public Cursor getCursor() {
// return cursor;
// }
//
// /**
// * @return Descriptive message about the event.
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * @return The value <code><script></code>. For the source filename use {@link Cursor#getFile()} obtained with the {@link #getCursor()} method.
// */
// public String getSourceFileName() {
// return sourceFileName;
// }
//
// /**
// * @return The Asciidoctor Ruby engine method used to convert the file; <code>convertFile</code> or <code>convert</code> whether you are converting a File or a String.
// */
// public String getSourceMethodName() {
// return sourceMethodName;
// }
// }
|
import org.asciidoctor.log.LogHandler;
import org.asciidoctor.ast.Cursor;
import org.asciidoctor.jruby.ast.impl.CursorImpl;
import org.asciidoctor.log.LogRecord;
import org.asciidoctor.log.Severity;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyHash;
import org.jruby.RubyModule;
import org.jruby.RubyObject;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.Helpers;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.backtrace.BacktraceElement;
import org.jruby.runtime.builtin.IRubyObject;
import java.util.Objects;
import java.util.Optional;
|
@JRubyMethod(name = "initialize", required = 1, optional = 2)
public IRubyObject initialize(final ThreadContext threadContext, final IRubyObject[] args) {
return Helpers.invokeSuper(
threadContext,
this,
getMetaClass(),
"initialize",
args,
Block.NULL_BLOCK);
}
/**
* @param threadContext
* @param args
*/
@JRubyMethod(name = "add", required = 1, optional = 2)
public IRubyObject add(final ThreadContext threadContext, final IRubyObject[] args, Block block) {
final IRubyObject rubyMessage;
if (args.length >= 2 && !args[1].isNil()) {
rubyMessage = args[1];
} else if (block.isGiven()) {
rubyMessage = block.yield(threadContext, getRuntime().getNil());
} else {
rubyMessage = args[2];
}
final Cursor cursor = getSourceLocation(rubyMessage);
final String message = formatMessage(rubyMessage);
final Severity severity = mapRubyLogLevel(args[0]);
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/log/LogHandler.java
// public interface LogHandler {
//
// /**
// * Process a log record.
// * This method is called during conversion and will abort completely
// * if an exception is thrown from within.
// *
// * @param logRecord
// */
// void log(LogRecord logRecord);
//
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/log/LogRecord.java
// public class LogRecord {
//
// private final Severity severity;
//
// private Cursor cursor;
//
// private final String message;
//
// private String sourceFileName;
//
// private String sourceMethodName;
//
// public LogRecord(Severity severity, String message) {
// this.severity = severity;
// this.message = message;
// }
//
// public LogRecord(Severity severity, Cursor cursor, String message) {
// this.severity = severity;
// this.cursor = cursor;
// this.message = message;
// }
//
// public LogRecord(Severity severity, Cursor cursor, String message, String sourceFileName, String sourceMethodName) {
// this.severity = severity;
// this.cursor = cursor;
// this.message = message;
// this.sourceFileName = sourceFileName;
// this.sourceMethodName = sourceMethodName;
// }
//
// /**
// * @return Severity level of the current record.
// */
// public Severity getSeverity() {
// return severity;
// }
//
// /**
// * @return Information about the location of the event.
// */
// public Cursor getCursor() {
// return cursor;
// }
//
// /**
// * @return Descriptive message about the event.
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * @return The value <code><script></code>. For the source filename use {@link Cursor#getFile()} obtained with the {@link #getCursor()} method.
// */
// public String getSourceFileName() {
// return sourceFileName;
// }
//
// /**
// * @return The Asciidoctor Ruby engine method used to convert the file; <code>convertFile</code> or <code>convert</code> whether you are converting a File or a String.
// */
// public String getSourceMethodName() {
// return sourceMethodName;
// }
// }
// Path: asciidoctorj-core/src/main/java/org/asciidoctor/jruby/log/internal/JavaLogger.java
import org.asciidoctor.log.LogHandler;
import org.asciidoctor.ast.Cursor;
import org.asciidoctor.jruby.ast.impl.CursorImpl;
import org.asciidoctor.log.LogRecord;
import org.asciidoctor.log.Severity;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyHash;
import org.jruby.RubyModule;
import org.jruby.RubyObject;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.Helpers;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.backtrace.BacktraceElement;
import org.jruby.runtime.builtin.IRubyObject;
import java.util.Objects;
import java.util.Optional;
@JRubyMethod(name = "initialize", required = 1, optional = 2)
public IRubyObject initialize(final ThreadContext threadContext, final IRubyObject[] args) {
return Helpers.invokeSuper(
threadContext,
this,
getMetaClass(),
"initialize",
args,
Block.NULL_BLOCK);
}
/**
* @param threadContext
* @param args
*/
@JRubyMethod(name = "add", required = 1, optional = 2)
public IRubyObject add(final ThreadContext threadContext, final IRubyObject[] args, Block block) {
final IRubyObject rubyMessage;
if (args.length >= 2 && !args[1].isNil()) {
rubyMessage = args[1];
} else if (block.isGiven()) {
rubyMessage = block.yield(threadContext, getRuntime().getNil());
} else {
rubyMessage = args[2];
}
final Cursor cursor = getSourceLocation(rubyMessage);
final String message = formatMessage(rubyMessage);
final Severity severity = mapRubyLogLevel(args[0]);
|
final LogRecord record = createLogRecord(threadContext, severity, cursor, message);
|
asciidoctor/asciidoctorj
|
asciidoctorj-core/src/test/java/org/asciidoctor/extension/MetaRobotsDocinfoProcessor.java
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
|
import org.asciidoctor.ast.Document;
import java.util.Map;
|
package org.asciidoctor.extension;
public class MetaRobotsDocinfoProcessor extends DocinfoProcessor {
public MetaRobotsDocinfoProcessor(Map<String, Object> config) {
super(config);
}
@Override
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
// Path: asciidoctorj-core/src/test/java/org/asciidoctor/extension/MetaRobotsDocinfoProcessor.java
import org.asciidoctor.ast.Document;
import java.util.Map;
package org.asciidoctor.extension;
public class MetaRobotsDocinfoProcessor extends DocinfoProcessor {
public MetaRobotsDocinfoProcessor(Map<String, Object> config) {
super(config);
}
@Override
|
public String process(Document document) {
|
asciidoctor/asciidoctorj
|
asciidoctorj-api/src/main/java/org/asciidoctor/Asciidoctor.java
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/DocumentHeader.java
// @Deprecated
// public interface DocumentHeader {
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// List<Author> getAuthors();
//
// /**
// * @deprecated Use {@link Document#getStructuredDoctitle()} instead.
// */
// @Deprecated
// Title getDocumentTitle();
//
// /**
// * @deprecated Use {@link Document#getDoctitle()} instead.
// */
// @Deprecated
// String getPageTitle();
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// Author getAuthor();
//
// /**
// * @deprecated Use {@link Document#getRevisionInfo()} instead.
// */
// @Deprecated
// RevisionInfo getRevisionInfo();
//
// /**
// * @deprecated Use {@link Document#getAttributes()} instead.
// */
// @Deprecated
// Map<String, Object> getAttributes();
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/log/LogHandler.java
// public interface LogHandler {
//
// /**
// * Process a log record.
// * This method is called during conversion and will abort completely
// * if an exception is thrown from within.
// *
// * @param logRecord
// */
// void log(LogRecord logRecord);
//
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/syntaxhighlighter/SyntaxHighlighterRegistry.java
// public interface SyntaxHighlighterRegistry {
//
// void register(Class<? extends SyntaxHighlighterAdapter> sourceHighlighter , String... names);
//
// }
|
import org.asciidoctor.ast.Document;
import org.asciidoctor.ast.DocumentHeader;
import org.asciidoctor.converter.JavaConverterRegistry;
import org.asciidoctor.extension.ExtensionGroup;
import org.asciidoctor.extension.JavaExtensionRegistry;
import org.asciidoctor.extension.RubyExtensionRegistry;
import org.asciidoctor.log.LogHandler;
import org.asciidoctor.syntaxhighlighter.SyntaxHighlighterRegistry;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.*;
import java.util.stream.Collectors;
|
* @param options a Map of options to control processing (default: {}).
* @return returns an array of 0 positions if the rendered output is written
* to a file.
*/
@Deprecated
String[] convertFiles(Collection<File> files, OptionsBuilder options);
/**
* Loads the given Ruby gem(s) by name.
*
* @param requiredLibraries
*/
void requireLibrary(String... requiredLibraries);
/**
* Loads the given Ruby gem in requiredLibraries by name.
*
* @param requiredLibraries
*/
void requireLibraries(Collection<String> requiredLibraries);
/**
* Reads only header parameters instead of all document.
*
* @deprecated Use {@link #loadFile(File, Map)} instead.
*
* @param file to read the attributes.
* @return header.
*/
@Deprecated
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/DocumentHeader.java
// @Deprecated
// public interface DocumentHeader {
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// List<Author> getAuthors();
//
// /**
// * @deprecated Use {@link Document#getStructuredDoctitle()} instead.
// */
// @Deprecated
// Title getDocumentTitle();
//
// /**
// * @deprecated Use {@link Document#getDoctitle()} instead.
// */
// @Deprecated
// String getPageTitle();
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// Author getAuthor();
//
// /**
// * @deprecated Use {@link Document#getRevisionInfo()} instead.
// */
// @Deprecated
// RevisionInfo getRevisionInfo();
//
// /**
// * @deprecated Use {@link Document#getAttributes()} instead.
// */
// @Deprecated
// Map<String, Object> getAttributes();
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/log/LogHandler.java
// public interface LogHandler {
//
// /**
// * Process a log record.
// * This method is called during conversion and will abort completely
// * if an exception is thrown from within.
// *
// * @param logRecord
// */
// void log(LogRecord logRecord);
//
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/syntaxhighlighter/SyntaxHighlighterRegistry.java
// public interface SyntaxHighlighterRegistry {
//
// void register(Class<? extends SyntaxHighlighterAdapter> sourceHighlighter , String... names);
//
// }
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/Asciidoctor.java
import org.asciidoctor.ast.Document;
import org.asciidoctor.ast.DocumentHeader;
import org.asciidoctor.converter.JavaConverterRegistry;
import org.asciidoctor.extension.ExtensionGroup;
import org.asciidoctor.extension.JavaExtensionRegistry;
import org.asciidoctor.extension.RubyExtensionRegistry;
import org.asciidoctor.log.LogHandler;
import org.asciidoctor.syntaxhighlighter.SyntaxHighlighterRegistry;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.*;
import java.util.stream.Collectors;
* @param options a Map of options to control processing (default: {}).
* @return returns an array of 0 positions if the rendered output is written
* to a file.
*/
@Deprecated
String[] convertFiles(Collection<File> files, OptionsBuilder options);
/**
* Loads the given Ruby gem(s) by name.
*
* @param requiredLibraries
*/
void requireLibrary(String... requiredLibraries);
/**
* Loads the given Ruby gem in requiredLibraries by name.
*
* @param requiredLibraries
*/
void requireLibraries(Collection<String> requiredLibraries);
/**
* Reads only header parameters instead of all document.
*
* @deprecated Use {@link #loadFile(File, Map)} instead.
*
* @param file to read the attributes.
* @return header.
*/
@Deprecated
|
DocumentHeader readDocumentHeader(File file);
|
asciidoctor/asciidoctorj
|
asciidoctorj-api/src/main/java/org/asciidoctor/Asciidoctor.java
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/DocumentHeader.java
// @Deprecated
// public interface DocumentHeader {
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// List<Author> getAuthors();
//
// /**
// * @deprecated Use {@link Document#getStructuredDoctitle()} instead.
// */
// @Deprecated
// Title getDocumentTitle();
//
// /**
// * @deprecated Use {@link Document#getDoctitle()} instead.
// */
// @Deprecated
// String getPageTitle();
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// Author getAuthor();
//
// /**
// * @deprecated Use {@link Document#getRevisionInfo()} instead.
// */
// @Deprecated
// RevisionInfo getRevisionInfo();
//
// /**
// * @deprecated Use {@link Document#getAttributes()} instead.
// */
// @Deprecated
// Map<String, Object> getAttributes();
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/log/LogHandler.java
// public interface LogHandler {
//
// /**
// * Process a log record.
// * This method is called during conversion and will abort completely
// * if an exception is thrown from within.
// *
// * @param logRecord
// */
// void log(LogRecord logRecord);
//
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/syntaxhighlighter/SyntaxHighlighterRegistry.java
// public interface SyntaxHighlighterRegistry {
//
// void register(Class<? extends SyntaxHighlighterAdapter> sourceHighlighter , String... names);
//
// }
|
import org.asciidoctor.ast.Document;
import org.asciidoctor.ast.DocumentHeader;
import org.asciidoctor.converter.JavaConverterRegistry;
import org.asciidoctor.extension.ExtensionGroup;
import org.asciidoctor.extension.JavaExtensionRegistry;
import org.asciidoctor.extension.RubyExtensionRegistry;
import org.asciidoctor.log.LogHandler;
import org.asciidoctor.syntaxhighlighter.SyntaxHighlighterRegistry;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.*;
import java.util.stream.Collectors;
|
DocumentHeader readDocumentHeader(Reader contentReader);
/**
* Creates an extension registry ready to be used for registering Java extensions.
*
* @return Extension Registry object.
*/
JavaExtensionRegistry javaExtensionRegistry();
/**
* Creates an Ruby extension registry ready to be used for registering Ruby extension.
*
* @return Extension Registry object.
*/
RubyExtensionRegistry rubyExtensionRegistry();
/**
* Creates a registry for registering Java converters.
*
* @return Converter Registry object.
*/
JavaConverterRegistry javaConverterRegistry();
/**
* Creates a registry for registering Java syntax highlighter.
*
* <p>This API is experimental and might change in an incompatible way in a minor version update!</p>
*
* @return Converter Registry object.
*/
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/DocumentHeader.java
// @Deprecated
// public interface DocumentHeader {
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// List<Author> getAuthors();
//
// /**
// * @deprecated Use {@link Document#getStructuredDoctitle()} instead.
// */
// @Deprecated
// Title getDocumentTitle();
//
// /**
// * @deprecated Use {@link Document#getDoctitle()} instead.
// */
// @Deprecated
// String getPageTitle();
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// Author getAuthor();
//
// /**
// * @deprecated Use {@link Document#getRevisionInfo()} instead.
// */
// @Deprecated
// RevisionInfo getRevisionInfo();
//
// /**
// * @deprecated Use {@link Document#getAttributes()} instead.
// */
// @Deprecated
// Map<String, Object> getAttributes();
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/log/LogHandler.java
// public interface LogHandler {
//
// /**
// * Process a log record.
// * This method is called during conversion and will abort completely
// * if an exception is thrown from within.
// *
// * @param logRecord
// */
// void log(LogRecord logRecord);
//
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/syntaxhighlighter/SyntaxHighlighterRegistry.java
// public interface SyntaxHighlighterRegistry {
//
// void register(Class<? extends SyntaxHighlighterAdapter> sourceHighlighter , String... names);
//
// }
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/Asciidoctor.java
import org.asciidoctor.ast.Document;
import org.asciidoctor.ast.DocumentHeader;
import org.asciidoctor.converter.JavaConverterRegistry;
import org.asciidoctor.extension.ExtensionGroup;
import org.asciidoctor.extension.JavaExtensionRegistry;
import org.asciidoctor.extension.RubyExtensionRegistry;
import org.asciidoctor.log.LogHandler;
import org.asciidoctor.syntaxhighlighter.SyntaxHighlighterRegistry;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.*;
import java.util.stream.Collectors;
DocumentHeader readDocumentHeader(Reader contentReader);
/**
* Creates an extension registry ready to be used for registering Java extensions.
*
* @return Extension Registry object.
*/
JavaExtensionRegistry javaExtensionRegistry();
/**
* Creates an Ruby extension registry ready to be used for registering Ruby extension.
*
* @return Extension Registry object.
*/
RubyExtensionRegistry rubyExtensionRegistry();
/**
* Creates a registry for registering Java converters.
*
* @return Converter Registry object.
*/
JavaConverterRegistry javaConverterRegistry();
/**
* Creates a registry for registering Java syntax highlighter.
*
* <p>This API is experimental and might change in an incompatible way in a minor version update!</p>
*
* @return Converter Registry object.
*/
|
SyntaxHighlighterRegistry syntaxHighlighterRegistry();
|
asciidoctor/asciidoctorj
|
asciidoctorj-api/src/main/java/org/asciidoctor/Asciidoctor.java
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/DocumentHeader.java
// @Deprecated
// public interface DocumentHeader {
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// List<Author> getAuthors();
//
// /**
// * @deprecated Use {@link Document#getStructuredDoctitle()} instead.
// */
// @Deprecated
// Title getDocumentTitle();
//
// /**
// * @deprecated Use {@link Document#getDoctitle()} instead.
// */
// @Deprecated
// String getPageTitle();
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// Author getAuthor();
//
// /**
// * @deprecated Use {@link Document#getRevisionInfo()} instead.
// */
// @Deprecated
// RevisionInfo getRevisionInfo();
//
// /**
// * @deprecated Use {@link Document#getAttributes()} instead.
// */
// @Deprecated
// Map<String, Object> getAttributes();
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/log/LogHandler.java
// public interface LogHandler {
//
// /**
// * Process a log record.
// * This method is called during conversion and will abort completely
// * if an exception is thrown from within.
// *
// * @param logRecord
// */
// void log(LogRecord logRecord);
//
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/syntaxhighlighter/SyntaxHighlighterRegistry.java
// public interface SyntaxHighlighterRegistry {
//
// void register(Class<? extends SyntaxHighlighterAdapter> sourceHighlighter , String... names);
//
// }
|
import org.asciidoctor.ast.Document;
import org.asciidoctor.ast.DocumentHeader;
import org.asciidoctor.converter.JavaConverterRegistry;
import org.asciidoctor.extension.ExtensionGroup;
import org.asciidoctor.extension.JavaExtensionRegistry;
import org.asciidoctor.extension.RubyExtensionRegistry;
import org.asciidoctor.log.LogHandler;
import org.asciidoctor.syntaxhighlighter.SyntaxHighlighterRegistry;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.*;
import java.util.stream.Collectors;
|
if (iterator.hasNext()) {
Asciidoctor impl = iterator.next();
List<Asciidoctor> remainingImpls = new ArrayList<>();
while (iterator.hasNext()) {
remainingImpls.add(iterator.next());
}
if (!remainingImpls.isEmpty()) {
remainingImpls.add(0, impl);
String remainingImplNames = remainingImpls
.stream()
.map(asciidoctor -> asciidoctor.getClass().getName())
.collect(Collectors.joining(",", "[", "]"));
throw new RuntimeException(String.format("Found multiple Asciidoctor implementations in the classpath: %s", remainingImplNames));
}
return impl;
} else {
throw new RuntimeException("Unable to find an implementation of Asciidoctor in the classpath (using ServiceLoader)");
}
}
}
/**
* Loads AsciiDoc content and returns the Document object.
* @deprecated Use {@link #load(String, Options)} instead.
*
* @param content to be parsed.
* @param options a Map of options to control processing (default: {}).
* @return Document of given content.
*/
@Deprecated
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/DocumentHeader.java
// @Deprecated
// public interface DocumentHeader {
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// List<Author> getAuthors();
//
// /**
// * @deprecated Use {@link Document#getStructuredDoctitle()} instead.
// */
// @Deprecated
// Title getDocumentTitle();
//
// /**
// * @deprecated Use {@link Document#getDoctitle()} instead.
// */
// @Deprecated
// String getPageTitle();
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// Author getAuthor();
//
// /**
// * @deprecated Use {@link Document#getRevisionInfo()} instead.
// */
// @Deprecated
// RevisionInfo getRevisionInfo();
//
// /**
// * @deprecated Use {@link Document#getAttributes()} instead.
// */
// @Deprecated
// Map<String, Object> getAttributes();
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/log/LogHandler.java
// public interface LogHandler {
//
// /**
// * Process a log record.
// * This method is called during conversion and will abort completely
// * if an exception is thrown from within.
// *
// * @param logRecord
// */
// void log(LogRecord logRecord);
//
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/syntaxhighlighter/SyntaxHighlighterRegistry.java
// public interface SyntaxHighlighterRegistry {
//
// void register(Class<? extends SyntaxHighlighterAdapter> sourceHighlighter , String... names);
//
// }
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/Asciidoctor.java
import org.asciidoctor.ast.Document;
import org.asciidoctor.ast.DocumentHeader;
import org.asciidoctor.converter.JavaConverterRegistry;
import org.asciidoctor.extension.ExtensionGroup;
import org.asciidoctor.extension.JavaExtensionRegistry;
import org.asciidoctor.extension.RubyExtensionRegistry;
import org.asciidoctor.log.LogHandler;
import org.asciidoctor.syntaxhighlighter.SyntaxHighlighterRegistry;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.*;
import java.util.stream.Collectors;
if (iterator.hasNext()) {
Asciidoctor impl = iterator.next();
List<Asciidoctor> remainingImpls = new ArrayList<>();
while (iterator.hasNext()) {
remainingImpls.add(iterator.next());
}
if (!remainingImpls.isEmpty()) {
remainingImpls.add(0, impl);
String remainingImplNames = remainingImpls
.stream()
.map(asciidoctor -> asciidoctor.getClass().getName())
.collect(Collectors.joining(",", "[", "]"));
throw new RuntimeException(String.format("Found multiple Asciidoctor implementations in the classpath: %s", remainingImplNames));
}
return impl;
} else {
throw new RuntimeException("Unable to find an implementation of Asciidoctor in the classpath (using ServiceLoader)");
}
}
}
/**
* Loads AsciiDoc content and returns the Document object.
* @deprecated Use {@link #load(String, Options)} instead.
*
* @param content to be parsed.
* @param options a Map of options to control processing (default: {}).
* @return Document of given content.
*/
@Deprecated
|
Document load(String content, Map<String, Object> options);
|
asciidoctor/asciidoctorj
|
asciidoctorj-api/src/main/java/org/asciidoctor/Asciidoctor.java
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/DocumentHeader.java
// @Deprecated
// public interface DocumentHeader {
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// List<Author> getAuthors();
//
// /**
// * @deprecated Use {@link Document#getStructuredDoctitle()} instead.
// */
// @Deprecated
// Title getDocumentTitle();
//
// /**
// * @deprecated Use {@link Document#getDoctitle()} instead.
// */
// @Deprecated
// String getPageTitle();
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// Author getAuthor();
//
// /**
// * @deprecated Use {@link Document#getRevisionInfo()} instead.
// */
// @Deprecated
// RevisionInfo getRevisionInfo();
//
// /**
// * @deprecated Use {@link Document#getAttributes()} instead.
// */
// @Deprecated
// Map<String, Object> getAttributes();
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/log/LogHandler.java
// public interface LogHandler {
//
// /**
// * Process a log record.
// * This method is called during conversion and will abort completely
// * if an exception is thrown from within.
// *
// * @param logRecord
// */
// void log(LogRecord logRecord);
//
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/syntaxhighlighter/SyntaxHighlighterRegistry.java
// public interface SyntaxHighlighterRegistry {
//
// void register(Class<? extends SyntaxHighlighterAdapter> sourceHighlighter , String... names);
//
// }
|
import org.asciidoctor.ast.Document;
import org.asciidoctor.ast.DocumentHeader;
import org.asciidoctor.converter.JavaConverterRegistry;
import org.asciidoctor.extension.ExtensionGroup;
import org.asciidoctor.extension.JavaExtensionRegistry;
import org.asciidoctor.extension.RubyExtensionRegistry;
import org.asciidoctor.log.LogHandler;
import org.asciidoctor.syntaxhighlighter.SyntaxHighlighterRegistry;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.*;
import java.util.stream.Collectors;
|
* @param options options to control processing (default: empty).
* @return Document of given content.
*/
Document load(String content, Options options);
/**
* Loads AsciiDoc content from file and returns the Document object.
* @deprecated Use {@link #loadFile(File, Options)} instead.
*
* @param file to be parsed.
* @param options a Map of options to control processing (default: {}).
* @return Document of given content.
*/
@Deprecated
Document loadFile(File file, Map<String, Object> options);
/**
* Loads AsciiDoc content from file and returns the Document object.
*
* @param file to be parsed.
* @param options options to control processing (default: empty).
* @return Document of given content.
*/
Document loadFile(File file, Options options);
/**
* Register a {@link LogHandler} to capture Asciidoctor message records.
*
* @param logHandler handler instance.
*/
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/DocumentHeader.java
// @Deprecated
// public interface DocumentHeader {
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// List<Author> getAuthors();
//
// /**
// * @deprecated Use {@link Document#getStructuredDoctitle()} instead.
// */
// @Deprecated
// Title getDocumentTitle();
//
// /**
// * @deprecated Use {@link Document#getDoctitle()} instead.
// */
// @Deprecated
// String getPageTitle();
//
// /**
// * @deprecated Use {@link Document#getAuthors()} instead.
// */
// @Deprecated
// Author getAuthor();
//
// /**
// * @deprecated Use {@link Document#getRevisionInfo()} instead.
// */
// @Deprecated
// RevisionInfo getRevisionInfo();
//
// /**
// * @deprecated Use {@link Document#getAttributes()} instead.
// */
// @Deprecated
// Map<String, Object> getAttributes();
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/log/LogHandler.java
// public interface LogHandler {
//
// /**
// * Process a log record.
// * This method is called during conversion and will abort completely
// * if an exception is thrown from within.
// *
// * @param logRecord
// */
// void log(LogRecord logRecord);
//
// }
//
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/syntaxhighlighter/SyntaxHighlighterRegistry.java
// public interface SyntaxHighlighterRegistry {
//
// void register(Class<? extends SyntaxHighlighterAdapter> sourceHighlighter , String... names);
//
// }
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/Asciidoctor.java
import org.asciidoctor.ast.Document;
import org.asciidoctor.ast.DocumentHeader;
import org.asciidoctor.converter.JavaConverterRegistry;
import org.asciidoctor.extension.ExtensionGroup;
import org.asciidoctor.extension.JavaExtensionRegistry;
import org.asciidoctor.extension.RubyExtensionRegistry;
import org.asciidoctor.log.LogHandler;
import org.asciidoctor.syntaxhighlighter.SyntaxHighlighterRegistry;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.*;
import java.util.stream.Collectors;
* @param options options to control processing (default: empty).
* @return Document of given content.
*/
Document load(String content, Options options);
/**
* Loads AsciiDoc content from file and returns the Document object.
* @deprecated Use {@link #loadFile(File, Options)} instead.
*
* @param file to be parsed.
* @param options a Map of options to control processing (default: {}).
* @return Document of given content.
*/
@Deprecated
Document loadFile(File file, Map<String, Object> options);
/**
* Loads AsciiDoc content from file and returns the Document object.
*
* @param file to be parsed.
* @param options options to control processing (default: empty).
* @return Document of given content.
*/
Document loadFile(File file, Options options);
/**
* Register a {@link LogHandler} to capture Asciidoctor message records.
*
* @param logHandler handler instance.
*/
|
void registerLogHandler(LogHandler logHandler);
|
asciidoctor/asciidoctorj
|
asciidoctorj-api/src/main/java/org/asciidoctor/extension/DocinfoProcessor.java
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
|
import org.asciidoctor.ast.Document;
import java.util.HashMap;
import java.util.Map;
|
package org.asciidoctor.extension;
public abstract class DocinfoProcessor extends BaseProcessor {
public DocinfoProcessor() {
super(new HashMap<>());
}
public DocinfoProcessor(Map<String, Object> config) {
super(config);
}
|
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/ast/Document.java
// public interface Document extends StructuralNode {
//
// /**
// * @return The Title structure for this document.
// * @see Title
// */
// Title getStructuredDoctitle();
//
// /**
// * @return The title as a String.
// * @see Title
// */
// String getDoctitle();
//
// /**
// * @deprecated Please use {@link #getDoctitle()}
// * @return The title as a String.
// * @see Title
// */
// @Deprecated
// String doctitle();
//
// /**
// * Gets the author(s) information as defined in the author line
// * in the document header, or in author & email attributes.
// *
// * @return authors information
// */
// List<Author> getAuthors();
//
// /**
// * @return basebackend attribute value
// */
// boolean isBasebackend(String backend);
//
// /**
// * @deprecated Please use {@link #isBasebackend(String)}
// * @return basebackend attribute value
// */
// @Deprecated
// boolean basebackend(String backend);
//
// /**
// *
// * @return options defined in document.
// */
// Map<Object, Object> getOptions();
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return 1.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @return
// */
// int getAndIncrementCounter(String name);
//
// /**
// * Gets the current counter with the given name and increases its value.
// * At the first invocation the counter will return the given initial value.
// * After the call the value of the counter is set to the returned value plus 1.
// * @param name
// * @param initialValue
// * @return
// */
// int getAndIncrementCounter(String name, int initialValue);
//
// /**
// * @return Whether the sourcemap is enabled.
// */
// boolean isSourcemap();
//
// /**
// * Toggles the sourcemap option.
// *
// * This method must be called before the document is parsed, such as
// * from a Preprocessor extension. Otherwise, it has no effect.
// *
// * @param state The state in which to put the sourcemap (true = on, false = off).
// */
// void setSourcemap(boolean state);
//
//
// /**
// * The catalog contains data collected by asciidoctor that is useful to a converter.
// *
// * Note that the catalog is not part of the asciidoctor public API and is subject to change.
// *
// * @return catalog
// */
// Catalog getCatalog();
//
//
// /**
// * The revision information with: date, number and remark.
// *
// * @return revisionInfo
// */
// RevisionInfo getRevisionInfo();
// }
// Path: asciidoctorj-api/src/main/java/org/asciidoctor/extension/DocinfoProcessor.java
import org.asciidoctor.ast.Document;
import java.util.HashMap;
import java.util.Map;
package org.asciidoctor.extension;
public abstract class DocinfoProcessor extends BaseProcessor {
public DocinfoProcessor() {
super(new HashMap<>());
}
public DocinfoProcessor(Map<String, Object> config) {
super(config);
}
|
public abstract String process(Document document);
|
quanticc/lawena-recording-tool
|
src/main/java/lwrt/CustomPathList.java
|
// Path: src/main/java/lwrt/CustomPath.java
// public enum PathContents {
// DEFAULT, READONLY, HUD, CONFIG, SKYBOX;
//
// @Override
// public String toString() {
// return name().toLowerCase();
// }
// }
//
// Path: src/main/java/util/ListFilesVisitor.java
// public class ListFilesVisitor extends SimpleFileVisitor<Path> {
//
// private List<String> files = new ArrayList<>();
// private Path start;
//
// public ListFilesVisitor(Path start) {
// this.start = start;
// }
//
// public List<String> getFiles() {
// return files;
// }
//
// @Override
// public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// String str =
// start.toAbsolutePath().relativize(file.toAbsolutePath()).toString();
// files.add(str);
// return FileVisitResult.CONTINUE;
// }
//
// @Override
// public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
// return FileVisitResult.TERMINATE;
// }
//
// }
|
import lwrt.CustomPath.PathContents;
import util.ListFilesVisitor;
import javax.swing.table.AbstractTableModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
|
package lwrt;
public class CustomPathList extends AbstractTableModel {
public static final CustomPath particles = new CustomPath(Paths.get("custom", "pldx_particles.vpk"),
|
// Path: src/main/java/lwrt/CustomPath.java
// public enum PathContents {
// DEFAULT, READONLY, HUD, CONFIG, SKYBOX;
//
// @Override
// public String toString() {
// return name().toLowerCase();
// }
// }
//
// Path: src/main/java/util/ListFilesVisitor.java
// public class ListFilesVisitor extends SimpleFileVisitor<Path> {
//
// private List<String> files = new ArrayList<>();
// private Path start;
//
// public ListFilesVisitor(Path start) {
// this.start = start;
// }
//
// public List<String> getFiles() {
// return files;
// }
//
// @Override
// public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// String str =
// start.toAbsolutePath().relativize(file.toAbsolutePath()).toString();
// files.add(str);
// return FileVisitResult.CONTINUE;
// }
//
// @Override
// public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
// return FileVisitResult.TERMINATE;
// }
//
// }
// Path: src/main/java/lwrt/CustomPathList.java
import lwrt.CustomPath.PathContents;
import util.ListFilesVisitor;
import javax.swing.table.AbstractTableModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
package lwrt;
public class CustomPathList extends AbstractTableModel {
public static final CustomPath particles = new CustomPath(Paths.get("custom", "pldx_particles.vpk"),
|
"Enable enhanced particles", EnumSet.of(PathContents.READONLY));
|
quanticc/lawena-recording-tool
|
src/main/java/lwrt/CustomPathList.java
|
// Path: src/main/java/lwrt/CustomPath.java
// public enum PathContents {
// DEFAULT, READONLY, HUD, CONFIG, SKYBOX;
//
// @Override
// public String toString() {
// return name().toLowerCase();
// }
// }
//
// Path: src/main/java/util/ListFilesVisitor.java
// public class ListFilesVisitor extends SimpleFileVisitor<Path> {
//
// private List<String> files = new ArrayList<>();
// private Path start;
//
// public ListFilesVisitor(Path start) {
// this.start = start;
// }
//
// public List<String> getFiles() {
// return files;
// }
//
// @Override
// public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// String str =
// start.toAbsolutePath().relativize(file.toAbsolutePath()).toString();
// files.add(str);
// return FileVisitResult.CONTINUE;
// }
//
// @Override
// public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
// return FileVisitResult.TERMINATE;
// }
//
// }
|
import lwrt.CustomPath.PathContents;
import util.ListFilesVisitor;
import javax.swing.table.AbstractTableModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
|
public Object getValueAt(int row, int column) {
CustomPath cp = list.get(row);
switch (Column.values()[column]) {
case CONTENTS:
return simplify(cp.getContents());
case SELECTED:
return cp.isSelected();
case PATH:
return cp;
default:
return "";
}
}
@Override
public void setValueAt(Object value, int row, int column) {
CustomPath cp = list.get(row);
switch (Column.values()[column]) {
case SELECTED:
cp.setSelected((boolean) value);
fireTableCellUpdated(row, column);
return;
default:
}
}
private List<String> getContentsList(Path path) {
if (path.toString().endsWith(".vpk")) {
return cl.getVpkContents(cfg.getTfPath(), path);
} else if (Files.isDirectory(path)) {
|
// Path: src/main/java/lwrt/CustomPath.java
// public enum PathContents {
// DEFAULT, READONLY, HUD, CONFIG, SKYBOX;
//
// @Override
// public String toString() {
// return name().toLowerCase();
// }
// }
//
// Path: src/main/java/util/ListFilesVisitor.java
// public class ListFilesVisitor extends SimpleFileVisitor<Path> {
//
// private List<String> files = new ArrayList<>();
// private Path start;
//
// public ListFilesVisitor(Path start) {
// this.start = start;
// }
//
// public List<String> getFiles() {
// return files;
// }
//
// @Override
// public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// String str =
// start.toAbsolutePath().relativize(file.toAbsolutePath()).toString();
// files.add(str);
// return FileVisitResult.CONTINUE;
// }
//
// @Override
// public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
// return FileVisitResult.TERMINATE;
// }
//
// }
// Path: src/main/java/lwrt/CustomPathList.java
import lwrt.CustomPath.PathContents;
import util.ListFilesVisitor;
import javax.swing.table.AbstractTableModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
public Object getValueAt(int row, int column) {
CustomPath cp = list.get(row);
switch (Column.values()[column]) {
case CONTENTS:
return simplify(cp.getContents());
case SELECTED:
return cp.isSelected();
case PATH:
return cp;
default:
return "";
}
}
@Override
public void setValueAt(Object value, int row, int column) {
CustomPath cp = list.get(row);
switch (Column.values()[column]) {
case SELECTED:
cp.setSelected((boolean) value);
fireTableCellUpdated(row, column);
return;
default:
}
}
private List<String> getContentsList(Path path) {
if (path.toString().endsWith(".vpk")) {
return cl.getVpkContents(cfg.getTfPath(), path);
} else if (Files.isDirectory(path)) {
|
ListFilesVisitor visitor = new ListFilesVisitor(path);
|
quanticc/lawena-recording-tool
|
src/main/java/ui/DemoEditorView.java
|
// Path: src/main/java/vdm/SkipMode.java
// public enum SkipMode {
//
// SKIP_AHEAD("Standard: Use SkipAhead VDM factory"),
// NO_SKIPS("No tick skipping (older SrcDemo\u00B2 workaround)"),
// DEMO_TIMESCALE("Run demo_timescale before each segment");
//
// private String description;
//
// SkipMode(String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return description;
// }
//
// @Override
// public String toString() {
// return description;
// }
//
// }
//
// Path: src/main/java/vdm/Tick/Exec.java
// public class Exec extends AbstractExec {
// public static final String Text = "Add Exec";
// public static final String Segment = "exec";
// public static final String Template = "exec spec_player";
// public static final String QuitTemplate = "exec quit";
//
// public Exec(File demoFile, String demoname, int start, String template) {
// super(demoFile, demoname, start, start, Segment, template);
// }
//
// public String getCommand(int count) {
// return getTemplate();
// }
// }
//
// Path: src/main/java/vdm/Tick/ExecRecord.java
// public class ExecRecord extends AbstractExec {
// public static final String Segment = "exec_record";
// public static final String Template = "mirv_camimport start \"{{BVH_PATH}}\"";
// public static final String Text = "Add Exec + Record";
//
// public ExecRecord(File demoFile, String demoname, int start, int end, String template) throws NumberFormatException {
// super(demoFile, demoname, start, end, Segment, template);
// if (start >= end) {
// throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
// }
// }
//
// public String getCommand(int count) {
// return "exec " + Util.stripFilenameExtension(getDemoFile().getName()) + "_" + count + "; startrecording";
// }
// }
//
// Path: src/main/java/vdm/Tick/Record.java
// public class Record extends Tick {
// public static final String Segment = "record";
// public static final String Template = "N/A";
// public static final String Text = "Add Record";
//
// public Record(File demoFile, String demoname, int start, int end) throws NumberFormatException {
// super(demoFile, demoname, start, end, Segment, Template);
// if (start >= end) {
// throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
// }
// }
// }
|
import vdm.SkipMode;
import vdm.Tick.Exec;
import vdm.Tick.ExecRecord;
import vdm.Tick.Record;
import javax.swing.*;
import java.awt.*;
|
package ui;
public class DemoEditorView extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private JLabel lblSelectDemoFile;
private JTextField txtDemofile;
private JButton btnBrowse;
private JLabel lblStartTick;
private JTextField txtStarttick;
private JLabel lblEndTick;
private JTextField txtEndtick;
private JButton btnAdd;
private JPanel panelButtonsLeft;
private JButton btnClearTickList;
private JButton btnCreateVdmFiles;
private JButton btnDeleteVdmFiles;
private JScrollPane scrollPane_1;
private JTable tableTicks;
private JPanel panelButtonsRight;
private JButton btnDeleteSelectedTick;
private JScrollPane scrollPane;
private JTextArea txtrDemodetails;
private JCheckBox chckbxSrcDemoFix;
private JButton btnAddExecRecord;
private JButton btnAddExec;
private JLabel lblSkipMode;
|
// Path: src/main/java/vdm/SkipMode.java
// public enum SkipMode {
//
// SKIP_AHEAD("Standard: Use SkipAhead VDM factory"),
// NO_SKIPS("No tick skipping (older SrcDemo\u00B2 workaround)"),
// DEMO_TIMESCALE("Run demo_timescale before each segment");
//
// private String description;
//
// SkipMode(String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return description;
// }
//
// @Override
// public String toString() {
// return description;
// }
//
// }
//
// Path: src/main/java/vdm/Tick/Exec.java
// public class Exec extends AbstractExec {
// public static final String Text = "Add Exec";
// public static final String Segment = "exec";
// public static final String Template = "exec spec_player";
// public static final String QuitTemplate = "exec quit";
//
// public Exec(File demoFile, String demoname, int start, String template) {
// super(demoFile, demoname, start, start, Segment, template);
// }
//
// public String getCommand(int count) {
// return getTemplate();
// }
// }
//
// Path: src/main/java/vdm/Tick/ExecRecord.java
// public class ExecRecord extends AbstractExec {
// public static final String Segment = "exec_record";
// public static final String Template = "mirv_camimport start \"{{BVH_PATH}}\"";
// public static final String Text = "Add Exec + Record";
//
// public ExecRecord(File demoFile, String demoname, int start, int end, String template) throws NumberFormatException {
// super(demoFile, demoname, start, end, Segment, template);
// if (start >= end) {
// throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
// }
// }
//
// public String getCommand(int count) {
// return "exec " + Util.stripFilenameExtension(getDemoFile().getName()) + "_" + count + "; startrecording";
// }
// }
//
// Path: src/main/java/vdm/Tick/Record.java
// public class Record extends Tick {
// public static final String Segment = "record";
// public static final String Template = "N/A";
// public static final String Text = "Add Record";
//
// public Record(File demoFile, String demoname, int start, int end) throws NumberFormatException {
// super(demoFile, demoname, start, end, Segment, Template);
// if (start >= end) {
// throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
// }
// }
// }
// Path: src/main/java/ui/DemoEditorView.java
import vdm.SkipMode;
import vdm.Tick.Exec;
import vdm.Tick.ExecRecord;
import vdm.Tick.Record;
import javax.swing.*;
import java.awt.*;
package ui;
public class DemoEditorView extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private JLabel lblSelectDemoFile;
private JTextField txtDemofile;
private JButton btnBrowse;
private JLabel lblStartTick;
private JTextField txtStarttick;
private JLabel lblEndTick;
private JTextField txtEndtick;
private JButton btnAdd;
private JPanel panelButtonsLeft;
private JButton btnClearTickList;
private JButton btnCreateVdmFiles;
private JButton btnDeleteVdmFiles;
private JScrollPane scrollPane_1;
private JTable tableTicks;
private JPanel panelButtonsRight;
private JButton btnDeleteSelectedTick;
private JScrollPane scrollPane;
private JTextArea txtrDemodetails;
private JCheckBox chckbxSrcDemoFix;
private JButton btnAddExecRecord;
private JButton btnAddExec;
private JLabel lblSkipMode;
|
private JComboBox<SkipMode> cmbSkipMode;
|
quanticc/lawena-recording-tool
|
src/main/java/ui/DemoEditorView.java
|
// Path: src/main/java/vdm/SkipMode.java
// public enum SkipMode {
//
// SKIP_AHEAD("Standard: Use SkipAhead VDM factory"),
// NO_SKIPS("No tick skipping (older SrcDemo\u00B2 workaround)"),
// DEMO_TIMESCALE("Run demo_timescale before each segment");
//
// private String description;
//
// SkipMode(String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return description;
// }
//
// @Override
// public String toString() {
// return description;
// }
//
// }
//
// Path: src/main/java/vdm/Tick/Exec.java
// public class Exec extends AbstractExec {
// public static final String Text = "Add Exec";
// public static final String Segment = "exec";
// public static final String Template = "exec spec_player";
// public static final String QuitTemplate = "exec quit";
//
// public Exec(File demoFile, String demoname, int start, String template) {
// super(demoFile, demoname, start, start, Segment, template);
// }
//
// public String getCommand(int count) {
// return getTemplate();
// }
// }
//
// Path: src/main/java/vdm/Tick/ExecRecord.java
// public class ExecRecord extends AbstractExec {
// public static final String Segment = "exec_record";
// public static final String Template = "mirv_camimport start \"{{BVH_PATH}}\"";
// public static final String Text = "Add Exec + Record";
//
// public ExecRecord(File demoFile, String demoname, int start, int end, String template) throws NumberFormatException {
// super(demoFile, demoname, start, end, Segment, template);
// if (start >= end) {
// throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
// }
// }
//
// public String getCommand(int count) {
// return "exec " + Util.stripFilenameExtension(getDemoFile().getName()) + "_" + count + "; startrecording";
// }
// }
//
// Path: src/main/java/vdm/Tick/Record.java
// public class Record extends Tick {
// public static final String Segment = "record";
// public static final String Template = "N/A";
// public static final String Text = "Add Record";
//
// public Record(File demoFile, String demoname, int start, int end) throws NumberFormatException {
// super(demoFile, demoname, start, end, Segment, Template);
// if (start >= end) {
// throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
// }
// }
// }
|
import vdm.SkipMode;
import vdm.Tick.Exec;
import vdm.Tick.ExecRecord;
import vdm.Tick.Record;
import javax.swing.*;
import java.awt.*;
|
GridBagConstraints gbc_lblEndTick = new GridBagConstraints();
gbc_lblEndTick.anchor = GridBagConstraints.EAST;
gbc_lblEndTick.insets = new Insets(0, 0, 5, 5);
gbc_lblEndTick.gridx = 2;
gbc_lblEndTick.gridy = 2;
add(lblEndTick, gbc_lblEndTick);
txtEndtick = new JTextField();
GridBagConstraints gbc_txtEndtick = new GridBagConstraints();
gbc_txtEndtick.insets = new Insets(0, 0, 5, 5);
gbc_txtEndtick.fill = GridBagConstraints.HORIZONTAL;
gbc_txtEndtick.gridx = 3;
gbc_txtEndtick.gridy = 2;
add(txtEndtick, gbc_txtEndtick);
txtEndtick.setColumns(10);
panelButtonsRight = new JPanel();
FlowLayout flowLayout = (FlowLayout) panelButtonsRight.getLayout();
flowLayout.setAlignment(FlowLayout.RIGHT);
flowLayout.setVgap(0);
flowLayout.setHgap(0);
GridBagConstraints gbc_panelButtonsRight = new GridBagConstraints();
gbc_panelButtonsRight.anchor = GridBagConstraints.WEST;
gbc_panelButtonsRight.gridwidth = 5;
gbc_panelButtonsRight.insets = new Insets(0, 5, 5, 5);
gbc_panelButtonsRight.fill = GridBagConstraints.VERTICAL;
gbc_panelButtonsRight.gridx = 0;
gbc_panelButtonsRight.gridy = 3;
add(panelButtonsRight, gbc_panelButtonsRight);
|
// Path: src/main/java/vdm/SkipMode.java
// public enum SkipMode {
//
// SKIP_AHEAD("Standard: Use SkipAhead VDM factory"),
// NO_SKIPS("No tick skipping (older SrcDemo\u00B2 workaround)"),
// DEMO_TIMESCALE("Run demo_timescale before each segment");
//
// private String description;
//
// SkipMode(String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return description;
// }
//
// @Override
// public String toString() {
// return description;
// }
//
// }
//
// Path: src/main/java/vdm/Tick/Exec.java
// public class Exec extends AbstractExec {
// public static final String Text = "Add Exec";
// public static final String Segment = "exec";
// public static final String Template = "exec spec_player";
// public static final String QuitTemplate = "exec quit";
//
// public Exec(File demoFile, String demoname, int start, String template) {
// super(demoFile, demoname, start, start, Segment, template);
// }
//
// public String getCommand(int count) {
// return getTemplate();
// }
// }
//
// Path: src/main/java/vdm/Tick/ExecRecord.java
// public class ExecRecord extends AbstractExec {
// public static final String Segment = "exec_record";
// public static final String Template = "mirv_camimport start \"{{BVH_PATH}}\"";
// public static final String Text = "Add Exec + Record";
//
// public ExecRecord(File demoFile, String demoname, int start, int end, String template) throws NumberFormatException {
// super(demoFile, demoname, start, end, Segment, template);
// if (start >= end) {
// throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
// }
// }
//
// public String getCommand(int count) {
// return "exec " + Util.stripFilenameExtension(getDemoFile().getName()) + "_" + count + "; startrecording";
// }
// }
//
// Path: src/main/java/vdm/Tick/Record.java
// public class Record extends Tick {
// public static final String Segment = "record";
// public static final String Template = "N/A";
// public static final String Text = "Add Record";
//
// public Record(File demoFile, String demoname, int start, int end) throws NumberFormatException {
// super(demoFile, demoname, start, end, Segment, Template);
// if (start >= end) {
// throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
// }
// }
// }
// Path: src/main/java/ui/DemoEditorView.java
import vdm.SkipMode;
import vdm.Tick.Exec;
import vdm.Tick.ExecRecord;
import vdm.Tick.Record;
import javax.swing.*;
import java.awt.*;
GridBagConstraints gbc_lblEndTick = new GridBagConstraints();
gbc_lblEndTick.anchor = GridBagConstraints.EAST;
gbc_lblEndTick.insets = new Insets(0, 0, 5, 5);
gbc_lblEndTick.gridx = 2;
gbc_lblEndTick.gridy = 2;
add(lblEndTick, gbc_lblEndTick);
txtEndtick = new JTextField();
GridBagConstraints gbc_txtEndtick = new GridBagConstraints();
gbc_txtEndtick.insets = new Insets(0, 0, 5, 5);
gbc_txtEndtick.fill = GridBagConstraints.HORIZONTAL;
gbc_txtEndtick.gridx = 3;
gbc_txtEndtick.gridy = 2;
add(txtEndtick, gbc_txtEndtick);
txtEndtick.setColumns(10);
panelButtonsRight = new JPanel();
FlowLayout flowLayout = (FlowLayout) panelButtonsRight.getLayout();
flowLayout.setAlignment(FlowLayout.RIGHT);
flowLayout.setVgap(0);
flowLayout.setHgap(0);
GridBagConstraints gbc_panelButtonsRight = new GridBagConstraints();
gbc_panelButtonsRight.anchor = GridBagConstraints.WEST;
gbc_panelButtonsRight.gridwidth = 5;
gbc_panelButtonsRight.insets = new Insets(0, 5, 5, 5);
gbc_panelButtonsRight.fill = GridBagConstraints.VERTICAL;
gbc_panelButtonsRight.gridx = 0;
gbc_panelButtonsRight.gridy = 3;
add(panelButtonsRight, gbc_panelButtonsRight);
|
btnAdd = new JButton(Record.Text);
|
quanticc/lawena-recording-tool
|
src/main/java/ui/DemoEditorView.java
|
// Path: src/main/java/vdm/SkipMode.java
// public enum SkipMode {
//
// SKIP_AHEAD("Standard: Use SkipAhead VDM factory"),
// NO_SKIPS("No tick skipping (older SrcDemo\u00B2 workaround)"),
// DEMO_TIMESCALE("Run demo_timescale before each segment");
//
// private String description;
//
// SkipMode(String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return description;
// }
//
// @Override
// public String toString() {
// return description;
// }
//
// }
//
// Path: src/main/java/vdm/Tick/Exec.java
// public class Exec extends AbstractExec {
// public static final String Text = "Add Exec";
// public static final String Segment = "exec";
// public static final String Template = "exec spec_player";
// public static final String QuitTemplate = "exec quit";
//
// public Exec(File demoFile, String demoname, int start, String template) {
// super(demoFile, demoname, start, start, Segment, template);
// }
//
// public String getCommand(int count) {
// return getTemplate();
// }
// }
//
// Path: src/main/java/vdm/Tick/ExecRecord.java
// public class ExecRecord extends AbstractExec {
// public static final String Segment = "exec_record";
// public static final String Template = "mirv_camimport start \"{{BVH_PATH}}\"";
// public static final String Text = "Add Exec + Record";
//
// public ExecRecord(File demoFile, String demoname, int start, int end, String template) throws NumberFormatException {
// super(demoFile, demoname, start, end, Segment, template);
// if (start >= end) {
// throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
// }
// }
//
// public String getCommand(int count) {
// return "exec " + Util.stripFilenameExtension(getDemoFile().getName()) + "_" + count + "; startrecording";
// }
// }
//
// Path: src/main/java/vdm/Tick/Record.java
// public class Record extends Tick {
// public static final String Segment = "record";
// public static final String Template = "N/A";
// public static final String Text = "Add Record";
//
// public Record(File demoFile, String demoname, int start, int end) throws NumberFormatException {
// super(demoFile, demoname, start, end, Segment, Template);
// if (start >= end) {
// throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
// }
// }
// }
|
import vdm.SkipMode;
import vdm.Tick.Exec;
import vdm.Tick.ExecRecord;
import vdm.Tick.Record;
import javax.swing.*;
import java.awt.*;
|
gbc_lblEndTick.gridx = 2;
gbc_lblEndTick.gridy = 2;
add(lblEndTick, gbc_lblEndTick);
txtEndtick = new JTextField();
GridBagConstraints gbc_txtEndtick = new GridBagConstraints();
gbc_txtEndtick.insets = new Insets(0, 0, 5, 5);
gbc_txtEndtick.fill = GridBagConstraints.HORIZONTAL;
gbc_txtEndtick.gridx = 3;
gbc_txtEndtick.gridy = 2;
add(txtEndtick, gbc_txtEndtick);
txtEndtick.setColumns(10);
panelButtonsRight = new JPanel();
FlowLayout flowLayout = (FlowLayout) panelButtonsRight.getLayout();
flowLayout.setAlignment(FlowLayout.RIGHT);
flowLayout.setVgap(0);
flowLayout.setHgap(0);
GridBagConstraints gbc_panelButtonsRight = new GridBagConstraints();
gbc_panelButtonsRight.anchor = GridBagConstraints.WEST;
gbc_panelButtonsRight.gridwidth = 5;
gbc_panelButtonsRight.insets = new Insets(0, 5, 5, 5);
gbc_panelButtonsRight.fill = GridBagConstraints.VERTICAL;
gbc_panelButtonsRight.gridx = 0;
gbc_panelButtonsRight.gridy = 3;
add(panelButtonsRight, gbc_panelButtonsRight);
btnAdd = new JButton(Record.Text);
panelButtonsRight.add(btnAdd);
|
// Path: src/main/java/vdm/SkipMode.java
// public enum SkipMode {
//
// SKIP_AHEAD("Standard: Use SkipAhead VDM factory"),
// NO_SKIPS("No tick skipping (older SrcDemo\u00B2 workaround)"),
// DEMO_TIMESCALE("Run demo_timescale before each segment");
//
// private String description;
//
// SkipMode(String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return description;
// }
//
// @Override
// public String toString() {
// return description;
// }
//
// }
//
// Path: src/main/java/vdm/Tick/Exec.java
// public class Exec extends AbstractExec {
// public static final String Text = "Add Exec";
// public static final String Segment = "exec";
// public static final String Template = "exec spec_player";
// public static final String QuitTemplate = "exec quit";
//
// public Exec(File demoFile, String demoname, int start, String template) {
// super(demoFile, demoname, start, start, Segment, template);
// }
//
// public String getCommand(int count) {
// return getTemplate();
// }
// }
//
// Path: src/main/java/vdm/Tick/ExecRecord.java
// public class ExecRecord extends AbstractExec {
// public static final String Segment = "exec_record";
// public static final String Template = "mirv_camimport start \"{{BVH_PATH}}\"";
// public static final String Text = "Add Exec + Record";
//
// public ExecRecord(File demoFile, String demoname, int start, int end, String template) throws NumberFormatException {
// super(demoFile, demoname, start, end, Segment, template);
// if (start >= end) {
// throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
// }
// }
//
// public String getCommand(int count) {
// return "exec " + Util.stripFilenameExtension(getDemoFile().getName()) + "_" + count + "; startrecording";
// }
// }
//
// Path: src/main/java/vdm/Tick/Record.java
// public class Record extends Tick {
// public static final String Segment = "record";
// public static final String Template = "N/A";
// public static final String Text = "Add Record";
//
// public Record(File demoFile, String demoname, int start, int end) throws NumberFormatException {
// super(demoFile, demoname, start, end, Segment, Template);
// if (start >= end) {
// throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
// }
// }
// }
// Path: src/main/java/ui/DemoEditorView.java
import vdm.SkipMode;
import vdm.Tick.Exec;
import vdm.Tick.ExecRecord;
import vdm.Tick.Record;
import javax.swing.*;
import java.awt.*;
gbc_lblEndTick.gridx = 2;
gbc_lblEndTick.gridy = 2;
add(lblEndTick, gbc_lblEndTick);
txtEndtick = new JTextField();
GridBagConstraints gbc_txtEndtick = new GridBagConstraints();
gbc_txtEndtick.insets = new Insets(0, 0, 5, 5);
gbc_txtEndtick.fill = GridBagConstraints.HORIZONTAL;
gbc_txtEndtick.gridx = 3;
gbc_txtEndtick.gridy = 2;
add(txtEndtick, gbc_txtEndtick);
txtEndtick.setColumns(10);
panelButtonsRight = new JPanel();
FlowLayout flowLayout = (FlowLayout) panelButtonsRight.getLayout();
flowLayout.setAlignment(FlowLayout.RIGHT);
flowLayout.setVgap(0);
flowLayout.setHgap(0);
GridBagConstraints gbc_panelButtonsRight = new GridBagConstraints();
gbc_panelButtonsRight.anchor = GridBagConstraints.WEST;
gbc_panelButtonsRight.gridwidth = 5;
gbc_panelButtonsRight.insets = new Insets(0, 5, 5, 5);
gbc_panelButtonsRight.fill = GridBagConstraints.VERTICAL;
gbc_panelButtonsRight.gridx = 0;
gbc_panelButtonsRight.gridy = 3;
add(panelButtonsRight, gbc_panelButtonsRight);
btnAdd = new JButton(Record.Text);
panelButtonsRight.add(btnAdd);
|
btnAddExecRecord = new JButton(ExecRecord.Text);
|
quanticc/lawena-recording-tool
|
src/main/java/ui/DemoEditorView.java
|
// Path: src/main/java/vdm/SkipMode.java
// public enum SkipMode {
//
// SKIP_AHEAD("Standard: Use SkipAhead VDM factory"),
// NO_SKIPS("No tick skipping (older SrcDemo\u00B2 workaround)"),
// DEMO_TIMESCALE("Run demo_timescale before each segment");
//
// private String description;
//
// SkipMode(String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return description;
// }
//
// @Override
// public String toString() {
// return description;
// }
//
// }
//
// Path: src/main/java/vdm/Tick/Exec.java
// public class Exec extends AbstractExec {
// public static final String Text = "Add Exec";
// public static final String Segment = "exec";
// public static final String Template = "exec spec_player";
// public static final String QuitTemplate = "exec quit";
//
// public Exec(File demoFile, String demoname, int start, String template) {
// super(demoFile, demoname, start, start, Segment, template);
// }
//
// public String getCommand(int count) {
// return getTemplate();
// }
// }
//
// Path: src/main/java/vdm/Tick/ExecRecord.java
// public class ExecRecord extends AbstractExec {
// public static final String Segment = "exec_record";
// public static final String Template = "mirv_camimport start \"{{BVH_PATH}}\"";
// public static final String Text = "Add Exec + Record";
//
// public ExecRecord(File demoFile, String demoname, int start, int end, String template) throws NumberFormatException {
// super(demoFile, demoname, start, end, Segment, template);
// if (start >= end) {
// throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
// }
// }
//
// public String getCommand(int count) {
// return "exec " + Util.stripFilenameExtension(getDemoFile().getName()) + "_" + count + "; startrecording";
// }
// }
//
// Path: src/main/java/vdm/Tick/Record.java
// public class Record extends Tick {
// public static final String Segment = "record";
// public static final String Template = "N/A";
// public static final String Text = "Add Record";
//
// public Record(File demoFile, String demoname, int start, int end) throws NumberFormatException {
// super(demoFile, demoname, start, end, Segment, Template);
// if (start >= end) {
// throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
// }
// }
// }
|
import vdm.SkipMode;
import vdm.Tick.Exec;
import vdm.Tick.ExecRecord;
import vdm.Tick.Record;
import javax.swing.*;
import java.awt.*;
|
txtEndtick = new JTextField();
GridBagConstraints gbc_txtEndtick = new GridBagConstraints();
gbc_txtEndtick.insets = new Insets(0, 0, 5, 5);
gbc_txtEndtick.fill = GridBagConstraints.HORIZONTAL;
gbc_txtEndtick.gridx = 3;
gbc_txtEndtick.gridy = 2;
add(txtEndtick, gbc_txtEndtick);
txtEndtick.setColumns(10);
panelButtonsRight = new JPanel();
FlowLayout flowLayout = (FlowLayout) panelButtonsRight.getLayout();
flowLayout.setAlignment(FlowLayout.RIGHT);
flowLayout.setVgap(0);
flowLayout.setHgap(0);
GridBagConstraints gbc_panelButtonsRight = new GridBagConstraints();
gbc_panelButtonsRight.anchor = GridBagConstraints.WEST;
gbc_panelButtonsRight.gridwidth = 5;
gbc_panelButtonsRight.insets = new Insets(0, 5, 5, 5);
gbc_panelButtonsRight.fill = GridBagConstraints.VERTICAL;
gbc_panelButtonsRight.gridx = 0;
gbc_panelButtonsRight.gridy = 3;
add(panelButtonsRight, gbc_panelButtonsRight);
btnAdd = new JButton(Record.Text);
panelButtonsRight.add(btnAdd);
btnAddExecRecord = new JButton(ExecRecord.Text);
panelButtonsRight.add(btnAddExecRecord);
|
// Path: src/main/java/vdm/SkipMode.java
// public enum SkipMode {
//
// SKIP_AHEAD("Standard: Use SkipAhead VDM factory"),
// NO_SKIPS("No tick skipping (older SrcDemo\u00B2 workaround)"),
// DEMO_TIMESCALE("Run demo_timescale before each segment");
//
// private String description;
//
// SkipMode(String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return description;
// }
//
// @Override
// public String toString() {
// return description;
// }
//
// }
//
// Path: src/main/java/vdm/Tick/Exec.java
// public class Exec extends AbstractExec {
// public static final String Text = "Add Exec";
// public static final String Segment = "exec";
// public static final String Template = "exec spec_player";
// public static final String QuitTemplate = "exec quit";
//
// public Exec(File demoFile, String demoname, int start, String template) {
// super(demoFile, demoname, start, start, Segment, template);
// }
//
// public String getCommand(int count) {
// return getTemplate();
// }
// }
//
// Path: src/main/java/vdm/Tick/ExecRecord.java
// public class ExecRecord extends AbstractExec {
// public static final String Segment = "exec_record";
// public static final String Template = "mirv_camimport start \"{{BVH_PATH}}\"";
// public static final String Text = "Add Exec + Record";
//
// public ExecRecord(File demoFile, String demoname, int start, int end, String template) throws NumberFormatException {
// super(demoFile, demoname, start, end, Segment, template);
// if (start >= end) {
// throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
// }
// }
//
// public String getCommand(int count) {
// return "exec " + Util.stripFilenameExtension(getDemoFile().getName()) + "_" + count + "; startrecording";
// }
// }
//
// Path: src/main/java/vdm/Tick/Record.java
// public class Record extends Tick {
// public static final String Segment = "record";
// public static final String Template = "N/A";
// public static final String Text = "Add Record";
//
// public Record(File demoFile, String demoname, int start, int end) throws NumberFormatException {
// super(demoFile, demoname, start, end, Segment, Template);
// if (start >= end) {
// throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
// }
// }
// }
// Path: src/main/java/ui/DemoEditorView.java
import vdm.SkipMode;
import vdm.Tick.Exec;
import vdm.Tick.ExecRecord;
import vdm.Tick.Record;
import javax.swing.*;
import java.awt.*;
txtEndtick = new JTextField();
GridBagConstraints gbc_txtEndtick = new GridBagConstraints();
gbc_txtEndtick.insets = new Insets(0, 0, 5, 5);
gbc_txtEndtick.fill = GridBagConstraints.HORIZONTAL;
gbc_txtEndtick.gridx = 3;
gbc_txtEndtick.gridy = 2;
add(txtEndtick, gbc_txtEndtick);
txtEndtick.setColumns(10);
panelButtonsRight = new JPanel();
FlowLayout flowLayout = (FlowLayout) panelButtonsRight.getLayout();
flowLayout.setAlignment(FlowLayout.RIGHT);
flowLayout.setVgap(0);
flowLayout.setHgap(0);
GridBagConstraints gbc_panelButtonsRight = new GridBagConstraints();
gbc_panelButtonsRight.anchor = GridBagConstraints.WEST;
gbc_panelButtonsRight.gridwidth = 5;
gbc_panelButtonsRight.insets = new Insets(0, 5, 5, 5);
gbc_panelButtonsRight.fill = GridBagConstraints.VERTICAL;
gbc_panelButtonsRight.gridx = 0;
gbc_panelButtonsRight.gridy = 3;
add(panelButtonsRight, gbc_panelButtonsRight);
btnAdd = new JButton(Record.Text);
panelButtonsRight.add(btnAdd);
btnAddExecRecord = new JButton(ExecRecord.Text);
panelButtonsRight.add(btnAddExecRecord);
|
btnAddExec = new JButton(Exec.Text);
|
quanticc/lawena-recording-tool
|
src/main/java/vdm/TickTableModel.java
|
// Path: src/main/java/vdm/Tick/Tick.java
// abstract public class Tick {
//
// public String getSegment() {
// return segment;
// }
//
// private final String segment;
//
// private final String tickTemplate;
// private final String demoName;
// private final File demoFile;
// private int start;
// private int end;
// boolean valid;
// String reason;
//
// public boolean isValid() {
// return valid;
// }
//
// public String getReason() {
// return reason;
// }
//
// public Tick(File demoFile, String demoName, int start, int end, String segment, String tickTemplate) {
// this.demoFile = demoFile;
// this.demoName = demoName;
// this.start = start;
// this.end = end;
// this.segment = segment;
// this.tickTemplate = tickTemplate;
// this.valid = true;
// }
//
// public File getDemoFile() {
// return demoFile;
// }
//
// public String getDemoName() {
// return demoName;
// }
//
// public int getStart() {
// return start;
// }
//
// public int getEnd() {
// return end;
// }
//
// public String getTemplate() {
// return tickTemplate;
// }
//
// @Override
// public String toString() {
// return demoName + ": " + start + "-" + end;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((demoName == null) ? 0 : demoName.hashCode());
// result = prime * result + end;
// result = prime * result + start;
// result = prime * result + ((segment == null) ? 0 : segment.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// Tick other = (Tick) obj;
// if (demoName == null) {
// if (other.demoName != null) {
// return false;
// }
// } else if (!demoName.equals(other.demoName)) {
// return false;
// }
// if (end != other.end) {
// return false;
// }
// if (start != other.start) {
// return false;
// }
// if (segment == null) {
// if (other.segment != null) {
// return false;
// }
// } else if (!segment.equals(other.segment)) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/vdm/Tick/TickFactory.java
// public class TickFactory {
//
// public static Tick makeTick(File demoFile, String demoname, int start, int end, String segment) {
// return makeTick(demoFile, demoname, start, end, segment, null);
// }
//
// public static Tick makeTick(File demoFile, String demoname, int start, int end, String segment, String template) {
// Tick t;
// try {
// switch (segment) {
// case Record.Segment:
// t = new Record(demoFile, demoname, start, end);
// break;
// case ExecRecord.Segment:
// t = new ExecRecord(demoFile, demoname, start, end, (template == null || template.equals(Record.Template)) ? ExecRecord.Template : template);
// break;
// case Exec.Segment:
// t = new Exec(demoFile, demoname, start, (template == null || template.equals(Record.Template)) ? Exec.Template : template);
// break;
// default:
// t = new InvalidTick(demoFile, demoname, start, end, segment, template, "Unknown Segment Type");
// }
// } catch (NumberFormatException e) {
// t = new InvalidTick(demoFile, demoname, start, end, segment, template, e.getMessage());
// }
// return t;
// }
// }
|
import vdm.Tick.Tick;
import vdm.Tick.TickFactory;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
|
package vdm;
public class TickTableModel extends AbstractTableModel {
private static final Logger log = Logger.getLogger("lawena");
private static final long serialVersionUID = 1L;
|
// Path: src/main/java/vdm/Tick/Tick.java
// abstract public class Tick {
//
// public String getSegment() {
// return segment;
// }
//
// private final String segment;
//
// private final String tickTemplate;
// private final String demoName;
// private final File demoFile;
// private int start;
// private int end;
// boolean valid;
// String reason;
//
// public boolean isValid() {
// return valid;
// }
//
// public String getReason() {
// return reason;
// }
//
// public Tick(File demoFile, String demoName, int start, int end, String segment, String tickTemplate) {
// this.demoFile = demoFile;
// this.demoName = demoName;
// this.start = start;
// this.end = end;
// this.segment = segment;
// this.tickTemplate = tickTemplate;
// this.valid = true;
// }
//
// public File getDemoFile() {
// return demoFile;
// }
//
// public String getDemoName() {
// return demoName;
// }
//
// public int getStart() {
// return start;
// }
//
// public int getEnd() {
// return end;
// }
//
// public String getTemplate() {
// return tickTemplate;
// }
//
// @Override
// public String toString() {
// return demoName + ": " + start + "-" + end;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((demoName == null) ? 0 : demoName.hashCode());
// result = prime * result + end;
// result = prime * result + start;
// result = prime * result + ((segment == null) ? 0 : segment.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// Tick other = (Tick) obj;
// if (demoName == null) {
// if (other.demoName != null) {
// return false;
// }
// } else if (!demoName.equals(other.demoName)) {
// return false;
// }
// if (end != other.end) {
// return false;
// }
// if (start != other.start) {
// return false;
// }
// if (segment == null) {
// if (other.segment != null) {
// return false;
// }
// } else if (!segment.equals(other.segment)) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/vdm/Tick/TickFactory.java
// public class TickFactory {
//
// public static Tick makeTick(File demoFile, String demoname, int start, int end, String segment) {
// return makeTick(demoFile, demoname, start, end, segment, null);
// }
//
// public static Tick makeTick(File demoFile, String demoname, int start, int end, String segment, String template) {
// Tick t;
// try {
// switch (segment) {
// case Record.Segment:
// t = new Record(demoFile, demoname, start, end);
// break;
// case ExecRecord.Segment:
// t = new ExecRecord(demoFile, demoname, start, end, (template == null || template.equals(Record.Template)) ? ExecRecord.Template : template);
// break;
// case Exec.Segment:
// t = new Exec(demoFile, demoname, start, (template == null || template.equals(Record.Template)) ? Exec.Template : template);
// break;
// default:
// t = new InvalidTick(demoFile, demoname, start, end, segment, template, "Unknown Segment Type");
// }
// } catch (NumberFormatException e) {
// t = new InvalidTick(demoFile, demoname, start, end, segment, template, e.getMessage());
// }
// return t;
// }
// }
// Path: src/main/java/vdm/TickTableModel.java
import vdm.Tick.Tick;
import vdm.Tick.TickFactory;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
package vdm;
public class TickTableModel extends AbstractTableModel {
private static final Logger log = Logger.getLogger("lawena");
private static final long serialVersionUID = 1L;
|
private List<Tick> list = new ArrayList<>();
|
quanticc/lawena-recording-tool
|
src/main/java/vdm/TickTableModel.java
|
// Path: src/main/java/vdm/Tick/Tick.java
// abstract public class Tick {
//
// public String getSegment() {
// return segment;
// }
//
// private final String segment;
//
// private final String tickTemplate;
// private final String demoName;
// private final File demoFile;
// private int start;
// private int end;
// boolean valid;
// String reason;
//
// public boolean isValid() {
// return valid;
// }
//
// public String getReason() {
// return reason;
// }
//
// public Tick(File demoFile, String demoName, int start, int end, String segment, String tickTemplate) {
// this.demoFile = demoFile;
// this.demoName = demoName;
// this.start = start;
// this.end = end;
// this.segment = segment;
// this.tickTemplate = tickTemplate;
// this.valid = true;
// }
//
// public File getDemoFile() {
// return demoFile;
// }
//
// public String getDemoName() {
// return demoName;
// }
//
// public int getStart() {
// return start;
// }
//
// public int getEnd() {
// return end;
// }
//
// public String getTemplate() {
// return tickTemplate;
// }
//
// @Override
// public String toString() {
// return demoName + ": " + start + "-" + end;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((demoName == null) ? 0 : demoName.hashCode());
// result = prime * result + end;
// result = prime * result + start;
// result = prime * result + ((segment == null) ? 0 : segment.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// Tick other = (Tick) obj;
// if (demoName == null) {
// if (other.demoName != null) {
// return false;
// }
// } else if (!demoName.equals(other.demoName)) {
// return false;
// }
// if (end != other.end) {
// return false;
// }
// if (start != other.start) {
// return false;
// }
// if (segment == null) {
// if (other.segment != null) {
// return false;
// }
// } else if (!segment.equals(other.segment)) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/vdm/Tick/TickFactory.java
// public class TickFactory {
//
// public static Tick makeTick(File demoFile, String demoname, int start, int end, String segment) {
// return makeTick(demoFile, demoname, start, end, segment, null);
// }
//
// public static Tick makeTick(File demoFile, String demoname, int start, int end, String segment, String template) {
// Tick t;
// try {
// switch (segment) {
// case Record.Segment:
// t = new Record(demoFile, demoname, start, end);
// break;
// case ExecRecord.Segment:
// t = new ExecRecord(demoFile, demoname, start, end, (template == null || template.equals(Record.Template)) ? ExecRecord.Template : template);
// break;
// case Exec.Segment:
// t = new Exec(demoFile, demoname, start, (template == null || template.equals(Record.Template)) ? Exec.Template : template);
// break;
// default:
// t = new InvalidTick(demoFile, demoname, start, end, segment, template, "Unknown Segment Type");
// }
// } catch (NumberFormatException e) {
// t = new InvalidTick(demoFile, demoname, start, end, segment, template, e.getMessage());
// }
// return t;
// }
// }
|
import vdm.Tick.Tick;
import vdm.Tick.TickFactory;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
|
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Tick tick = list.get(rowIndex);
Column c = Column.values()[columnIndex];
switch (c) {
case DEMO:
return tick.getDemoName();
case START:
return tick.getStart();
case END:
return tick.getEnd();
case TYPE:
return tick.getSegment();
case TEMPLATE:
return tick.getTemplate();
default:
return null;
}
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
Tick tick = list.get(rowIndex);
Column c = Column.values()[columnIndex];
switch (c) {
case START:
try {
list.set(rowIndex,
|
// Path: src/main/java/vdm/Tick/Tick.java
// abstract public class Tick {
//
// public String getSegment() {
// return segment;
// }
//
// private final String segment;
//
// private final String tickTemplate;
// private final String demoName;
// private final File demoFile;
// private int start;
// private int end;
// boolean valid;
// String reason;
//
// public boolean isValid() {
// return valid;
// }
//
// public String getReason() {
// return reason;
// }
//
// public Tick(File demoFile, String demoName, int start, int end, String segment, String tickTemplate) {
// this.demoFile = demoFile;
// this.demoName = demoName;
// this.start = start;
// this.end = end;
// this.segment = segment;
// this.tickTemplate = tickTemplate;
// this.valid = true;
// }
//
// public File getDemoFile() {
// return demoFile;
// }
//
// public String getDemoName() {
// return demoName;
// }
//
// public int getStart() {
// return start;
// }
//
// public int getEnd() {
// return end;
// }
//
// public String getTemplate() {
// return tickTemplate;
// }
//
// @Override
// public String toString() {
// return demoName + ": " + start + "-" + end;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((demoName == null) ? 0 : demoName.hashCode());
// result = prime * result + end;
// result = prime * result + start;
// result = prime * result + ((segment == null) ? 0 : segment.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// Tick other = (Tick) obj;
// if (demoName == null) {
// if (other.demoName != null) {
// return false;
// }
// } else if (!demoName.equals(other.demoName)) {
// return false;
// }
// if (end != other.end) {
// return false;
// }
// if (start != other.start) {
// return false;
// }
// if (segment == null) {
// if (other.segment != null) {
// return false;
// }
// } else if (!segment.equals(other.segment)) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/vdm/Tick/TickFactory.java
// public class TickFactory {
//
// public static Tick makeTick(File demoFile, String demoname, int start, int end, String segment) {
// return makeTick(demoFile, demoname, start, end, segment, null);
// }
//
// public static Tick makeTick(File demoFile, String demoname, int start, int end, String segment, String template) {
// Tick t;
// try {
// switch (segment) {
// case Record.Segment:
// t = new Record(demoFile, demoname, start, end);
// break;
// case ExecRecord.Segment:
// t = new ExecRecord(demoFile, demoname, start, end, (template == null || template.equals(Record.Template)) ? ExecRecord.Template : template);
// break;
// case Exec.Segment:
// t = new Exec(demoFile, demoname, start, (template == null || template.equals(Record.Template)) ? Exec.Template : template);
// break;
// default:
// t = new InvalidTick(demoFile, demoname, start, end, segment, template, "Unknown Segment Type");
// }
// } catch (NumberFormatException e) {
// t = new InvalidTick(demoFile, demoname, start, end, segment, template, e.getMessage());
// }
// return t;
// }
// }
// Path: src/main/java/vdm/TickTableModel.java
import vdm.Tick.Tick;
import vdm.Tick.TickFactory;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Tick tick = list.get(rowIndex);
Column c = Column.values()[columnIndex];
switch (c) {
case DEMO:
return tick.getDemoName();
case START:
return tick.getStart();
case END:
return tick.getEnd();
case TYPE:
return tick.getSegment();
case TEMPLATE:
return tick.getTemplate();
default:
return null;
}
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
Tick tick = list.get(rowIndex);
Column c = Column.values()[columnIndex];
switch (c) {
case START:
try {
list.set(rowIndex,
|
TickFactory.makeTick(
|
quanticc/lawena-recording-tool
|
src/main/java/ui/TooltipRenderer.java
|
// Path: src/main/java/lwrt/CustomPath.java
// public class CustomPath {
//
// private Path path;
// private String name;
// private boolean selected = false;
// private EnumSet<PathContents> contents;
//
// public CustomPath(Path path) {
// this(path, path.getFileName().toString());
// }
//
// public CustomPath(Path path, String name) {
// this(path, name, EnumSet.noneOf(PathContents.class));
// }
//
// public CustomPath(Path path, String name, EnumSet<PathContents> contents) {
// this.path = path;
// this.name = name;
// this.contents = contents;
// if (contents.contains(PathContents.READONLY)) {
// selected = true;
// }
// }
//
// public Path getPath() {
// return path;
// }
//
// public String getName() {
// return name;
// }
//
// public boolean isSelected() {
// return selected;
// }
//
// public void setSelected(boolean selected) {
// this.selected = selected;
// }
//
// public EnumSet<PathContents> getContents() {
// return contents;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// public enum PathContents {
// DEFAULT, READONLY, HUD, CONFIG, SKYBOX;
//
// @Override
// public String toString() {
// return name().toLowerCase();
// }
// }
//
// }
|
import lwrt.CustomPath;
import lwrt.SettingsManager;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.nio.file.Path;
|
package ui;
public class TooltipRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
private SettingsManager cfg;
public TooltipRenderer(SettingsManager cfg) {
this.cfg = cfg;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
|
// Path: src/main/java/lwrt/CustomPath.java
// public class CustomPath {
//
// private Path path;
// private String name;
// private boolean selected = false;
// private EnumSet<PathContents> contents;
//
// public CustomPath(Path path) {
// this(path, path.getFileName().toString());
// }
//
// public CustomPath(Path path, String name) {
// this(path, name, EnumSet.noneOf(PathContents.class));
// }
//
// public CustomPath(Path path, String name, EnumSet<PathContents> contents) {
// this.path = path;
// this.name = name;
// this.contents = contents;
// if (contents.contains(PathContents.READONLY)) {
// selected = true;
// }
// }
//
// public Path getPath() {
// return path;
// }
//
// public String getName() {
// return name;
// }
//
// public boolean isSelected() {
// return selected;
// }
//
// public void setSelected(boolean selected) {
// this.selected = selected;
// }
//
// public EnumSet<PathContents> getContents() {
// return contents;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// public enum PathContents {
// DEFAULT, READONLY, HUD, CONFIG, SKYBOX;
//
// @Override
// public String toString() {
// return name().toLowerCase();
// }
// }
//
// }
// Path: src/main/java/ui/TooltipRenderer.java
import lwrt.CustomPath;
import lwrt.SettingsManager;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.nio.file.Path;
package ui;
public class TooltipRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
private SettingsManager cfg;
public TooltipRenderer(SettingsManager cfg) {
this.cfg = cfg;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
|
CustomPath cp = (CustomPath) value;
|
quanticc/lawena-recording-tool
|
src/main/java/vdm/Tick/ExecRecord.java
|
// Path: src/main/java/util/Util.java
// public class Util {
//
// private static final Logger log = Logger.getLogger("lawena");
//
// private Util() {
// }
//
// public static int compareCreationTime(File newgd, File curgd) {
// try {
// Path newp = newgd.toPath();
// BasicFileAttributes newAttributes = Files.readAttributes(newp, BasicFileAttributes.class);
// FileTime newCreationTime = newAttributes.creationTime();
// Path curp = curgd.toPath();
// BasicFileAttributes curAttributes = Files.readAttributes(curp, BasicFileAttributes.class);
// FileTime curCreationTime = curAttributes.creationTime();
// log.fine("Comparing creationTime: new=" + newCreationTime + " cur=" + curCreationTime);
// return newCreationTime.compareTo(curCreationTime);
// } catch (IOException e) {
// log.warning("Could not retrieve file creation time: " + e.toString());
// }
// return 1;
// }
//
// public static void copy(InputStream in, OutputStream out) throws IOException {
// try {
// byte[] buffer = new byte[4096];
// for (int read; (read = in.read(buffer)) > 0; ) {
// out.write(buffer, 0, read);
// }
// } finally {
// if (in != null) {
// try {
// in.close();
// } catch (IOException ignored) {
// }
// }
// if (out != null) {
// try {
// out.close();
// } catch (IOException ignored) {
// }
// }
// }
// }
//
// public static String now(String format) {
// SimpleDateFormat sdf = new SimpleDateFormat(format);
// return sdf.format(Calendar.getInstance().getTime());
// }
//
// public static long sizeOfPath(Path startPath) throws IOException {
// final AtomicLong size = new AtomicLong(0);
// Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
// @Override
// public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
// size.addAndGet(attrs.size());
// return FileVisitResult.CONTINUE;
// }
//
// @Override
// public FileVisitResult visitFileFailed(Path file, IOException exc) {
// return FileVisitResult.CONTINUE;
// }
// });
// return size.get();
// }
//
// public static String humanReadableByteCount(long bytes, boolean si) {
// int unit = si ? 1000 : 1024;
// if (bytes < unit) {
// return bytes + " B";
// }
// int exp = (int) (Math.log(bytes) / Math.log(unit));
// String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
// return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
// }
//
// public static int startProcess(List<String> command) {
// try {
// ProcessBuilder builder = new ProcessBuilder(command);
// Process p = builder.start();
// return p.waitFor();
// } catch (InterruptedException | IOException e) {
// log.warning("Process could not be completed: " + e.toString());
// }
// return 1;
// }
//
// /**
// * Strip the filename extension from the given Java resource path, e.g. "mypath/myfile.txt" -> "mypath/myfile".
// *
// * @param path the file path (may be {@code null})
// * @return the path with stripped filename extension, or {@code null} if none
// */
// public static String stripFilenameExtension(String path) {
// if (path == null) {
// return null;
// }
// int extIndex = path.lastIndexOf('.');
// if (extIndex == -1) {
// return path;
// }
// int folderIndex = path.lastIndexOf(File.separatorChar);
// if (folderIndex > extIndex) {
// return path;
// }
// return path.substring(0, extIndex);
// }
//
// }
|
import util.Util;
import java.io.File;
|
package vdm.Tick;
public class ExecRecord extends AbstractExec {
public static final String Segment = "exec_record";
public static final String Template = "mirv_camimport start \"{{BVH_PATH}}\"";
public static final String Text = "Add Exec + Record";
public ExecRecord(File demoFile, String demoname, int start, int end, String template) throws NumberFormatException {
super(demoFile, demoname, start, end, Segment, template);
if (start >= end) {
throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
}
}
public String getCommand(int count) {
|
// Path: src/main/java/util/Util.java
// public class Util {
//
// private static final Logger log = Logger.getLogger("lawena");
//
// private Util() {
// }
//
// public static int compareCreationTime(File newgd, File curgd) {
// try {
// Path newp = newgd.toPath();
// BasicFileAttributes newAttributes = Files.readAttributes(newp, BasicFileAttributes.class);
// FileTime newCreationTime = newAttributes.creationTime();
// Path curp = curgd.toPath();
// BasicFileAttributes curAttributes = Files.readAttributes(curp, BasicFileAttributes.class);
// FileTime curCreationTime = curAttributes.creationTime();
// log.fine("Comparing creationTime: new=" + newCreationTime + " cur=" + curCreationTime);
// return newCreationTime.compareTo(curCreationTime);
// } catch (IOException e) {
// log.warning("Could not retrieve file creation time: " + e.toString());
// }
// return 1;
// }
//
// public static void copy(InputStream in, OutputStream out) throws IOException {
// try {
// byte[] buffer = new byte[4096];
// for (int read; (read = in.read(buffer)) > 0; ) {
// out.write(buffer, 0, read);
// }
// } finally {
// if (in != null) {
// try {
// in.close();
// } catch (IOException ignored) {
// }
// }
// if (out != null) {
// try {
// out.close();
// } catch (IOException ignored) {
// }
// }
// }
// }
//
// public static String now(String format) {
// SimpleDateFormat sdf = new SimpleDateFormat(format);
// return sdf.format(Calendar.getInstance().getTime());
// }
//
// public static long sizeOfPath(Path startPath) throws IOException {
// final AtomicLong size = new AtomicLong(0);
// Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
// @Override
// public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
// size.addAndGet(attrs.size());
// return FileVisitResult.CONTINUE;
// }
//
// @Override
// public FileVisitResult visitFileFailed(Path file, IOException exc) {
// return FileVisitResult.CONTINUE;
// }
// });
// return size.get();
// }
//
// public static String humanReadableByteCount(long bytes, boolean si) {
// int unit = si ? 1000 : 1024;
// if (bytes < unit) {
// return bytes + " B";
// }
// int exp = (int) (Math.log(bytes) / Math.log(unit));
// String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
// return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
// }
//
// public static int startProcess(List<String> command) {
// try {
// ProcessBuilder builder = new ProcessBuilder(command);
// Process p = builder.start();
// return p.waitFor();
// } catch (InterruptedException | IOException e) {
// log.warning("Process could not be completed: " + e.toString());
// }
// return 1;
// }
//
// /**
// * Strip the filename extension from the given Java resource path, e.g. "mypath/myfile.txt" -> "mypath/myfile".
// *
// * @param path the file path (may be {@code null})
// * @return the path with stripped filename extension, or {@code null} if none
// */
// public static String stripFilenameExtension(String path) {
// if (path == null) {
// return null;
// }
// int extIndex = path.lastIndexOf('.');
// if (extIndex == -1) {
// return path;
// }
// int folderIndex = path.lastIndexOf(File.separatorChar);
// if (folderIndex > extIndex) {
// return path;
// }
// return path.substring(0, extIndex);
// }
//
// }
// Path: src/main/java/vdm/Tick/ExecRecord.java
import util.Util;
import java.io.File;
package vdm.Tick;
public class ExecRecord extends AbstractExec {
public static final String Segment = "exec_record";
public static final String Template = "mirv_camimport start \"{{BVH_PATH}}\"";
public static final String Text = "Add Exec + Record";
public ExecRecord(File demoFile, String demoname, int start, int end, String template) throws NumberFormatException {
super(demoFile, demoname, start, end, Segment, template);
if (start >= end) {
throw new NumberFormatException(String.format("end tick (%d) must be greater than start tick (%d)", end, start));
}
}
public String getCommand(int count) {
|
return "exec " + Util.stripFilenameExtension(getDemoFile().getName()) + "_" + count + "; startrecording";
|
querydsl/codegen
|
src/main/java/com/mysema/codegen/JavaWriter.java
|
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String ASSIGN = " = ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String COMMA = ", ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String DOT = ".";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String QUOTE = "\"";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SEMICOLON = ";";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SPACE = " ";
//
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
|
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
|
/*
* Copyright 2010, Mysema Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mysema.codegen;
/**
* JavaWriter is the default implementation of the CodeWriter interface
*
* @author tiwe
*
*/
public final class JavaWriter extends AbstractCodeWriter<JavaWriter> {
private static final String EXTENDS = " extends ";
private static final String IMPLEMENTS = " implements ";
private static final String IMPORT = "import ";
private static final String IMPORT_STATIC = "import static ";
private static final String PACKAGE = "package ";
private static final String PRIVATE = "private ";
private static final String PRIVATE_FINAL = "private final ";
private static final String PRIVATE_STATIC_FINAL = "private static final ";
private static final String PROTECTED = "protected ";
private static final String PROTECTED_FINAL = "protected final ";
private static final String PUBLIC = "public ";
private static final String PUBLIC_CLASS = "public class ";
private static final String PUBLIC_FINAL = "public final ";
private static final String PUBLIC_INTERFACE = "public interface ";
private static final String PUBLIC_STATIC = "public static ";
private static final String PUBLIC_STATIC_FINAL = "public static final ";
private final Set<String> classes = new HashSet<String>();
private final Set<String> packages = new HashSet<String>();
|
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String ASSIGN = " = ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String COMMA = ", ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String DOT = ".";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String QUOTE = "\"";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SEMICOLON = ";";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SPACE = " ";
//
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
// Path: src/main/java/com/mysema/codegen/JavaWriter.java
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
/*
* Copyright 2010, Mysema Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mysema.codegen;
/**
* JavaWriter is the default implementation of the CodeWriter interface
*
* @author tiwe
*
*/
public final class JavaWriter extends AbstractCodeWriter<JavaWriter> {
private static final String EXTENDS = " extends ";
private static final String IMPLEMENTS = " implements ";
private static final String IMPORT = "import ";
private static final String IMPORT_STATIC = "import static ";
private static final String PACKAGE = "package ";
private static final String PRIVATE = "private ";
private static final String PRIVATE_FINAL = "private final ";
private static final String PRIVATE_STATIC_FINAL = "private static final ";
private static final String PROTECTED = "protected ";
private static final String PROTECTED_FINAL = "protected final ";
private static final String PUBLIC = "public ";
private static final String PUBLIC_CLASS = "public class ";
private static final String PUBLIC_FINAL = "public final ";
private static final String PUBLIC_INTERFACE = "public interface ";
private static final String PUBLIC_STATIC = "public static ";
private static final String PUBLIC_STATIC_FINAL = "public static final ";
private final Set<String> classes = new HashSet<String>();
private final Set<String> packages = new HashSet<String>();
|
private final Stack<Type> types = new Stack<Type>();
|
querydsl/codegen
|
src/main/java/com/mysema/codegen/JavaWriter.java
|
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String ASSIGN = " = ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String COMMA = ", ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String DOT = ".";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String QUOTE = "\"";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SEMICOLON = ";";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SPACE = " ";
//
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
|
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
|
}
@Override
public JavaWriter annotation(Annotation annotation) throws IOException {
beginLine().append("@").appendType(annotation.annotationType());
Method[] methods = annotation.annotationType().getDeclaredMethods();
if (methods.length == 1 && methods[0].getName().equals("value")) {
try {
Object value = methods[0].invoke(annotation);
append("(");
annotationConstant(value);
append(")");
} catch (IllegalArgumentException e) {
throw new CodegenException(e);
} catch (IllegalAccessException e) {
throw new CodegenException(e);
} catch (InvocationTargetException e) {
throw new CodegenException(e);
}
} else {
boolean first = true;
for (Method method : methods) {
try {
Object value = method.invoke(annotation);
if (value == null || value.equals(method.getDefaultValue())) {
continue;
} else if (value.getClass().isArray()
&& Arrays.equals((Object[]) value, (Object[]) method.getDefaultValue())) {
continue;
} else if (!first) {
|
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String ASSIGN = " = ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String COMMA = ", ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String DOT = ".";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String QUOTE = "\"";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SEMICOLON = ";";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SPACE = " ";
//
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
// Path: src/main/java/com/mysema/codegen/JavaWriter.java
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
}
@Override
public JavaWriter annotation(Annotation annotation) throws IOException {
beginLine().append("@").appendType(annotation.annotationType());
Method[] methods = annotation.annotationType().getDeclaredMethods();
if (methods.length == 1 && methods[0].getName().equals("value")) {
try {
Object value = methods[0].invoke(annotation);
append("(");
annotationConstant(value);
append(")");
} catch (IllegalArgumentException e) {
throw new CodegenException(e);
} catch (IllegalAccessException e) {
throw new CodegenException(e);
} catch (InvocationTargetException e) {
throw new CodegenException(e);
}
} else {
boolean first = true;
for (Method method : methods) {
try {
Object value = method.invoke(annotation);
if (value == null || value.equals(method.getDefaultValue())) {
continue;
} else if (value.getClass().isArray()
&& Arrays.equals((Object[]) value, (Object[]) method.getDefaultValue())) {
continue;
} else if (!first) {
|
append(COMMA);
|
querydsl/codegen
|
src/main/java/com/mysema/codegen/JavaWriter.java
|
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String ASSIGN = " = ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String COMMA = ", ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String DOT = ".";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String QUOTE = "\"";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SEMICOLON = ";";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SPACE = " ";
//
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
|
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
|
}
@Override
public JavaWriter annotation(Class<? extends Annotation> annotation) throws IOException {
return beginLine().append("@").appendType(annotation).nl();
}
@SuppressWarnings("unchecked")
private void annotationConstant(Object value) throws IOException {
if (value.getClass().isArray()) {
append("{");
boolean first = true;
for (Object o : (Object[]) value) {
if (!first) {
append(", ");
}
annotationConstant(o);
first = false;
}
append("}");
} else if (value instanceof Class) {
appendType((Class) value).append(".class");
} else if (value instanceof Number || value instanceof Boolean) {
append(value.toString());
} else if (value instanceof Enum) {
Enum<?> enumValue = (Enum<?>) value;
if (classes.contains(enumValue.getClass().getName())
|| packages.contains(enumValue.getClass().getPackage().getName())) {
append(enumValue.name());
} else {
|
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String ASSIGN = " = ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String COMMA = ", ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String DOT = ".";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String QUOTE = "\"";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SEMICOLON = ";";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SPACE = " ";
//
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
// Path: src/main/java/com/mysema/codegen/JavaWriter.java
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
}
@Override
public JavaWriter annotation(Class<? extends Annotation> annotation) throws IOException {
return beginLine().append("@").appendType(annotation).nl();
}
@SuppressWarnings("unchecked")
private void annotationConstant(Object value) throws IOException {
if (value.getClass().isArray()) {
append("{");
boolean first = true;
for (Object o : (Object[]) value) {
if (!first) {
append(", ");
}
annotationConstant(o);
first = false;
}
append("}");
} else if (value instanceof Class) {
appendType((Class) value).append(".class");
} else if (value instanceof Number || value instanceof Boolean) {
append(value.toString());
} else if (value instanceof Enum) {
Enum<?> enumValue = (Enum<?>) value;
if (classes.contains(enumValue.getClass().getName())
|| packages.contains(enumValue.getClass().getPackage().getName())) {
append(enumValue.name());
} else {
|
append(enumValue.getDeclaringClass().getName()).append(DOT).append(enumValue.name());
|
querydsl/codegen
|
src/main/java/com/mysema/codegen/JavaWriter.java
|
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String ASSIGN = " = ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String COMMA = ", ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String DOT = ".";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String QUOTE = "\"";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SEMICOLON = ";";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SPACE = " ";
//
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
|
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
|
return beginLine().append("@").appendType(annotation).nl();
}
@SuppressWarnings("unchecked")
private void annotationConstant(Object value) throws IOException {
if (value.getClass().isArray()) {
append("{");
boolean first = true;
for (Object o : (Object[]) value) {
if (!first) {
append(", ");
}
annotationConstant(o);
first = false;
}
append("}");
} else if (value instanceof Class) {
appendType((Class) value).append(".class");
} else if (value instanceof Number || value instanceof Boolean) {
append(value.toString());
} else if (value instanceof Enum) {
Enum<?> enumValue = (Enum<?>) value;
if (classes.contains(enumValue.getClass().getName())
|| packages.contains(enumValue.getClass().getPackage().getName())) {
append(enumValue.name());
} else {
append(enumValue.getDeclaringClass().getName()).append(DOT).append(enumValue.name());
}
} else if (value instanceof String) {
String escaped = StringUtils.escapeJava(value.toString());
|
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String ASSIGN = " = ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String COMMA = ", ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String DOT = ".";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String QUOTE = "\"";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SEMICOLON = ";";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SPACE = " ";
//
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
// Path: src/main/java/com/mysema/codegen/JavaWriter.java
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
return beginLine().append("@").appendType(annotation).nl();
}
@SuppressWarnings("unchecked")
private void annotationConstant(Object value) throws IOException {
if (value.getClass().isArray()) {
append("{");
boolean first = true;
for (Object o : (Object[]) value) {
if (!first) {
append(", ");
}
annotationConstant(o);
first = false;
}
append("}");
} else if (value instanceof Class) {
appendType((Class) value).append(".class");
} else if (value instanceof Number || value instanceof Boolean) {
append(value.toString());
} else if (value instanceof Enum) {
Enum<?> enumValue = (Enum<?>) value;
if (classes.contains(enumValue.getClass().getName())
|| packages.contains(enumValue.getClass().getPackage().getName())) {
append(enumValue.name());
} else {
append(enumValue.getDeclaringClass().getName()).append(DOT).append(enumValue.name());
}
} else if (value instanceof String) {
String escaped = StringUtils.escapeJava(value.toString());
|
append(QUOTE).append(escaped.replace("\\/", "/")).append(QUOTE);
|
querydsl/codegen
|
src/main/java/com/mysema/codegen/JavaWriter.java
|
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String ASSIGN = " = ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String COMMA = ", ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String DOT = ".";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String QUOTE = "\"";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SEMICOLON = ";";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SPACE = " ";
//
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
|
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
|
@Override
public JavaWriter beginClass(Type type) throws IOException {
return beginClass(type, null);
}
@Override
public JavaWriter beginClass(Type type, Type superClass, Type... interfaces) throws IOException {
packages.add(type.getPackageName());
beginLine(PUBLIC_CLASS, type.getGenericName(false, packages, classes));
if (superClass != null) {
append(EXTENDS).append(superClass.getGenericName(false, packages, classes));
}
if (interfaces.length > 0) {
append(IMPLEMENTS);
for (int i = 0; i < interfaces.length; i++) {
if (i > 0) {
append(COMMA);
}
append(interfaces[i].getGenericName(false, packages, classes));
}
}
append(" {").nl().nl();
goIn();
types.push(type);
return this;
}
@Override
public <T> JavaWriter beginConstructor(Collection<T> parameters,
|
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String ASSIGN = " = ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String COMMA = ", ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String DOT = ".";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String QUOTE = "\"";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SEMICOLON = ";";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SPACE = " ";
//
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
// Path: src/main/java/com/mysema/codegen/JavaWriter.java
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
@Override
public JavaWriter beginClass(Type type) throws IOException {
return beginClass(type, null);
}
@Override
public JavaWriter beginClass(Type type, Type superClass, Type... interfaces) throws IOException {
packages.add(type.getPackageName());
beginLine(PUBLIC_CLASS, type.getGenericName(false, packages, classes));
if (superClass != null) {
append(EXTENDS).append(superClass.getGenericName(false, packages, classes));
}
if (interfaces.length > 0) {
append(IMPLEMENTS);
for (int i = 0; i < interfaces.length; i++) {
if (i > 0) {
append(COMMA);
}
append(interfaces[i].getGenericName(false, packages, classes));
}
}
append(" {").nl().nl();
goIn();
types.push(type);
return this;
}
@Override
public <T> JavaWriter beginConstructor(Collection<T> parameters,
|
Function<T, Parameter> transformer) throws IOException {
|
querydsl/codegen
|
src/main/java/com/mysema/codegen/JavaWriter.java
|
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String ASSIGN = " = ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String COMMA = ", ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String DOT = ".";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String QUOTE = "\"";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SEMICOLON = ";";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SPACE = " ";
//
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
|
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
|
@Override
public JavaWriter beginConstructor(Parameter... parameters) throws IOException {
types.push(types.peek());
beginLine(PUBLIC, types.peek().getSimpleName()).params(parameters).append(" {").nl();
return goIn();
}
@Override
public JavaWriter beginInterface(Type type, Type... interfaces) throws IOException {
packages.add(type.getPackageName());
beginLine(PUBLIC_INTERFACE, type.getGenericName(false, packages, classes));
if (interfaces.length > 0) {
append(EXTENDS);
for (int i = 0; i < interfaces.length; i++) {
if (i > 0) {
append(COMMA);
}
append(interfaces[i].getGenericName(false, packages, classes));
}
}
append(" {").nl().nl();
goIn();
types.push(type);
return this;
}
private JavaWriter beginMethod(String modifiers, Type returnType, String methodName,
Parameter... args) throws IOException {
types.push(types.peek());
beginLine(
|
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String ASSIGN = " = ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String COMMA = ", ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String DOT = ".";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String QUOTE = "\"";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SEMICOLON = ";";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SPACE = " ";
//
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
// Path: src/main/java/com/mysema/codegen/JavaWriter.java
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
@Override
public JavaWriter beginConstructor(Parameter... parameters) throws IOException {
types.push(types.peek());
beginLine(PUBLIC, types.peek().getSimpleName()).params(parameters).append(" {").nl();
return goIn();
}
@Override
public JavaWriter beginInterface(Type type, Type... interfaces) throws IOException {
packages.add(type.getPackageName());
beginLine(PUBLIC_INTERFACE, type.getGenericName(false, packages, classes));
if (interfaces.length > 0) {
append(EXTENDS);
for (int i = 0; i < interfaces.length; i++) {
if (i > 0) {
append(COMMA);
}
append(interfaces[i].getGenericName(false, packages, classes));
}
}
append(" {").nl().nl();
goIn();
types.push(type);
return this;
}
private JavaWriter beginMethod(String modifiers, Type returnType, String methodName,
Parameter... args) throws IOException {
types.push(types.peek());
beginLine(
|
modifiers, returnType.getGenericName(true, packages, classes), SPACE, methodName)
|
querydsl/codegen
|
src/main/java/com/mysema/codegen/JavaWriter.java
|
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String ASSIGN = " = ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String COMMA = ", ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String DOT = ".";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String QUOTE = "\"";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SEMICOLON = ";";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SPACE = " ";
//
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
|
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
|
}
@Override
public JavaWriter beginPublicMethod(Type returnType, String methodName, Parameter... args)
throws IOException {
return beginMethod(PUBLIC, returnType, methodName, args);
}
@Override
public <T> JavaWriter beginStaticMethod(Type returnType, String methodName,
Collection<T> parameters, Function<T, Parameter> transformer) throws IOException {
return beginMethod(PUBLIC_STATIC, returnType, methodName,
transform(parameters, transformer));
}
@Override
public JavaWriter beginStaticMethod(Type returnType, String methodName, Parameter... args)
throws IOException {
return beginMethod(PUBLIC_STATIC, returnType, methodName, args);
}
@Override
public JavaWriter end() throws IOException {
types.pop();
goOut();
return line("}").nl();
}
@Override
public JavaWriter field(Type type, String name) throws IOException {
|
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String ASSIGN = " = ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String COMMA = ", ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String DOT = ".";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String QUOTE = "\"";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SEMICOLON = ";";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SPACE = " ";
//
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
// Path: src/main/java/com/mysema/codegen/JavaWriter.java
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
}
@Override
public JavaWriter beginPublicMethod(Type returnType, String methodName, Parameter... args)
throws IOException {
return beginMethod(PUBLIC, returnType, methodName, args);
}
@Override
public <T> JavaWriter beginStaticMethod(Type returnType, String methodName,
Collection<T> parameters, Function<T, Parameter> transformer) throws IOException {
return beginMethod(PUBLIC_STATIC, returnType, methodName,
transform(parameters, transformer));
}
@Override
public JavaWriter beginStaticMethod(Type returnType, String methodName, Parameter... args)
throws IOException {
return beginMethod(PUBLIC_STATIC, returnType, methodName, args);
}
@Override
public JavaWriter end() throws IOException {
types.pop();
goOut();
return line("}").nl();
}
@Override
public JavaWriter field(Type type, String name) throws IOException {
|
return line(type.getGenericName(true, packages, classes), SPACE, name, SEMICOLON).nl();
|
querydsl/codegen
|
src/main/java/com/mysema/codegen/JavaWriter.java
|
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String ASSIGN = " = ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String COMMA = ", ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String DOT = ".";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String QUOTE = "\"";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SEMICOLON = ";";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SPACE = " ";
//
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
|
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
|
}
@Override
public JavaWriter beginStaticMethod(Type returnType, String methodName, Parameter... args)
throws IOException {
return beginMethod(PUBLIC_STATIC, returnType, methodName, args);
}
@Override
public JavaWriter end() throws IOException {
types.pop();
goOut();
return line("}").nl();
}
@Override
public JavaWriter field(Type type, String name) throws IOException {
return line(type.getGenericName(true, packages, classes), SPACE, name, SEMICOLON).nl();
}
private JavaWriter field(String modifier, Type type, String name) throws IOException {
return line(
modifier, type.getGenericName(true, packages, classes), SPACE, name, SEMICOLON)
.nl();
}
private JavaWriter field(String modifier, Type type, String name, String value)
throws IOException {
return line(
modifier, type.getGenericName(true, packages, classes), SPACE, name,
|
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String ASSIGN = " = ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String COMMA = ", ";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String DOT = ".";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String QUOTE = "\"";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SEMICOLON = ";";
//
// Path: src/main/java/com/mysema/codegen/Symbols.java
// public static final String SPACE = " ";
//
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
// Path: src/main/java/com/mysema/codegen/JavaWriter.java
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
}
@Override
public JavaWriter beginStaticMethod(Type returnType, String methodName, Parameter... args)
throws IOException {
return beginMethod(PUBLIC_STATIC, returnType, methodName, args);
}
@Override
public JavaWriter end() throws IOException {
types.pop();
goOut();
return line("}").nl();
}
@Override
public JavaWriter field(Type type, String name) throws IOException {
return line(type.getGenericName(true, packages, classes), SPACE, name, SEMICOLON).nl();
}
private JavaWriter field(String modifier, Type type, String name) throws IOException {
return line(
modifier, type.getGenericName(true, packages, classes), SPACE, name, SEMICOLON)
.nl();
}
private JavaWriter field(String modifier, Type type, String name, String value)
throws IOException {
return line(
modifier, type.getGenericName(true, packages, classes), SPACE, name,
|
ASSIGN , value, SEMICOLON).nl();
|
querydsl/codegen
|
src/main/java/com/mysema/codegen/CodeWriter.java
|
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
|
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Collection;
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
|
/*
* Copyright 2010, Mysema Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mysema.codegen;
/**
* CodeWriter defines an interface for serializing Java source code
*
* @author tiwe
*
*/
public interface CodeWriter extends Appendable {
String getRawName(Type type);
String getGenericName(boolean asArgType, Type type);
String getClassConstant(String className);
CodeWriter annotation(Annotation annotation) throws IOException;
CodeWriter annotation(Class<? extends Annotation> annotation) throws IOException;
CodeWriter beginClass(Type type) throws IOException;
CodeWriter beginClass(Type type, Type superClass, Type... interfaces) throws IOException;
|
// Path: src/main/java/com/mysema/codegen/model/Parameter.java
// public final class Parameter {
//
// private final String name;
//
// private final Type type;
//
// public Parameter(String name, Type type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) {
// return true;
// } else if (o instanceof Parameter) {
// Parameter t = (Parameter) o;
// return type.equals(t.type) && name.equals(t.name);
// } else {
// return false;
// }
// }
//
// public String getName() {
// return name;
// }
//
// public Type getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return type.hashCode();
// }
//
// @Override
// public String toString() {
// return type + " " + name;
// }
// }
//
// Path: src/main/java/com/mysema/codegen/model/Type.java
// public interface Type {
//
// Type as(TypeCategory category);
//
// Type asArrayType();
//
// Type getComponentType();
//
// Type getEnclosingType();
//
// TypeCategory getCategory();
//
// String getFullName();
//
// String getGenericName(boolean asArgType);
//
// String getGenericName(boolean asArgType, Set<String> packages, Set<String> classes);
//
// Class<?> getJavaClass();
//
// String getPackageName();
//
// List<Type> getParameters();
//
// String getRawName(Set<String> packages, Set<String> classes);
//
// String getSimpleName();
//
// boolean isFinal();
//
// boolean isPrimitive();
//
// boolean isMember();
//
// }
// Path: src/main/java/com/mysema/codegen/CodeWriter.java
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Collection;
import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;
/*
* Copyright 2010, Mysema Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mysema.codegen;
/**
* CodeWriter defines an interface for serializing Java source code
*
* @author tiwe
*
*/
public interface CodeWriter extends Appendable {
String getRawName(Type type);
String getGenericName(boolean asArgType, Type type);
String getClassConstant(String className);
CodeWriter annotation(Annotation annotation) throws IOException;
CodeWriter annotation(Class<? extends Annotation> annotation) throws IOException;
CodeWriter beginClass(Type type) throws IOException;
CodeWriter beginClass(Type type, Type superClass, Type... interfaces) throws IOException;
|
<T> CodeWriter beginConstructor(Collection<T> params, Function<T, Parameter> transformer) throws IOException;
|
querydsl/codegen
|
src/main/java/com/mysema/codegen/model/ClassType.java
|
// Path: src/main/java/com/mysema/codegen/support/ClassUtils.java
// public final class ClassUtils {
//
// private static final Set<String> JAVA_LANG = Collections.singleton("java.lang");
//
// public static String getName(Class<?> cl) {
// return getName(cl, JAVA_LANG, Collections.<String> emptySet());
// }
//
// public static String getFullName(Class<?> cl) {
// if (cl.isArray()) {
// return getFullName(cl.getComponentType()) + "[]";
// }
// final String name = cl.getName();
// if (name.indexOf('$') > 0) {
// return getFullName(cl.getDeclaringClass()) + "." + cl.getSimpleName();
// }
// return name;
// }
//
// public static String getPackageName(Class<?> cl) {
// while (cl.isArray()) {
// cl = cl.getComponentType();
// }
// final String name = cl.getName();
// final int i = name.lastIndexOf('.');
// if (i > 0) {
// return name.substring(0, i);
// } else {
// return "";
// }
// }
//
// public static String getName(Class<?> cl, Set<String> packages, Set<String> classes) {
// if (cl.isArray()) {
// return getName(cl.getComponentType(), packages, classes) + "[]";
// }
// final String canonicalName = cl.getName().replace('$', '.');
// final int i = cl.getName().lastIndexOf('.');
// if (classes.contains(canonicalName)) {
// return cl.getSimpleName();
// } else if (cl.getEnclosingClass() != null) {
// return getName(cl.getEnclosingClass(), packages, classes) + "." + cl.getSimpleName();
// } else if (i == -1) {
// return canonicalName;
// } else if (packages.contains(canonicalName.substring(0, i))) {
// return canonicalName.substring(i + 1);
// } else {
// return canonicalName;
// }
// }
//
// public static Class<?> normalize(Class<?> clazz) {
// if (List.class.isAssignableFrom(clazz)) {
// return List.class;
// } else if (Set.class.isAssignableFrom(clazz)) {
// return Set.class;
// } else if (Collection.class.isAssignableFrom(clazz)) {
// return Collection.class;
// } else if (Map.class.isAssignableFrom(clazz)) {
// return Map.class;
// // check for CGLIB generated classes
// } else if (clazz.getName().contains("$$")) {
// Class<?> zuper = clazz.getSuperclass();
// if (zuper != null && !Object.class.equals(zuper)) {
// return zuper;
// }
// } else if (!Modifier.isPublic(clazz.getModifiers())) {
// return normalize(clazz.getSuperclass());
// }
// return clazz;
// }
//
// private ClassUtils() {
// }
//
// }
|
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import com.mysema.codegen.support.ClassUtils;
|
/*
* Copyright 2010, Mysema Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mysema.codegen.model;
/**
* @author tiwe
*
*/
public class ClassType implements Type {
private final TypeCategory category;
private final Class<?> javaClass;
private final String className;
private final List<Type> parameters;
private Type arrayType, componentType, enclosingType;
public ClassType(Class<?> javaClass, Type... parameters) {
this(TypeCategory.SIMPLE, javaClass, Arrays.asList(parameters));
}
public ClassType(TypeCategory category, Class<?> clazz, Type... parameters) {
this(category, clazz, Arrays.asList(parameters));
}
public ClassType(TypeCategory category, Class<?> clazz, List<Type> parameters) {
this.category = category;
this.javaClass = clazz;
this.parameters = parameters;
|
// Path: src/main/java/com/mysema/codegen/support/ClassUtils.java
// public final class ClassUtils {
//
// private static final Set<String> JAVA_LANG = Collections.singleton("java.lang");
//
// public static String getName(Class<?> cl) {
// return getName(cl, JAVA_LANG, Collections.<String> emptySet());
// }
//
// public static String getFullName(Class<?> cl) {
// if (cl.isArray()) {
// return getFullName(cl.getComponentType()) + "[]";
// }
// final String name = cl.getName();
// if (name.indexOf('$') > 0) {
// return getFullName(cl.getDeclaringClass()) + "." + cl.getSimpleName();
// }
// return name;
// }
//
// public static String getPackageName(Class<?> cl) {
// while (cl.isArray()) {
// cl = cl.getComponentType();
// }
// final String name = cl.getName();
// final int i = name.lastIndexOf('.');
// if (i > 0) {
// return name.substring(0, i);
// } else {
// return "";
// }
// }
//
// public static String getName(Class<?> cl, Set<String> packages, Set<String> classes) {
// if (cl.isArray()) {
// return getName(cl.getComponentType(), packages, classes) + "[]";
// }
// final String canonicalName = cl.getName().replace('$', '.');
// final int i = cl.getName().lastIndexOf('.');
// if (classes.contains(canonicalName)) {
// return cl.getSimpleName();
// } else if (cl.getEnclosingClass() != null) {
// return getName(cl.getEnclosingClass(), packages, classes) + "." + cl.getSimpleName();
// } else if (i == -1) {
// return canonicalName;
// } else if (packages.contains(canonicalName.substring(0, i))) {
// return canonicalName.substring(i + 1);
// } else {
// return canonicalName;
// }
// }
//
// public static Class<?> normalize(Class<?> clazz) {
// if (List.class.isAssignableFrom(clazz)) {
// return List.class;
// } else if (Set.class.isAssignableFrom(clazz)) {
// return Set.class;
// } else if (Collection.class.isAssignableFrom(clazz)) {
// return Collection.class;
// } else if (Map.class.isAssignableFrom(clazz)) {
// return Map.class;
// // check for CGLIB generated classes
// } else if (clazz.getName().contains("$$")) {
// Class<?> zuper = clazz.getSuperclass();
// if (zuper != null && !Object.class.equals(zuper)) {
// return zuper;
// }
// } else if (!Modifier.isPublic(clazz.getModifiers())) {
// return normalize(clazz.getSuperclass());
// }
// return clazz;
// }
//
// private ClassUtils() {
// }
//
// }
// Path: src/main/java/com/mysema/codegen/model/ClassType.java
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import com.mysema.codegen.support.ClassUtils;
/*
* Copyright 2010, Mysema Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mysema.codegen.model;
/**
* @author tiwe
*
*/
public class ClassType implements Type {
private final TypeCategory category;
private final Class<?> javaClass;
private final String className;
private final List<Type> parameters;
private Type arrayType, componentType, enclosingType;
public ClassType(Class<?> javaClass, Type... parameters) {
this(TypeCategory.SIMPLE, javaClass, Arrays.asList(parameters));
}
public ClassType(TypeCategory category, Class<?> clazz, Type... parameters) {
this(category, clazz, Arrays.asList(parameters));
}
public ClassType(TypeCategory category, Class<?> clazz, List<Type> parameters) {
this.category = category;
this.javaClass = clazz;
this.parameters = parameters;
|
this.className = ClassUtils.getFullName(javaClass);
|
GoogleCloudPlatform/healthcare-api-dicom-fuse
|
src/main/java/com/google/dicomwebfuse/dao/spec/SeriesPathBuilder.java
|
// Path: src/main/java/com/google/dicomwebfuse/dao/Constants.java
// public static final String DATASETS = "/datasets/";
//
// Path: src/main/java/com/google/dicomwebfuse/dao/Constants.java
// public static final String DICOM_STORES = "/dicomStores/";
//
// Path: src/main/java/com/google/dicomwebfuse/dao/Constants.java
// public static final String DICOM_WEB = "/dicomWeb";
//
// Path: src/main/java/com/google/dicomwebfuse/dao/Constants.java
// public static final String LOCATIONS = "/locations/";
//
// Path: src/main/java/com/google/dicomwebfuse/dao/Constants.java
// public static final String PROJECTS = "/projects/";
//
// Path: src/main/java/com/google/dicomwebfuse/dao/Constants.java
// public static final String SERIES = "/series/";
//
// Path: src/main/java/com/google/dicomwebfuse/dao/Constants.java
// public static final String STUDIES = "/studies/";
//
// Path: src/main/java/com/google/dicomwebfuse/exception/DicomFuseException.java
// public class DicomFuseException extends Exception {
//
// private int statusCode;
//
// public DicomFuseException(String message) {
// super(message);
// }
//
// public DicomFuseException(String message, Exception e) {
// super(message, e);
// }
//
// public DicomFuseException(Exception e) {
// super(e);
// }
//
// public DicomFuseException(String message, int statusCode) {
// super(message);
// this.statusCode = statusCode;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
// }
|
import static com.google.dicomwebfuse.dao.Constants.DATASETS;
import static com.google.dicomwebfuse.dao.Constants.DICOM_STORES;
import static com.google.dicomwebfuse.dao.Constants.DICOM_WEB;
import static com.google.dicomwebfuse.dao.Constants.LOCATIONS;
import static com.google.dicomwebfuse.dao.Constants.PROJECTS;
import static com.google.dicomwebfuse.dao.Constants.SERIES;
import static com.google.dicomwebfuse.dao.Constants.STUDIES;
import com.google.dicomwebfuse.exception.DicomFuseException;
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.dicomwebfuse.dao.spec;
public class SeriesPathBuilder implements PathBuilder {
private QueryBuilder queryBuilder;
public SeriesPathBuilder(QueryBuilder queryBuilder) {
this.queryBuilder = queryBuilder;
}
@Override
|
// Path: src/main/java/com/google/dicomwebfuse/dao/Constants.java
// public static final String DATASETS = "/datasets/";
//
// Path: src/main/java/com/google/dicomwebfuse/dao/Constants.java
// public static final String DICOM_STORES = "/dicomStores/";
//
// Path: src/main/java/com/google/dicomwebfuse/dao/Constants.java
// public static final String DICOM_WEB = "/dicomWeb";
//
// Path: src/main/java/com/google/dicomwebfuse/dao/Constants.java
// public static final String LOCATIONS = "/locations/";
//
// Path: src/main/java/com/google/dicomwebfuse/dao/Constants.java
// public static final String PROJECTS = "/projects/";
//
// Path: src/main/java/com/google/dicomwebfuse/dao/Constants.java
// public static final String SERIES = "/series/";
//
// Path: src/main/java/com/google/dicomwebfuse/dao/Constants.java
// public static final String STUDIES = "/studies/";
//
// Path: src/main/java/com/google/dicomwebfuse/exception/DicomFuseException.java
// public class DicomFuseException extends Exception {
//
// private int statusCode;
//
// public DicomFuseException(String message) {
// super(message);
// }
//
// public DicomFuseException(String message, Exception e) {
// super(message, e);
// }
//
// public DicomFuseException(Exception e) {
// super(e);
// }
//
// public DicomFuseException(String message, int statusCode) {
// super(message);
// this.statusCode = statusCode;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
// }
// Path: src/main/java/com/google/dicomwebfuse/dao/spec/SeriesPathBuilder.java
import static com.google.dicomwebfuse.dao.Constants.DATASETS;
import static com.google.dicomwebfuse.dao.Constants.DICOM_STORES;
import static com.google.dicomwebfuse.dao.Constants.DICOM_WEB;
import static com.google.dicomwebfuse.dao.Constants.LOCATIONS;
import static com.google.dicomwebfuse.dao.Constants.PROJECTS;
import static com.google.dicomwebfuse.dao.Constants.SERIES;
import static com.google.dicomwebfuse.dao.Constants.STUDIES;
import com.google.dicomwebfuse.exception.DicomFuseException;
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.dicomwebfuse.dao.spec;
public class SeriesPathBuilder implements PathBuilder {
private QueryBuilder queryBuilder;
public SeriesPathBuilder(QueryBuilder queryBuilder) {
this.queryBuilder = queryBuilder;
}
@Override
|
public String toPath() throws DicomFuseException {
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.