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
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToLongPrefixTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToLongPrefixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToLongPrefixTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToLongPrefixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
config.setSigningType(CopyBookFieldSigningType.PREFIX);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToLongPrefixTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToLongPrefixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.PREFIX); typeConverter = new SignedIntegerToLong(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Long.TYPE, 2, -1); }
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToLongPrefixTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToLongPrefixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.PREFIX); typeConverter = new SignedIntegerToLong(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Long.TYPE, 2, -1); }
@Test(expected = TypeConverterException.class)
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToIntegerPostfixTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToIntegerPostfixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToIntegerPostfixTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToIntegerPostfixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
config.setSigningType(CopyBookFieldSigningType.POSTFIX);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToIntegerPostfixTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToIntegerPostfixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.POSTFIX); typeConverter = new SignedIntegerToInteger(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Integer.TYPE, 2, -1); }
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToIntegerPostfixTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToIntegerPostfixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.POSTFIX); typeConverter = new SignedIntegerToInteger(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Integer.TYPE, 2, -1); }
@Test(expected = TypeConverterException.class)
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverterBase.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import java.nio.charset.Charset; import java.util.Arrays;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public abstract class TypeConverterBase implements TypeConverter { protected Charset charset;
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverterBase.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import java.nio.charset.Charset; import java.util.Arrays; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public abstract class TypeConverterBase implements TypeConverter { protected Charset charset;
protected CopyBookFieldSigningType signingType;
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverterBase.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import java.nio.charset.Charset; import java.util.Arrays;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public abstract class TypeConverterBase implements TypeConverter { protected Charset charset; protected CopyBookFieldSigningType signingType; protected boolean rightPadding; protected byte paddingByte; protected byte nullFillerByte; protected String defaultValue; protected String format; protected TypeConverterConfig config; @Override public void initialize(TypeConverterConfig config) { this.config = config; this.charset = config.getCharset(); this.signingType = config.getSigningType(); this.rightPadding = config.isRightPadding(); byte[] paddingBytes = ( config.getPaddingChar() + "").getBytes(this.charset); if(paddingBytes.length > 1) {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverterBase.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import java.nio.charset.Charset; import java.util.Arrays; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public abstract class TypeConverterBase implements TypeConverter { protected Charset charset; protected CopyBookFieldSigningType signingType; protected boolean rightPadding; protected byte paddingByte; protected byte nullFillerByte; protected String defaultValue; protected String format; protected TypeConverterConfig config; @Override public void initialize(TypeConverterConfig config) { this.config = config; this.charset = config.getCharset(); this.signingType = config.getSigningType(); this.rightPadding = config.isRightPadding(); byte[] paddingBytes = ( config.getPaddingChar() + "").getBytes(this.charset); if(paddingBytes.length > 1) {
throw new TypeConverterException("Selected charset and padding char is more than 1 byte long");
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperNullValuesTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToString.java // public class StringToString extends TypeConverterBase { // @Override // public void validate(Class<?> type, int size, int decimals) { // if(!(String.class.equals(type))) { // throw new TypeConverterException("Only supports converting to and from String"); // } // } // // @Override // public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) { // if(ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler // if(this.defaultValue != null) { // return this.defaultValue; // // } else { // return null; // } // // } else { // return getString(bytes, offset, length, removePadding, 0); // } // } // // @Override // public byte[] from(Object value, int length, int decimals, boolean addPadding) { // byte[] strBytes = null; // if(value != null || this.defaultValue != null) { // strBytes = (value != null ? (String)value : this.defaultValue).getBytes(this.charset); // if (strBytes.length > length) { // throw new TypeConverterException("Field to small for value: " + length + " < " + strBytes.length); // } // if (addPadding) { // strBytes = padBytes(strBytes, length); // } // // } else if(addPadding) { // strBytes = new byte[length]; // Arrays.fill(strBytes, this.nullFillerByte); // } // // return strBytes; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // }
import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookFieldFormat; import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.converters.StringToString; import com.nordea.oss.copybook.exceptions.CopyBookException; import org.junit.Rule; import org.junit.rules.ExpectedException; import java.math.BigInteger; import static org.junit.Assert.*;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookMapperNullValuesTest { @Rule public ExpectedException expectedEx = ExpectedException.none(); @CopyBook(type = FullMapper.class)
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToString.java // public class StringToString extends TypeConverterBase { // @Override // public void validate(Class<?> type, int size, int decimals) { // if(!(String.class.equals(type))) { // throw new TypeConverterException("Only supports converting to and from String"); // } // } // // @Override // public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) { // if(ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler // if(this.defaultValue != null) { // return this.defaultValue; // // } else { // return null; // } // // } else { // return getString(bytes, offset, length, removePadding, 0); // } // } // // @Override // public byte[] from(Object value, int length, int decimals, boolean addPadding) { // byte[] strBytes = null; // if(value != null || this.defaultValue != null) { // strBytes = (value != null ? (String)value : this.defaultValue).getBytes(this.charset); // if (strBytes.length > length) { // throw new TypeConverterException("Field to small for value: " + length + " < " + strBytes.length); // } // if (addPadding) { // strBytes = padBytes(strBytes, length); // } // // } else if(addPadding) { // strBytes = new byte[length]; // Arrays.fill(strBytes, this.nullFillerByte); // } // // return strBytes; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperNullValuesTest.java import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookFieldFormat; import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.converters.StringToString; import com.nordea.oss.copybook.exceptions.CopyBookException; import org.junit.Rule; import org.junit.rules.ExpectedException; import java.math.BigInteger; import static org.junit.Assert.*; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookMapperNullValuesTest { @Rule public ExpectedException expectedEx = ExpectedException.none(); @CopyBook(type = FullMapper.class)
@CopyBookFieldFormat(type = StringToString.class, paddingChar = ' ', nullFillerChar = (byte)0, signingType = CopyBookFieldSigningType.PREFIX, rightPadding = false)
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperNullValuesTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToString.java // public class StringToString extends TypeConverterBase { // @Override // public void validate(Class<?> type, int size, int decimals) { // if(!(String.class.equals(type))) { // throw new TypeConverterException("Only supports converting to and from String"); // } // } // // @Override // public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) { // if(ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler // if(this.defaultValue != null) { // return this.defaultValue; // // } else { // return null; // } // // } else { // return getString(bytes, offset, length, removePadding, 0); // } // } // // @Override // public byte[] from(Object value, int length, int decimals, boolean addPadding) { // byte[] strBytes = null; // if(value != null || this.defaultValue != null) { // strBytes = (value != null ? (String)value : this.defaultValue).getBytes(this.charset); // if (strBytes.length > length) { // throw new TypeConverterException("Field to small for value: " + length + " < " + strBytes.length); // } // if (addPadding) { // strBytes = padBytes(strBytes, length); // } // // } else if(addPadding) { // strBytes = new byte[length]; // Arrays.fill(strBytes, this.nullFillerByte); // } // // return strBytes; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // }
import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookFieldFormat; import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.converters.StringToString; import com.nordea.oss.copybook.exceptions.CopyBookException; import org.junit.Rule; import org.junit.rules.ExpectedException; import java.math.BigInteger; import static org.junit.Assert.*;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookMapperNullValuesTest { @Rule public ExpectedException expectedEx = ExpectedException.none(); @CopyBook(type = FullMapper.class) @CopyBookFieldFormat(type = StringToString.class, paddingChar = ' ', nullFillerChar = (byte)0, signingType = CopyBookFieldSigningType.PREFIX, rightPadding = false) static public class fieldTypeStringSetToNullFull { @CopyBookLine("01 FIELD PIC X(4).") public String field; } @org.junit.Test public void testFieldTypeStringSetToNullFull() throws Exception {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToString.java // public class StringToString extends TypeConverterBase { // @Override // public void validate(Class<?> type, int size, int decimals) { // if(!(String.class.equals(type))) { // throw new TypeConverterException("Only supports converting to and from String"); // } // } // // @Override // public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) { // if(ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler // if(this.defaultValue != null) { // return this.defaultValue; // // } else { // return null; // } // // } else { // return getString(bytes, offset, length, removePadding, 0); // } // } // // @Override // public byte[] from(Object value, int length, int decimals, boolean addPadding) { // byte[] strBytes = null; // if(value != null || this.defaultValue != null) { // strBytes = (value != null ? (String)value : this.defaultValue).getBytes(this.charset); // if (strBytes.length > length) { // throw new TypeConverterException("Field to small for value: " + length + " < " + strBytes.length); // } // if (addPadding) { // strBytes = padBytes(strBytes, length); // } // // } else if(addPadding) { // strBytes = new byte[length]; // Arrays.fill(strBytes, this.nullFillerByte); // } // // return strBytes; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperNullValuesTest.java import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookFieldFormat; import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.converters.StringToString; import com.nordea.oss.copybook.exceptions.CopyBookException; import org.junit.Rule; import org.junit.rules.ExpectedException; import java.math.BigInteger; import static org.junit.Assert.*; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookMapperNullValuesTest { @Rule public ExpectedException expectedEx = ExpectedException.none(); @CopyBook(type = FullMapper.class) @CopyBookFieldFormat(type = StringToString.class, paddingChar = ' ', nullFillerChar = (byte)0, signingType = CopyBookFieldSigningType.PREFIX, rightPadding = false) static public class fieldTypeStringSetToNullFull { @CopyBookLine("01 FIELD PIC X(4).") public String field; } @org.junit.Test public void testFieldTypeStringSetToNullFull() throws Exception {
CopyBookSerializer serializer = new CopyBookSerializer(fieldTypeStringSetToNullFull.class);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperNullValuesTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToString.java // public class StringToString extends TypeConverterBase { // @Override // public void validate(Class<?> type, int size, int decimals) { // if(!(String.class.equals(type))) { // throw new TypeConverterException("Only supports converting to and from String"); // } // } // // @Override // public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) { // if(ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler // if(this.defaultValue != null) { // return this.defaultValue; // // } else { // return null; // } // // } else { // return getString(bytes, offset, length, removePadding, 0); // } // } // // @Override // public byte[] from(Object value, int length, int decimals, boolean addPadding) { // byte[] strBytes = null; // if(value != null || this.defaultValue != null) { // strBytes = (value != null ? (String)value : this.defaultValue).getBytes(this.charset); // if (strBytes.length > length) { // throw new TypeConverterException("Field to small for value: " + length + " < " + strBytes.length); // } // if (addPadding) { // strBytes = padBytes(strBytes, length); // } // // } else if(addPadding) { // strBytes = new byte[length]; // Arrays.fill(strBytes, this.nullFillerByte); // } // // return strBytes; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // }
import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookFieldFormat; import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.converters.StringToString; import com.nordea.oss.copybook.exceptions.CopyBookException; import org.junit.Rule; import org.junit.rules.ExpectedException; import java.math.BigInteger; import static org.junit.Assert.*;
} @CopyBook() static public class ObjectFieldInt { @CopyBookLine("01 FIELD PIC 9(2).") public int value; } @CopyBook(type = FullMapper.class) static public class FieldTypeNestedIntNull { @CopyBookLine("01 FIELD.") public ObjectFieldInt field; } @org.junit.Test public void testFieldTypeNestedIntNull() throws Exception { CopyBookSerializer serializer = new CopyBookSerializer(FieldTypeNestedIntNull.class); FieldTypeNestedIntNull test = new FieldTypeNestedIntNull(); byte[] testBytes = serializer.serialize(test); assertArrayEquals(new byte[] { 48, 48 }, testBytes); } @CopyBook(type = FullMapper.class, strict = true) static public class FieldTypeNestedIntNullStrict { @CopyBookLine("01 FIELD.") public ObjectFieldInt field; } @org.junit.Test public void testFieldTypeNestedIntNullStrict() throws Exception {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToString.java // public class StringToString extends TypeConverterBase { // @Override // public void validate(Class<?> type, int size, int decimals) { // if(!(String.class.equals(type))) { // throw new TypeConverterException("Only supports converting to and from String"); // } // } // // @Override // public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) { // if(ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler // if(this.defaultValue != null) { // return this.defaultValue; // // } else { // return null; // } // // } else { // return getString(bytes, offset, length, removePadding, 0); // } // } // // @Override // public byte[] from(Object value, int length, int decimals, boolean addPadding) { // byte[] strBytes = null; // if(value != null || this.defaultValue != null) { // strBytes = (value != null ? (String)value : this.defaultValue).getBytes(this.charset); // if (strBytes.length > length) { // throw new TypeConverterException("Field to small for value: " + length + " < " + strBytes.length); // } // if (addPadding) { // strBytes = padBytes(strBytes, length); // } // // } else if(addPadding) { // strBytes = new byte[length]; // Arrays.fill(strBytes, this.nullFillerByte); // } // // return strBytes; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperNullValuesTest.java import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookFieldFormat; import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.converters.StringToString; import com.nordea.oss.copybook.exceptions.CopyBookException; import org.junit.Rule; import org.junit.rules.ExpectedException; import java.math.BigInteger; import static org.junit.Assert.*; } @CopyBook() static public class ObjectFieldInt { @CopyBookLine("01 FIELD PIC 9(2).") public int value; } @CopyBook(type = FullMapper.class) static public class FieldTypeNestedIntNull { @CopyBookLine("01 FIELD.") public ObjectFieldInt field; } @org.junit.Test public void testFieldTypeNestedIntNull() throws Exception { CopyBookSerializer serializer = new CopyBookSerializer(FieldTypeNestedIntNull.class); FieldTypeNestedIntNull test = new FieldTypeNestedIntNull(); byte[] testBytes = serializer.serialize(test); assertArrayEquals(new byte[] { 48, 48 }, testBytes); } @CopyBook(type = FullMapper.class, strict = true) static public class FieldTypeNestedIntNullStrict { @CopyBookLine("01 FIELD.") public ObjectFieldInt field; } @org.junit.Test public void testFieldTypeNestedIntNullStrict() throws Exception {
expectedEx.expect(CopyBookException.class);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/IntegerToTypeConverterIntEnumTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToTypeConverterIntEnumTest { private TypeConverter typeConverter; private TypeConverterConfig config; public enum TestIntEnum implements TypeConverterIntEnum { HIGH(30), MEDIUM(20), LOW(10); private final int value; TestIntEnum(int value) { this.value = value; } public int getValue() { return value; } } @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); typeConverter = new IntegerToTypeConverterIntEnum(); typeConverter.initialize(config); typeConverter.validate(TestIntEnum.class, 2, 1); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(TestIntEnum.class, 2, -1); }
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/IntegerToTypeConverterIntEnumTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToTypeConverterIntEnumTest { private TypeConverter typeConverter; private TypeConverterConfig config; public enum TestIntEnum implements TypeConverterIntEnum { HIGH(30), MEDIUM(20), LOW(10); private final int value; TestIntEnum(int value) { this.value = value; } public int getValue() { return value; } } @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); typeConverter = new IntegerToTypeConverterIntEnum(); typeConverter.initialize(config); typeConverter.validate(TestIntEnum.class, 2, 1); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(TestIntEnum.class, 2, -1); }
@Test(expected = TypeConverterException.class)
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToIntegerPrefixTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToIntegerPrefixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToIntegerPrefixTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToIntegerPrefixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
config.setSigningType(CopyBookFieldSigningType.PREFIX);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToIntegerPrefixTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToIntegerPrefixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.PREFIX); typeConverter = new SignedIntegerToInteger(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Integer.TYPE, 2, -1); }
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToIntegerPrefixTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToIntegerPrefixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.PREFIX); typeConverter = new SignedIntegerToInteger(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Integer.TYPE, 2, -1); }
@Test(expected = TypeConverterException.class)
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedIntegerToLong.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToLong extends SignedIntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedIntegerToLong.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToLong extends SignedIntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) {
if(size > 22 && (this.signingType == CopyBookFieldSigningType.PREFIX || this.signingType == CopyBookFieldSigningType.POSTFIX)) {
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedIntegerToLong.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToLong extends SignedIntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(size > 22 && (this.signingType == CopyBookFieldSigningType.PREFIX || this.signingType == CopyBookFieldSigningType.POSTFIX)) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedIntegerToLong.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToLong extends SignedIntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(size > 22 && (this.signingType == CopyBookFieldSigningType.PREFIX || this.signingType == CopyBookFieldSigningType.POSTFIX)) {
throw new TypeConverterException("long is not large enough to hold possible value");
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedIntegerToLong.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToLong extends SignedIntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(size > 22 && (this.signingType == CopyBookFieldSigningType.PREFIX || this.signingType == CopyBookFieldSigningType.POSTFIX)) { throw new TypeConverterException("long is not large enough to hold possible value"); } if(size > 21 && (this.signingType == CopyBookFieldSigningType.LAST_BYTE_BIT8 || this.signingType == CopyBookFieldSigningType.LAST_BYTE_EBCDIC_BIT5)) { throw new TypeConverterException("long is not large enough to hold possible value"); } if(!(Long.class.equals(type) || Long.TYPE.equals(type))) { throw new TypeConverterException("Only supports converting to and from long or Long"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedIntegerToLong.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToLong extends SignedIntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(size > 22 && (this.signingType == CopyBookFieldSigningType.PREFIX || this.signingType == CopyBookFieldSigningType.POSTFIX)) { throw new TypeConverterException("long is not large enough to hold possible value"); } if(size > 21 && (this.signingType == CopyBookFieldSigningType.LAST_BYTE_BIT8 || this.signingType == CopyBookFieldSigningType.LAST_BYTE_EBCDIC_BIT5)) { throw new TypeConverterException("long is not large enough to hold possible value"); } if(!(Long.class.equals(type) || Long.TYPE.equals(type))) { throw new TypeConverterException("Only supports converting to and from long or Long"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
if(this.defaultValue != null && ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/annotations/CopyBookFieldFormat.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverter.java // public interface TypeConverter { // void initialize(TypeConverterConfig config); // void validate(Class<?> type, int size, int decimals); // TypeConverter copy(Class<?> type) throws IllegalAccessException, InstantiationException; // Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding); // byte[] from(Object value, int length, int decimals, boolean addPadding); // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.converters.TypeConverter; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import java.lang.annotation.*;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.annotations; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.FIELD }) @Repeatable(CopyBookFieldFormats.class) public @interface CopyBookFieldFormat {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverter.java // public interface TypeConverter { // void initialize(TypeConverterConfig config); // void validate(Class<?> type, int size, int decimals); // TypeConverter copy(Class<?> type) throws IllegalAccessException, InstantiationException; // Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding); // byte[] from(Object value, int length, int decimals, boolean addPadding); // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/annotations/CopyBookFieldFormat.java import com.nordea.oss.copybook.converters.TypeConverter; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import java.lang.annotation.*; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.annotations; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.FIELD }) @Repeatable(CopyBookFieldFormats.class) public @interface CopyBookFieldFormat {
Class<? extends TypeConverter> type();
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/annotations/CopyBookFieldFormat.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverter.java // public interface TypeConverter { // void initialize(TypeConverterConfig config); // void validate(Class<?> type, int size, int decimals); // TypeConverter copy(Class<?> type) throws IllegalAccessException, InstantiationException; // Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding); // byte[] from(Object value, int length, int decimals, boolean addPadding); // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.converters.TypeConverter; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import java.lang.annotation.*;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.annotations; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.FIELD }) @Repeatable(CopyBookFieldFormats.class) public @interface CopyBookFieldFormat { Class<? extends TypeConverter> type();
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverter.java // public interface TypeConverter { // void initialize(TypeConverterConfig config); // void validate(Class<?> type, int size, int decimals); // TypeConverter copy(Class<?> type) throws IllegalAccessException, InstantiationException; // Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding); // byte[] from(Object value, int length, int decimals, boolean addPadding); // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/annotations/CopyBookFieldFormat.java import com.nordea.oss.copybook.converters.TypeConverter; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import java.lang.annotation.*; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.annotations; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.FIELD }) @Repeatable(CopyBookFieldFormats.class) public @interface CopyBookFieldFormat { Class<? extends TypeConverter> type();
CopyBookFieldSigningType signingType() default CopyBookFieldSigningType.PREFIX;
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookParserMappingExceptionTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // }
import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.exceptions.CopyBookException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException;
@CopyBook() public class ArrayOfObjectToStringArray { @CopyBookLine("01 OBJS OCCURS 10 TIMES.") private String[] fields; } @CopyBook() public class IntegerArrayToInteger { @CopyBookLine("01 FIELDS OCCURS 10 TIMES.") @CopyBookLine("02 FIELD PIC 9(8).") private int fields; } @CopyBook() public class StringArrayToString { @CopyBookLine("01 FIELDS OCCURS 10 TIMES.") @CopyBookLine("02 FIELD PIC X(8).") private String fields; } @CopyBook() public class ArrayOfObjectToString { @CopyBookLine("01 OBJS OCCURS 10 TIMES.") private String fields; } @Test public void testIntegerToString() throws Exception {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookParserMappingExceptionTest.java import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.exceptions.CopyBookException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @CopyBook() public class ArrayOfObjectToStringArray { @CopyBookLine("01 OBJS OCCURS 10 TIMES.") private String[] fields; } @CopyBook() public class IntegerArrayToInteger { @CopyBookLine("01 FIELDS OCCURS 10 TIMES.") @CopyBookLine("02 FIELD PIC 9(8).") private int fields; } @CopyBook() public class StringArrayToString { @CopyBookLine("01 FIELDS OCCURS 10 TIMES.") @CopyBookLine("02 FIELD PIC X(8).") private String fields; } @CopyBook() public class ArrayOfObjectToString { @CopyBookLine("01 OBJS OCCURS 10 TIMES.") private String fields; } @Test public void testIntegerToString() throws Exception {
expectedEx.expect(CopyBookException.class);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToBigIntegerPrefixTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToBigIntegerPrefixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToBigIntegerPrefixTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToBigIntegerPrefixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
config.setSigningType(CopyBookFieldSigningType.PREFIX);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToBigIntegerPrefixTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToBigIntegerPrefixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.PREFIX); typeConverter = new SignedIntegerToBigInteger(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(BigInteger.class, 2, -1); }
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToBigIntegerPrefixTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToBigIntegerPrefixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.PREFIX); typeConverter = new SignedIntegerToBigInteger(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(BigInteger.class, 2, -1); }
@Test(expected = TypeConverterException.class)
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/StringToLocalDateTimeTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToLocalDateTimeTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); this.config.setFormat("yyyyMMddHHmmss"); typeConverter = new StringToLocalDateTime(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(LocalDateTime.class, 2, -1); }
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/StringToLocalDateTimeTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToLocalDateTimeTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); this.config.setFormat("yyyyMMddHHmmss"); typeConverter = new StringToLocalDateTime(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(LocalDateTime.class, 2, -1); }
@Test(expected = TypeConverterException.class)
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedDecimalToBigDecimalPrefixTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedDecimalToBigDecimalPrefixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedDecimalToBigDecimalPrefixTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedDecimalToBigDecimalPrefixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
config.setSigningType(CopyBookFieldSigningType.PREFIX);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedDecimalToBigDecimalPrefixTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedDecimalToBigDecimalPrefixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.PREFIX); typeConverter = new SignedDecimalToBigDecimal(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(BigDecimal.class, 10, -1); } @Test public void testValidateFail() throws Exception {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedDecimalToBigDecimalPrefixTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedDecimalToBigDecimalPrefixTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.PREFIX); typeConverter = new SignedDecimalToBigDecimal(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(BigDecimal.class, 10, -1); } @Test public void testValidateFail() throws Exception {
expectedEx.expect(TypeConverterException.class);
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverterConfig.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import java.nio.charset.Charset;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class TypeConverterConfig { private Charset charset;
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverterConfig.java import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import java.nio.charset.Charset; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class TypeConverterConfig { private Charset charset;
private CopyBookFieldSigningType signingType;
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookField.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverter.java // public interface TypeConverter { // void initialize(TypeConverterConfig config); // void validate(Class<?> type, int size, int decimals); // TypeConverter copy(Class<?> type) throws IllegalAccessException, InstantiationException; // Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding); // byte[] from(Object value, int length, int decimals, boolean addPadding); // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // }
import com.nordea.oss.copybook.converters.TypeConverter; import com.nordea.oss.copybook.exceptions.CopyBookException; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookField { private List<CopyBookField> subCopyBookFields; // TODO: Change to types and Class[] private Class<?> type; private Field field; private String[] lines; // TODO: Change to converters and TypeConverterBase[]
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverter.java // public interface TypeConverter { // void initialize(TypeConverterConfig config); // void validate(Class<?> type, int size, int decimals); // TypeConverter copy(Class<?> type) throws IllegalAccessException, InstantiationException; // Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding); // byte[] from(Object value, int length, int decimals, boolean addPadding); // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookField.java import com.nordea.oss.copybook.converters.TypeConverter; import com.nordea.oss.copybook.exceptions.CopyBookException; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookField { private List<CopyBookField> subCopyBookFields; // TODO: Change to types and Class[] private Class<?> type; private Field field; private String[] lines; // TODO: Change to converters and TypeConverterBase[]
private TypeConverter converter;
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookField.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverter.java // public interface TypeConverter { // void initialize(TypeConverterConfig config); // void validate(Class<?> type, int size, int decimals); // TypeConverter copy(Class<?> type) throws IllegalAccessException, InstantiationException; // Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding); // byte[] from(Object value, int length, int decimals, boolean addPadding); // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // }
import com.nordea.oss.copybook.converters.TypeConverter; import com.nordea.oss.copybook.exceptions.CopyBookException; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List;
this.counterKey = counterKey; this.converter = converter; this.name = name; this.size = size; this.decimals = decimals; this.minOccurs = minOccurs; this.maxOccurs = maxOccurs; } public Object setBytes(Object obj, ByteBuffer buffer, boolean removePadding) { byte[] bytes = new byte[this.size]; buffer.get(bytes); return setBytes(obj, bytes, 0, bytes.length, removePadding); } public Object setBytes(Object obj, byte[] bytes, boolean removePadding) { return setBytes(obj, bytes, 0, bytes != null ? bytes.length : 0, removePadding); } public Object setBytes(Object obj, byte[] bytes, int offset, int length, boolean removePadding) { try { Object value = bytes != null ? converter.to(bytes, offset, length, this.decimals, removePadding) : null; field.set(obj, value); return value; } catch (IllegalAccessException ex) { // We already set it to accessible so this should not happen return null; } catch (Exception ex) {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverter.java // public interface TypeConverter { // void initialize(TypeConverterConfig config); // void validate(Class<?> type, int size, int decimals); // TypeConverter copy(Class<?> type) throws IllegalAccessException, InstantiationException; // Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding); // byte[] from(Object value, int length, int decimals, boolean addPadding); // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookField.java import com.nordea.oss.copybook.converters.TypeConverter; import com.nordea.oss.copybook.exceptions.CopyBookException; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; this.counterKey = counterKey; this.converter = converter; this.name = name; this.size = size; this.decimals = decimals; this.minOccurs = minOccurs; this.maxOccurs = maxOccurs; } public Object setBytes(Object obj, ByteBuffer buffer, boolean removePadding) { byte[] bytes = new byte[this.size]; buffer.get(bytes); return setBytes(obj, bytes, 0, bytes.length, removePadding); } public Object setBytes(Object obj, byte[] bytes, boolean removePadding) { return setBytes(obj, bytes, 0, bytes != null ? bytes.length : 0, removePadding); } public Object setBytes(Object obj, byte[] bytes, int offset, int length, boolean removePadding) { try { Object value = bytes != null ? converter.to(bytes, offset, length, this.decimals, removePadding) : null; field.set(obj, value); return value; } catch (IllegalAccessException ex) { // We already set it to accessible so this should not happen return null; } catch (Exception ex) {
throw new CopyBookException(getFieldName() + ": ", ex);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToIntegerLastByteBit8Test.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToIntegerLastByteBit8Test { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToIntegerLastByteBit8Test.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToIntegerLastByteBit8Test { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0');
config.setSigningType(CopyBookFieldSigningType.LAST_BYTE_BIT8);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToIntegerLastByteBit8Test.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToIntegerLastByteBit8Test { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.LAST_BYTE_BIT8); typeConverter = new SignedIntegerToInteger(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Integer.TYPE, 2, -1); }
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookFieldSigningType.java // public enum CopyBookFieldSigningType { // POSTFIX, // PREFIX, // LAST_BYTE_BIT8, // LAST_BYTE_EBCDIC_BIT5 // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/SignedIntegerToIntegerLastByteBit8Test.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.copybook.serializers.CopyBookFieldSigningType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToIntegerLastByteBit8Test { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); config.setSigningType(CopyBookFieldSigningType.LAST_BYTE_BIT8); typeConverter = new SignedIntegerToInteger(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Integer.TYPE, 2, -1); }
@Test(expected = TypeConverterException.class)
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperFullCharsetTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToString.java // public class StringToString extends TypeConverterBase { // @Override // public void validate(Class<?> type, int size, int decimals) { // if(!(String.class.equals(type))) { // throw new TypeConverterException("Only supports converting to and from String"); // } // } // // @Override // public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) { // if(ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler // if(this.defaultValue != null) { // return this.defaultValue; // // } else { // return null; // } // // } else { // return getString(bytes, offset, length, removePadding, 0); // } // } // // @Override // public byte[] from(Object value, int length, int decimals, boolean addPadding) { // byte[] strBytes = null; // if(value != null || this.defaultValue != null) { // strBytes = (value != null ? (String)value : this.defaultValue).getBytes(this.charset); // if (strBytes.length > length) { // throw new TypeConverterException("Field to small for value: " + length + " < " + strBytes.length); // } // if (addPadding) { // strBytes = padBytes(strBytes, length); // } // // } else if(addPadding) { // strBytes = new byte[length]; // Arrays.fill(strBytes, this.nullFillerByte); // } // // return strBytes; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // }
import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.converters.StringToString; import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookFieldFormat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookMapperFullCharsetTest { @CopyBook(charset = "cp037", type = FullMapper.class)
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToString.java // public class StringToString extends TypeConverterBase { // @Override // public void validate(Class<?> type, int size, int decimals) { // if(!(String.class.equals(type))) { // throw new TypeConverterException("Only supports converting to and from String"); // } // } // // @Override // public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) { // if(ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler // if(this.defaultValue != null) { // return this.defaultValue; // // } else { // return null; // } // // } else { // return getString(bytes, offset, length, removePadding, 0); // } // } // // @Override // public byte[] from(Object value, int length, int decimals, boolean addPadding) { // byte[] strBytes = null; // if(value != null || this.defaultValue != null) { // strBytes = (value != null ? (String)value : this.defaultValue).getBytes(this.charset); // if (strBytes.length > length) { // throw new TypeConverterException("Field to small for value: " + length + " < " + strBytes.length); // } // if (addPadding) { // strBytes = padBytes(strBytes, length); // } // // } else if(addPadding) { // strBytes = new byte[length]; // Arrays.fill(strBytes, this.nullFillerByte); // } // // return strBytes; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperFullCharsetTest.java import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.converters.StringToString; import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookFieldFormat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookMapperFullCharsetTest { @CopyBook(charset = "cp037", type = FullMapper.class)
@CopyBookFieldFormat(type = StringToString.class, paddingChar = ' ', nullFillerChar = (byte)0, signingType = CopyBookFieldSigningType.PREFIX, rightPadding = false)
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperFullCharsetTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToString.java // public class StringToString extends TypeConverterBase { // @Override // public void validate(Class<?> type, int size, int decimals) { // if(!(String.class.equals(type))) { // throw new TypeConverterException("Only supports converting to and from String"); // } // } // // @Override // public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) { // if(ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler // if(this.defaultValue != null) { // return this.defaultValue; // // } else { // return null; // } // // } else { // return getString(bytes, offset, length, removePadding, 0); // } // } // // @Override // public byte[] from(Object value, int length, int decimals, boolean addPadding) { // byte[] strBytes = null; // if(value != null || this.defaultValue != null) { // strBytes = (value != null ? (String)value : this.defaultValue).getBytes(this.charset); // if (strBytes.length > length) { // throw new TypeConverterException("Field to small for value: " + length + " < " + strBytes.length); // } // if (addPadding) { // strBytes = padBytes(strBytes, length); // } // // } else if(addPadding) { // strBytes = new byte[length]; // Arrays.fill(strBytes, this.nullFillerByte); // } // // return strBytes; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // }
import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.converters.StringToString; import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookFieldFormat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookMapperFullCharsetTest { @CopyBook(charset = "cp037", type = FullMapper.class) @CopyBookFieldFormat(type = StringToString.class, paddingChar = ' ', nullFillerChar = (byte)0, signingType = CopyBookFieldSigningType.PREFIX, rightPadding = false) static public class fieldTypeStringCp037 { @CopyBookLine("01 FIELD PIC X(4).") public String field; } @org.junit.Test public void testFieldTypeStringCp037() throws Exception {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToString.java // public class StringToString extends TypeConverterBase { // @Override // public void validate(Class<?> type, int size, int decimals) { // if(!(String.class.equals(type))) { // throw new TypeConverterException("Only supports converting to and from String"); // } // } // // @Override // public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) { // if(ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler // if(this.defaultValue != null) { // return this.defaultValue; // // } else { // return null; // } // // } else { // return getString(bytes, offset, length, removePadding, 0); // } // } // // @Override // public byte[] from(Object value, int length, int decimals, boolean addPadding) { // byte[] strBytes = null; // if(value != null || this.defaultValue != null) { // strBytes = (value != null ? (String)value : this.defaultValue).getBytes(this.charset); // if (strBytes.length > length) { // throw new TypeConverterException("Field to small for value: " + length + " < " + strBytes.length); // } // if (addPadding) { // strBytes = padBytes(strBytes, length); // } // // } else if(addPadding) { // strBytes = new byte[length]; // Arrays.fill(strBytes, this.nullFillerByte); // } // // return strBytes; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperFullCharsetTest.java import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.converters.StringToString; import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookFieldFormat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookMapperFullCharsetTest { @CopyBook(charset = "cp037", type = FullMapper.class) @CopyBookFieldFormat(type = StringToString.class, paddingChar = ' ', nullFillerChar = (byte)0, signingType = CopyBookFieldSigningType.PREFIX, rightPadding = false) static public class fieldTypeStringCp037 { @CopyBookLine("01 FIELD PIC X(4).") public String field; } @org.junit.Test public void testFieldTypeStringCp037() throws Exception {
CopyBookSerializer serializer = new CopyBookSerializer(fieldTypeStringCp037.class);
NordeaOSS/copybook4java
copybook4java-codegen-maven-plugin/src/test/java/com/nordea/oss/copybook/codegen/CopyBookConverterTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // }
import com.nordea.oss.ByteUtils; import org.junit.Rule; import org.junit.rules.ExpectedException; import javax.script.ScriptException; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import static org.junit.Assert.assertEquals;
InputStream rootObjSample = this.getClass().getResourceAsStream("../../../../../rootobj.txt"); convertedJavaSources.addAll(converter.convert(rootObjSample, "mypackage", "RootObj", "none", "UTF-8", "nested", null)); List<String> errors = CompileGeneratedSource(convertedJavaSources); assertEquals(0, errors.size()); } @org.junit.Test public void testBasicConversionWithError() throws Exception { expectedEx.expect(ScriptException.class); expectedEx.expectMessage("Could not parse line"); String sample = "05 ERROR PIC 9(5) OCCURSZ 6."; CopyBookConverter converter = new CopyBookConverter(); List<String> result = converter.convert(sample, "mypackage", "MyHospital", "none", "UTF-8", "nested", null); } @org.junit.Test public void testMultiFileConversion() throws Exception { File basePath = new File(this.getClass().getResource("../../../../").toURI()); CopyBookConverter converter = new CopyBookConverter(); converter.convertFiles(basePath.getAbsolutePath(), Pattern.compile("\\.txt$"), basePath.getAbsolutePath(), "mypackage", "none", "UTF-8", "nested"); } private List<String> CompileGeneratedSource(List<String> convertedJavaSources) throws Exception { File annotationsFolder = new File(this.getClass().getResource(".").getFile() + "../../../../../../../../copybook4java/src/main/java/com/nordea/oss/copybook/annotations"); List<String> sources = new ArrayList<>(); for(File file : annotationsFolder.listFiles()) { if(file.isFile() && file.getName().endsWith(".java")) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // Path: copybook4java-codegen-maven-plugin/src/test/java/com/nordea/oss/copybook/codegen/CopyBookConverterTest.java import com.nordea.oss.ByteUtils; import org.junit.Rule; import org.junit.rules.ExpectedException; import javax.script.ScriptException; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import static org.junit.Assert.assertEquals; InputStream rootObjSample = this.getClass().getResourceAsStream("../../../../../rootobj.txt"); convertedJavaSources.addAll(converter.convert(rootObjSample, "mypackage", "RootObj", "none", "UTF-8", "nested", null)); List<String> errors = CompileGeneratedSource(convertedJavaSources); assertEquals(0, errors.size()); } @org.junit.Test public void testBasicConversionWithError() throws Exception { expectedEx.expect(ScriptException.class); expectedEx.expectMessage("Could not parse line"); String sample = "05 ERROR PIC 9(5) OCCURSZ 6."; CopyBookConverter converter = new CopyBookConverter(); List<String> result = converter.convert(sample, "mypackage", "MyHospital", "none", "UTF-8", "nested", null); } @org.junit.Test public void testMultiFileConversion() throws Exception { File basePath = new File(this.getClass().getResource("../../../../").toURI()); CopyBookConverter converter = new CopyBookConverter(); converter.convertFiles(basePath.getAbsolutePath(), Pattern.compile("\\.txt$"), basePath.getAbsolutePath(), "mypackage", "none", "UTF-8", "nested"); } private List<String> CompileGeneratedSource(List<String> convertedJavaSources) throws Exception { File annotationsFolder = new File(this.getClass().getResource(".").getFile() + "../../../../../../../../copybook4java/src/main/java/com/nordea/oss/copybook/annotations"); List<String> sources = new ArrayList<>(); for(File file : annotationsFolder.listFiles()) { if(file.isFile() && file.getName().endsWith(".java")) {
sources.add(new String(ByteUtils.toByteArray(new FileInputStream(file)), StandardCharsets.UTF_8));
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/IntegerToTypeConverterIntEnum.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.util.HashMap; import java.util.Map;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToTypeConverterIntEnum extends IntegerToInteger { Class<?> type; Object[] enumConstants; Map<Integer,Object> toEnumMap = new HashMap<>(); Map<Object,byte[]> fromEnumMap = new HashMap<>(); @Override public void validate(Class<?> type, int size, int decimals) { if(!(TypeConverterIntEnum.class.isAssignableFrom(type))) {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/IntegerToTypeConverterIntEnum.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.util.HashMap; import java.util.Map; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToTypeConverterIntEnum extends IntegerToInteger { Class<?> type; Object[] enumConstants; Map<Integer,Object> toEnumMap = new HashMap<>(); Map<Object,byte[]> fromEnumMap = new HashMap<>(); @Override public void validate(Class<?> type, int size, int decimals) { if(!(TypeConverterIntEnum.class.isAssignableFrom(type))) {
throw new TypeConverterException("Only supports converting to and from TypeConverterIntEnum");
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/IntegerToLongTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToLongTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); typeConverter = new IntegerToLong(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Long.TYPE, 10, -1); }
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/IntegerToLongTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToLongTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); typeConverter = new IntegerToLong(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Long.TYPE, 10, -1); }
@Test(expected = TypeConverterException.class)
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedIntegerToBigInteger.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.math.BigInteger;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToBigInteger extends SignedIntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!BigInteger.class.equals(type)) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedIntegerToBigInteger.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.math.BigInteger; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToBigInteger extends SignedIntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!BigInteger.class.equals(type)) {
throw new TypeConverterException("Only supports converting to and from BigInteger");
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedIntegerToBigInteger.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.math.BigInteger;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToBigInteger extends SignedIntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!BigInteger.class.equals(type)) { throw new TypeConverterException("Only supports converting to and from BigInteger"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/SignedIntegerToBigInteger.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.math.BigInteger; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class SignedIntegerToBigInteger extends SignedIntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!BigInteger.class.equals(type)) { throw new TypeConverterException("Only supports converting to and from BigInteger"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
if(this.defaultValue != null && ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToBoolean.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToBoolean extends StringToString { private String[] values; @Override public void initialize(TypeConverterConfig config) { super.initialize(config); values = format.split("\\|"); if(values.length != 2) {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToBoolean.java import com.nordea.oss.copybook.exceptions.TypeConverterException; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToBoolean extends StringToString { private String[] values; @Override public void initialize(TypeConverterConfig config) { super.initialize(config); values = format.split("\\|"); if(values.length != 2) {
throw new TypeConverterException("A minimum of two values should be provided in the format with | as seperator");
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/IntegerToInteger.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.ByteUtils;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToInteger extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimal) { if(size > 9) {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/IntegerToInteger.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.ByteUtils; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToInteger extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimal) { if(size > 9) {
throw new TypeConverterException("int is not large enough to hold possible value");
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/IntegerToInteger.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.ByteUtils;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToInteger extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimal) { if(size > 9) { throw new TypeConverterException("int is not large enough to hold possible value"); } if(!(Integer.class.equals(type) || Integer.TYPE.equals(type))) { throw new TypeConverterException("Only supports converting to and from int or Integer"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/IntegerToInteger.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import com.nordea.oss.ByteUtils; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToInteger extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimal) { if(size > 9) { throw new TypeConverterException("int is not large enough to hold possible value"); } if(!(Integer.class.equals(type) || Integer.TYPE.equals(type))) { throw new TypeConverterException("Only supports converting to and from int or Integer"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
if(this.defaultValue != null && ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookParser.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverter.java // public interface TypeConverter { // void initialize(TypeConverterConfig config); // void validate(Class<?> type, int size, int decimals); // TypeConverter copy(Class<?> type) throws IllegalAccessException, InstantiationException; // Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding); // byte[] from(Object value, int length, int decimals, boolean addPadding); // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverterConfig.java // public class TypeConverterConfig { // private Charset charset; // private CopyBookFieldSigningType signingType; // private boolean rightPadding; // private char paddingChar; // private char nullFillerChar; // private String defaultValue; // private String format; // // public TypeConverterConfig() { // } // // public Charset getCharset() { // return charset; // } // // public void setCharset(Charset charset) { // this.charset = charset; // } // // public CopyBookFieldSigningType getSigningType() { // return signingType; // } // // public void setSigningType(CopyBookFieldSigningType signingType) { // this.signingType = signingType; // } // // public boolean isRightPadding() { // return rightPadding; // } // // public void setRightPadding(boolean rightPadding) { // this.rightPadding = rightPadding; // } // // public char getPaddingChar() { // return paddingChar; // } // // public void setPaddingChar(char paddingChar) { // this.paddingChar = paddingChar; // } // // public char getNullFillerChar() { // return nullFillerChar; // } // // public void setNullFillerChar(char nullFillerChar) { // this.nullFillerChar = nullFillerChar; // } // // public String getDefaultValue() { // return defaultValue; // } // // public void setDefaultValue(String defaultValue) { // this.defaultValue = defaultValue; // } // // public String getFormat() { // return format; // } // // public void setFormat(String format) { // this.format = format; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.annotations.*; import com.nordea.oss.copybook.converters.TypeConverter; import com.nordea.oss.copybook.converters.TypeConverterConfig; import com.nordea.oss.copybook.exceptions.CopyBookException; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.nio.charset.Charset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors;
private Class<? extends CopyBookMapper> serializerClass = null; private CopyBookSerializerConfig config = new CopyBookSerializerConfig(); public CopyBookParser(Class<?> type) { this(type, false); } public CopyBookParser(Class<?> type, boolean debug) { // Read copybook annotations and defaults List<CopyBook> copybookAnnotations = getAnnotationsRecursively(CopyBookDefaults.class, CopyBook.class); copybookAnnotations.addAll(getAnnotationsRecursively(type, CopyBook.class)); for(CopyBook annotation : copybookAnnotations) { if (!annotation.type().equals(CopyBookMapper.class)) { this.serializerClass = annotation.type(); } if (!annotation.charset().isEmpty()) { config.setCharset(Charset.forName(annotation.charset())); } if(annotation.separatorChar() != 'G') { // Java sucks and does not support null as default value for annotations so we pick large G as this is å in EBCDIC and unlikely to be used as separator char config.setSeparatorByte((byte)annotation.separatorChar()); } if(annotation.bitmapBlockSize() != 0) { config.setBitmapBlockSize(annotation.bitmapBlockSize()); } if(annotation.strict()) { config.setStrict(annotation.strict()); } } if(serializerClass == null) {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverter.java // public interface TypeConverter { // void initialize(TypeConverterConfig config); // void validate(Class<?> type, int size, int decimals); // TypeConverter copy(Class<?> type) throws IllegalAccessException, InstantiationException; // Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding); // byte[] from(Object value, int length, int decimals, boolean addPadding); // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverterConfig.java // public class TypeConverterConfig { // private Charset charset; // private CopyBookFieldSigningType signingType; // private boolean rightPadding; // private char paddingChar; // private char nullFillerChar; // private String defaultValue; // private String format; // // public TypeConverterConfig() { // } // // public Charset getCharset() { // return charset; // } // // public void setCharset(Charset charset) { // this.charset = charset; // } // // public CopyBookFieldSigningType getSigningType() { // return signingType; // } // // public void setSigningType(CopyBookFieldSigningType signingType) { // this.signingType = signingType; // } // // public boolean isRightPadding() { // return rightPadding; // } // // public void setRightPadding(boolean rightPadding) { // this.rightPadding = rightPadding; // } // // public char getPaddingChar() { // return paddingChar; // } // // public void setPaddingChar(char paddingChar) { // this.paddingChar = paddingChar; // } // // public char getNullFillerChar() { // return nullFillerChar; // } // // public void setNullFillerChar(char nullFillerChar) { // this.nullFillerChar = nullFillerChar; // } // // public String getDefaultValue() { // return defaultValue; // } // // public void setDefaultValue(String defaultValue) { // this.defaultValue = defaultValue; // } // // public String getFormat() { // return format; // } // // public void setFormat(String format) { // this.format = format; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookParser.java import com.nordea.oss.copybook.annotations.*; import com.nordea.oss.copybook.converters.TypeConverter; import com.nordea.oss.copybook.converters.TypeConverterConfig; import com.nordea.oss.copybook.exceptions.CopyBookException; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.nio.charset.Charset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; private Class<? extends CopyBookMapper> serializerClass = null; private CopyBookSerializerConfig config = new CopyBookSerializerConfig(); public CopyBookParser(Class<?> type) { this(type, false); } public CopyBookParser(Class<?> type, boolean debug) { // Read copybook annotations and defaults List<CopyBook> copybookAnnotations = getAnnotationsRecursively(CopyBookDefaults.class, CopyBook.class); copybookAnnotations.addAll(getAnnotationsRecursively(type, CopyBook.class)); for(CopyBook annotation : copybookAnnotations) { if (!annotation.type().equals(CopyBookMapper.class)) { this.serializerClass = annotation.type(); } if (!annotation.charset().isEmpty()) { config.setCharset(Charset.forName(annotation.charset())); } if(annotation.separatorChar() != 'G') { // Java sucks and does not support null as default value for annotations so we pick large G as this is å in EBCDIC and unlikely to be used as separator char config.setSeparatorByte((byte)annotation.separatorChar()); } if(annotation.bitmapBlockSize() != 0) { config.setBitmapBlockSize(annotation.bitmapBlockSize()); } if(annotation.strict()) { config.setStrict(annotation.strict()); } } if(serializerClass == null) {
throw new CopyBookException("Serialization class missing");
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookParser.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverter.java // public interface TypeConverter { // void initialize(TypeConverterConfig config); // void validate(Class<?> type, int size, int decimals); // TypeConverter copy(Class<?> type) throws IllegalAccessException, InstantiationException; // Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding); // byte[] from(Object value, int length, int decimals, boolean addPadding); // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverterConfig.java // public class TypeConverterConfig { // private Charset charset; // private CopyBookFieldSigningType signingType; // private boolean rightPadding; // private char paddingChar; // private char nullFillerChar; // private String defaultValue; // private String format; // // public TypeConverterConfig() { // } // // public Charset getCharset() { // return charset; // } // // public void setCharset(Charset charset) { // this.charset = charset; // } // // public CopyBookFieldSigningType getSigningType() { // return signingType; // } // // public void setSigningType(CopyBookFieldSigningType signingType) { // this.signingType = signingType; // } // // public boolean isRightPadding() { // return rightPadding; // } // // public void setRightPadding(boolean rightPadding) { // this.rightPadding = rightPadding; // } // // public char getPaddingChar() { // return paddingChar; // } // // public void setPaddingChar(char paddingChar) { // this.paddingChar = paddingChar; // } // // public char getNullFillerChar() { // return nullFillerChar; // } // // public void setNullFillerChar(char nullFillerChar) { // this.nullFillerChar = nullFillerChar; // } // // public String getDefaultValue() { // return defaultValue; // } // // public void setDefaultValue(String defaultValue) { // this.defaultValue = defaultValue; // } // // public String getFormat() { // return format; // } // // public void setFormat(String format) { // this.format = format; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.annotations.*; import com.nordea.oss.copybook.converters.TypeConverter; import com.nordea.oss.copybook.converters.TypeConverterConfig; import com.nordea.oss.copybook.exceptions.CopyBookException; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.nio.charset.Charset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors;
} public CopyBookParser(Class<?> type, boolean debug) { // Read copybook annotations and defaults List<CopyBook> copybookAnnotations = getAnnotationsRecursively(CopyBookDefaults.class, CopyBook.class); copybookAnnotations.addAll(getAnnotationsRecursively(type, CopyBook.class)); for(CopyBook annotation : copybookAnnotations) { if (!annotation.type().equals(CopyBookMapper.class)) { this.serializerClass = annotation.type(); } if (!annotation.charset().isEmpty()) { config.setCharset(Charset.forName(annotation.charset())); } if(annotation.separatorChar() != 'G') { // Java sucks and does not support null as default value for annotations so we pick large G as this is å in EBCDIC and unlikely to be used as separator char config.setSeparatorByte((byte)annotation.separatorChar()); } if(annotation.bitmapBlockSize() != 0) { config.setBitmapBlockSize(annotation.bitmapBlockSize()); } if(annotation.strict()) { config.setStrict(annotation.strict()); } } if(serializerClass == null) { throw new CopyBookException("Serialization class missing"); } config.setDebug(debug);
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverter.java // public interface TypeConverter { // void initialize(TypeConverterConfig config); // void validate(Class<?> type, int size, int decimals); // TypeConverter copy(Class<?> type) throws IllegalAccessException, InstantiationException; // Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding); // byte[] from(Object value, int length, int decimals, boolean addPadding); // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverterConfig.java // public class TypeConverterConfig { // private Charset charset; // private CopyBookFieldSigningType signingType; // private boolean rightPadding; // private char paddingChar; // private char nullFillerChar; // private String defaultValue; // private String format; // // public TypeConverterConfig() { // } // // public Charset getCharset() { // return charset; // } // // public void setCharset(Charset charset) { // this.charset = charset; // } // // public CopyBookFieldSigningType getSigningType() { // return signingType; // } // // public void setSigningType(CopyBookFieldSigningType signingType) { // this.signingType = signingType; // } // // public boolean isRightPadding() { // return rightPadding; // } // // public void setRightPadding(boolean rightPadding) { // this.rightPadding = rightPadding; // } // // public char getPaddingChar() { // return paddingChar; // } // // public void setPaddingChar(char paddingChar) { // this.paddingChar = paddingChar; // } // // public char getNullFillerChar() { // return nullFillerChar; // } // // public void setNullFillerChar(char nullFillerChar) { // this.nullFillerChar = nullFillerChar; // } // // public String getDefaultValue() { // return defaultValue; // } // // public void setDefaultValue(String defaultValue) { // this.defaultValue = defaultValue; // } // // public String getFormat() { // return format; // } // // public void setFormat(String format) { // this.format = format; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookParser.java import com.nordea.oss.copybook.annotations.*; import com.nordea.oss.copybook.converters.TypeConverter; import com.nordea.oss.copybook.converters.TypeConverterConfig; import com.nordea.oss.copybook.exceptions.CopyBookException; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.nio.charset.Charset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; } public CopyBookParser(Class<?> type, boolean debug) { // Read copybook annotations and defaults List<CopyBook> copybookAnnotations = getAnnotationsRecursively(CopyBookDefaults.class, CopyBook.class); copybookAnnotations.addAll(getAnnotationsRecursively(type, CopyBook.class)); for(CopyBook annotation : copybookAnnotations) { if (!annotation.type().equals(CopyBookMapper.class)) { this.serializerClass = annotation.type(); } if (!annotation.charset().isEmpty()) { config.setCharset(Charset.forName(annotation.charset())); } if(annotation.separatorChar() != 'G') { // Java sucks and does not support null as default value for annotations so we pick large G as this is å in EBCDIC and unlikely to be used as separator char config.setSeparatorByte((byte)annotation.separatorChar()); } if(annotation.bitmapBlockSize() != 0) { config.setBitmapBlockSize(annotation.bitmapBlockSize()); } if(annotation.strict()) { config.setStrict(annotation.strict()); } } if(serializerClass == null) { throw new CopyBookException("Serialization class missing"); } config.setDebug(debug);
Map<String,TypeConverter> defaultTypeConverterMap = getTypeConvertersRecursively(CopyBookDefaults.class, config.getCharset(), config.isStrict());
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookParser.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverter.java // public interface TypeConverter { // void initialize(TypeConverterConfig config); // void validate(Class<?> type, int size, int decimals); // TypeConverter copy(Class<?> type) throws IllegalAccessException, InstantiationException; // Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding); // byte[] from(Object value, int length, int decimals, boolean addPadding); // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverterConfig.java // public class TypeConverterConfig { // private Charset charset; // private CopyBookFieldSigningType signingType; // private boolean rightPadding; // private char paddingChar; // private char nullFillerChar; // private String defaultValue; // private String format; // // public TypeConverterConfig() { // } // // public Charset getCharset() { // return charset; // } // // public void setCharset(Charset charset) { // this.charset = charset; // } // // public CopyBookFieldSigningType getSigningType() { // return signingType; // } // // public void setSigningType(CopyBookFieldSigningType signingType) { // this.signingType = signingType; // } // // public boolean isRightPadding() { // return rightPadding; // } // // public void setRightPadding(boolean rightPadding) { // this.rightPadding = rightPadding; // } // // public char getPaddingChar() { // return paddingChar; // } // // public void setPaddingChar(char paddingChar) { // this.paddingChar = paddingChar; // } // // public char getNullFillerChar() { // return nullFillerChar; // } // // public void setNullFillerChar(char nullFillerChar) { // this.nullFillerChar = nullFillerChar; // } // // public String getDefaultValue() { // return defaultValue; // } // // public void setDefaultValue(String defaultValue) { // this.defaultValue = defaultValue; // } // // public String getFormat() { // return format; // } // // public void setFormat(String format) { // this.format = format; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.annotations.*; import com.nordea.oss.copybook.converters.TypeConverter; import com.nordea.oss.copybook.converters.TypeConverterConfig; import com.nordea.oss.copybook.exceptions.CopyBookException; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.nio.charset.Charset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors;
} // Try to see if we have a convert for any of the interfaces this type implements if (typeConverter == null) { for (Class<?> aInterface : fieldBaseType.getInterfaces()) { typeConverter = fieldTypeConverterMap.get(copyBookType + "To" + aInterface.getSimpleName()); if(typeConverter != null) { try { typeConverter = typeConverter.copy(type); } catch (IllegalAccessException | InstantiationException e) { throw new CopyBookException("Failed to copy type convert for this field '" + fieldName + "'", e); } } } } } else { if (field.getType().isArray()) { //TODO: Add ArrayTo example and test typeConverter = fieldTypeConverterMap.get("ArrayTo" + fieldTypeName + "Array"); } if (typeConverter == null) { typeConverter = fieldTypeConverterMap.get("To" + fieldTypeName); } } if(typeConverter != null) { try { typeConverter.validate(fieldBaseType, size, decimals);
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverter.java // public interface TypeConverter { // void initialize(TypeConverterConfig config); // void validate(Class<?> type, int size, int decimals); // TypeConverter copy(Class<?> type) throws IllegalAccessException, InstantiationException; // Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding); // byte[] from(Object value, int length, int decimals, boolean addPadding); // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverterConfig.java // public class TypeConverterConfig { // private Charset charset; // private CopyBookFieldSigningType signingType; // private boolean rightPadding; // private char paddingChar; // private char nullFillerChar; // private String defaultValue; // private String format; // // public TypeConverterConfig() { // } // // public Charset getCharset() { // return charset; // } // // public void setCharset(Charset charset) { // this.charset = charset; // } // // public CopyBookFieldSigningType getSigningType() { // return signingType; // } // // public void setSigningType(CopyBookFieldSigningType signingType) { // this.signingType = signingType; // } // // public boolean isRightPadding() { // return rightPadding; // } // // public void setRightPadding(boolean rightPadding) { // this.rightPadding = rightPadding; // } // // public char getPaddingChar() { // return paddingChar; // } // // public void setPaddingChar(char paddingChar) { // this.paddingChar = paddingChar; // } // // public char getNullFillerChar() { // return nullFillerChar; // } // // public void setNullFillerChar(char nullFillerChar) { // this.nullFillerChar = nullFillerChar; // } // // public String getDefaultValue() { // return defaultValue; // } // // public void setDefaultValue(String defaultValue) { // this.defaultValue = defaultValue; // } // // public String getFormat() { // return format; // } // // public void setFormat(String format) { // this.format = format; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookParser.java import com.nordea.oss.copybook.annotations.*; import com.nordea.oss.copybook.converters.TypeConverter; import com.nordea.oss.copybook.converters.TypeConverterConfig; import com.nordea.oss.copybook.exceptions.CopyBookException; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.nio.charset.Charset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; } // Try to see if we have a convert for any of the interfaces this type implements if (typeConverter == null) { for (Class<?> aInterface : fieldBaseType.getInterfaces()) { typeConverter = fieldTypeConverterMap.get(copyBookType + "To" + aInterface.getSimpleName()); if(typeConverter != null) { try { typeConverter = typeConverter.copy(type); } catch (IllegalAccessException | InstantiationException e) { throw new CopyBookException("Failed to copy type convert for this field '" + fieldName + "'", e); } } } } } else { if (field.getType().isArray()) { //TODO: Add ArrayTo example and test typeConverter = fieldTypeConverterMap.get("ArrayTo" + fieldTypeName + "Array"); } if (typeConverter == null) { typeConverter = fieldTypeConverterMap.get("To" + fieldTypeName); } } if(typeConverter != null) { try { typeConverter.validate(fieldBaseType, size, decimals);
} catch (TypeConverterException ex) {
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookParser.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverter.java // public interface TypeConverter { // void initialize(TypeConverterConfig config); // void validate(Class<?> type, int size, int decimals); // TypeConverter copy(Class<?> type) throws IllegalAccessException, InstantiationException; // Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding); // byte[] from(Object value, int length, int decimals, boolean addPadding); // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverterConfig.java // public class TypeConverterConfig { // private Charset charset; // private CopyBookFieldSigningType signingType; // private boolean rightPadding; // private char paddingChar; // private char nullFillerChar; // private String defaultValue; // private String format; // // public TypeConverterConfig() { // } // // public Charset getCharset() { // return charset; // } // // public void setCharset(Charset charset) { // this.charset = charset; // } // // public CopyBookFieldSigningType getSigningType() { // return signingType; // } // // public void setSigningType(CopyBookFieldSigningType signingType) { // this.signingType = signingType; // } // // public boolean isRightPadding() { // return rightPadding; // } // // public void setRightPadding(boolean rightPadding) { // this.rightPadding = rightPadding; // } // // public char getPaddingChar() { // return paddingChar; // } // // public void setPaddingChar(char paddingChar) { // this.paddingChar = paddingChar; // } // // public char getNullFillerChar() { // return nullFillerChar; // } // // public void setNullFillerChar(char nullFillerChar) { // this.nullFillerChar = nullFillerChar; // } // // public String getDefaultValue() { // return defaultValue; // } // // public void setDefaultValue(String defaultValue) { // this.defaultValue = defaultValue; // } // // public String getFormat() { // return format; // } // // public void setFormat(String format) { // this.format = format; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.annotations.*; import com.nordea.oss.copybook.converters.TypeConverter; import com.nordea.oss.copybook.converters.TypeConverterConfig; import com.nordea.oss.copybook.exceptions.CopyBookException; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.nio.charset.Charset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors;
if(annotationType.isInstance(annotation)) { results.add((T)annotation); } else if (annotation.annotationType().getAnnotation(annotationType) != null) { results.addAll(getAnnotationsRecursively(annotation.annotationType(), annotationType)); } } return results; } private Map<String, TypeConverter> getTypeConvertersRecursively(Class<?> type, Charset charset, Boolean strict) { Map<String,TypeConverter> results = new HashMap<>(); for (Annotation annotation : type.getAnnotations()) { if(CopyBookFieldFormats.class.isInstance(annotation)) { for(CopyBookFieldFormat fieldFormat : ((CopyBookFieldFormats)annotation).value()) { results.put(fieldFormat.type().getSimpleName(), createTypeConverter(fieldFormat, charset, strict)); } } else if(CopyBookFieldFormat.class.isInstance(annotation)) { CopyBookFieldFormat fieldFormat = (CopyBookFieldFormat)annotation; results.put(fieldFormat.type().getSimpleName(), createTypeConverter(fieldFormat, charset, strict)); } else if (annotation.annotationType().getAnnotation(CopyBookFieldFormat.class) != null) { results.putAll(getTypeConvertersRecursively(annotation.annotationType(), charset, strict)); } } return results; } private TypeConverter createTypeConverter(CopyBookFieldFormat copyBookFieldFormat, Charset charset, Boolean strict) {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverter.java // public interface TypeConverter { // void initialize(TypeConverterConfig config); // void validate(Class<?> type, int size, int decimals); // TypeConverter copy(Class<?> type) throws IllegalAccessException, InstantiationException; // Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding); // byte[] from(Object value, int length, int decimals, boolean addPadding); // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/TypeConverterConfig.java // public class TypeConverterConfig { // private Charset charset; // private CopyBookFieldSigningType signingType; // private boolean rightPadding; // private char paddingChar; // private char nullFillerChar; // private String defaultValue; // private String format; // // public TypeConverterConfig() { // } // // public Charset getCharset() { // return charset; // } // // public void setCharset(Charset charset) { // this.charset = charset; // } // // public CopyBookFieldSigningType getSigningType() { // return signingType; // } // // public void setSigningType(CopyBookFieldSigningType signingType) { // this.signingType = signingType; // } // // public boolean isRightPadding() { // return rightPadding; // } // // public void setRightPadding(boolean rightPadding) { // this.rightPadding = rightPadding; // } // // public char getPaddingChar() { // return paddingChar; // } // // public void setPaddingChar(char paddingChar) { // this.paddingChar = paddingChar; // } // // public char getNullFillerChar() { // return nullFillerChar; // } // // public void setNullFillerChar(char nullFillerChar) { // this.nullFillerChar = nullFillerChar; // } // // public String getDefaultValue() { // return defaultValue; // } // // public void setDefaultValue(String defaultValue) { // this.defaultValue = defaultValue; // } // // public String getFormat() { // return format; // } // // public void setFormat(String format) { // this.format = format; // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/CopyBookParser.java import com.nordea.oss.copybook.annotations.*; import com.nordea.oss.copybook.converters.TypeConverter; import com.nordea.oss.copybook.converters.TypeConverterConfig; import com.nordea.oss.copybook.exceptions.CopyBookException; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.nio.charset.Charset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; if(annotationType.isInstance(annotation)) { results.add((T)annotation); } else if (annotation.annotationType().getAnnotation(annotationType) != null) { results.addAll(getAnnotationsRecursively(annotation.annotationType(), annotationType)); } } return results; } private Map<String, TypeConverter> getTypeConvertersRecursively(Class<?> type, Charset charset, Boolean strict) { Map<String,TypeConverter> results = new HashMap<>(); for (Annotation annotation : type.getAnnotations()) { if(CopyBookFieldFormats.class.isInstance(annotation)) { for(CopyBookFieldFormat fieldFormat : ((CopyBookFieldFormats)annotation).value()) { results.put(fieldFormat.type().getSimpleName(), createTypeConverter(fieldFormat, charset, strict)); } } else if(CopyBookFieldFormat.class.isInstance(annotation)) { CopyBookFieldFormat fieldFormat = (CopyBookFieldFormat)annotation; results.put(fieldFormat.type().getSimpleName(), createTypeConverter(fieldFormat, charset, strict)); } else if (annotation.annotationType().getAnnotation(CopyBookFieldFormat.class) != null) { results.putAll(getTypeConvertersRecursively(annotation.annotationType(), charset, strict)); } } return results; } private TypeConverter createTypeConverter(CopyBookFieldFormat copyBookFieldFormat, Charset charset, Boolean strict) {
TypeConverterConfig config = new TypeConverterConfig();
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperFullOccursPicSingleLineTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // }
import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookLine; import java.math.BigDecimal; import static org.junit.Assert.assertArrayEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookMapperFullOccursPicSingleLineTest { @CopyBook(type = FullMapper.class) static public class StringFieldOccursTwoTimes { @CopyBookLine("01 FIELDS OCCURS 2 TIMES PIC X(4).") public String[] fields; } @CopyBook(type = FullMapper.class) static public class IntFieldOccursTwoTimes { @CopyBookLine("01 FIELDS OCCURS 2 TIMES PIC 9(4).") public int[] fields; } @CopyBook(type = FullMapper.class) static public class SignedIntFieldOccursTwoTimes { @CopyBookLine("01 FIELDS OCCURS 2 TIMES PIC S9(4).") public int[] fields; } @CopyBook(type = FullMapper.class) static public class DecimalFieldOccursTwoTimes { @CopyBookLine("01 FIELDS OCCURS 2 TIMES PIC 9(3)V9(2).") public BigDecimal[] fields; } @CopyBook(type = FullMapper.class) static public class SignedDecimalFieldOccursTwoTimes { @CopyBookLine("01 FIELDS OCCURS 2 TIMES PIC S9(3)V9(2).") public BigDecimal[] fields; } @org.junit.Test public void testStringFieldOccursTwoTimes() throws Exception {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperFullOccursPicSingleLineTest.java import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookLine; import java.math.BigDecimal; import static org.junit.Assert.assertArrayEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.serializers; public class CopyBookMapperFullOccursPicSingleLineTest { @CopyBook(type = FullMapper.class) static public class StringFieldOccursTwoTimes { @CopyBookLine("01 FIELDS OCCURS 2 TIMES PIC X(4).") public String[] fields; } @CopyBook(type = FullMapper.class) static public class IntFieldOccursTwoTimes { @CopyBookLine("01 FIELDS OCCURS 2 TIMES PIC 9(4).") public int[] fields; } @CopyBook(type = FullMapper.class) static public class SignedIntFieldOccursTwoTimes { @CopyBookLine("01 FIELDS OCCURS 2 TIMES PIC S9(4).") public int[] fields; } @CopyBook(type = FullMapper.class) static public class DecimalFieldOccursTwoTimes { @CopyBookLine("01 FIELDS OCCURS 2 TIMES PIC 9(3)V9(2).") public BigDecimal[] fields; } @CopyBook(type = FullMapper.class) static public class SignedDecimalFieldOccursTwoTimes { @CopyBookLine("01 FIELDS OCCURS 2 TIMES PIC S9(3)V9(2).") public BigDecimal[] fields; } @org.junit.Test public void testStringFieldOccursTwoTimes() throws Exception {
CopyBookSerializer serializer = new CopyBookSerializer(StringFieldOccursTwoTimes.class);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperFullTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // }
import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookLine; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
@CopyBookLine("02 TITLE PIC X(5).") public String title; @CopyBookLine("02 BODY PIC X(10).") public String body; public RequestMessage() { } public RequestMessage(String title, String body) { this.title = title; this.body = body; } } @Test public void testSerializeDeserialize() throws Exception { // Build test object RequestTest requestTest = new RequestTest(); requestTest.id = 1; requestTest.command = "cmd1234()"; requestTest.hello = new RequestMessage("Hello", "Body1234"); requestTest.hellos = new RequestMessage[] { new RequestMessage("abc", "1234ydob") }; requestTest.hellos_count = requestTest.hellos.length; requestTest.messages = new RequestMessage[] { new RequestMessage("msg1", "stuff123"), new RequestMessage("msg2", "stuff12345") }; requestTest.messages_count = requestTest.messages.length; requestTest.args = new String[]{ "do", "stuff" }; requestTest.args_count = requestTest.args.length; // Serializer and Deserializer object to and from bytes
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperFullTest.java import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookLine; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @CopyBookLine("02 TITLE PIC X(5).") public String title; @CopyBookLine("02 BODY PIC X(10).") public String body; public RequestMessage() { } public RequestMessage(String title, String body) { this.title = title; this.body = body; } } @Test public void testSerializeDeserialize() throws Exception { // Build test object RequestTest requestTest = new RequestTest(); requestTest.id = 1; requestTest.command = "cmd1234()"; requestTest.hello = new RequestMessage("Hello", "Body1234"); requestTest.hellos = new RequestMessage[] { new RequestMessage("abc", "1234ydob") }; requestTest.hellos_count = requestTest.hellos.length; requestTest.messages = new RequestMessage[] { new RequestMessage("msg1", "stuff123"), new RequestMessage("msg2", "stuff12345") }; requestTest.messages_count = requestTest.messages.length; requestTest.args = new String[]{ "do", "stuff" }; requestTest.args_count = requestTest.args.length; // Serializer and Deserializer object to and from bytes
CopyBookSerializer requestTestSerializer = new CopyBookSerializer(RequestTest.class);
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/IntegerToBoolean.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToBoolean extends IntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!(Boolean.class.equals(type) || Boolean.TYPE.equals(type))) {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/IntegerToBoolean.java import com.nordea.oss.copybook.exceptions.TypeConverterException; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToBoolean extends IntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!(Boolean.class.equals(type) || Boolean.TYPE.equals(type))) {
throw new TypeConverterException("Only supports converting to and from int or Integer");
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/IntegerToIntegerTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToIntegerTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); typeConverter = new IntegerToInteger(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Integer.TYPE, 2, -1); }
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/IntegerToIntegerTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToIntegerTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); typeConverter = new IntegerToInteger(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Integer.TYPE, 2, -1); }
@Test(expected = TypeConverterException.class)
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/IntegerToBigInteger.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.math.BigInteger; import java.util.Arrays;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToBigInteger extends IntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!BigInteger.class.equals(type)) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/IntegerToBigInteger.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.math.BigInteger; import java.util.Arrays; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToBigInteger extends IntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!BigInteger.class.equals(type)) {
throw new TypeConverterException("Only supports converting to and from BigInteger");
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/IntegerToBigInteger.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.math.BigInteger; import java.util.Arrays;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToBigInteger extends IntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!BigInteger.class.equals(type)) { throw new TypeConverterException("Only supports converting to and from BigInteger"); } } @Override public BigInteger to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/IntegerToBigInteger.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.math.BigInteger; import java.util.Arrays; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToBigInteger extends IntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!BigInteger.class.equals(type)) { throw new TypeConverterException("Only supports converting to and from BigInteger"); } } @Override public BigInteger to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
if(this.defaultValue != null && ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/serializers/PackedFirstLevelMapper.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.CopyBookException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.List;
writeField(buffer, field, field.getObject(rootObj), last); } } } private void writeField(PackedBuffer buffer, CopyBookField field, Object valueObj, boolean last) { if(field.getLevel() == 0) { buffer.put(field.getBytes(null, valueObj, false), true); // No padding with separator } else if(last) { byte[] valueBytes = field.getBytes(null, valueObj, false); // Don't pad if it's the last field if(valueBytes == null) { valueBytes = field.getBytes(null, valueObj, true); // Except if it's null } buffer.put(valueBytes, true); // With separator } else { buffer.put(field.getBytes(null, valueObj, true), false); // With padding without separator } } @Override public <T> T deserialize(byte[] bytes, Class<T> type) { try { T obj = type.newInstance(); PackedBuffer buffer = new PackedBuffer(bytes, this.maxBitmapSize, this.bitmapBlockSize, this.separatorByte); readFields(this.fields, buffer, obj, true); return obj; } catch (IllegalAccessException | InstantiationException e) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/PackedFirstLevelMapper.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.CopyBookException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.List; writeField(buffer, field, field.getObject(rootObj), last); } } } private void writeField(PackedBuffer buffer, CopyBookField field, Object valueObj, boolean last) { if(field.getLevel() == 0) { buffer.put(field.getBytes(null, valueObj, false), true); // No padding with separator } else if(last) { byte[] valueBytes = field.getBytes(null, valueObj, false); // Don't pad if it's the last field if(valueBytes == null) { valueBytes = field.getBytes(null, valueObj, true); // Except if it's null } buffer.put(valueBytes, true); // With separator } else { buffer.put(field.getBytes(null, valueObj, true), false); // With padding without separator } } @Override public <T> T deserialize(byte[] bytes, Class<T> type) { try { T obj = type.newInstance(); PackedBuffer buffer = new PackedBuffer(bytes, this.maxBitmapSize, this.bitmapBlockSize, this.separatorByte); readFields(this.fields, buffer, obj, true); return obj; } catch (IllegalAccessException | InstantiationException e) {
throw new CopyBookException("Failed to create new object", e);
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/serializers/PackedFirstLevelMapper.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.CopyBookException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.List;
/* TODO: Calculate the number of set bits with bit masking and Long.numberOfTrailingZeros as this should be quicker String befor = debugBitmap(this.bitmapBytes, 0, 8); ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.put(this.bitmapBytes); buffer.flip();//need flip long stuff = buffer.getLong(); long mask = (Long.MAX_VALUE >> bitmapIndex - 1) & (Long.MAX_VALUE << (bitmapSize * 8 - bitmapIndex - maxOccurs)); long num2 = stuff & mask; long size2 = num2 > 0 ? 8 * 8 - Long.numberOfTrailingZeros(num2) - bitmapIndex : 0; long num3 = (stuff >> (8*8 - (bitmapIndex + maxOccurs))) & (Long.MAX_VALUE >> (8*8 - (bitmapIndex + maxOccurs))); long size3 = maxOccurs - Long.numberOfTrailingZeros(num3); ByteBuffer buffer2 = ByteBuffer.allocate(Long.BYTES); buffer2.putLong(num3); byte[] testbytes = buffer2.array(); String after = debugBitmap(testbytes, 0, 8); */ return size; } public byte[] get(int maxLength, boolean separator) { byte[] byteValue = null; if (getBitInBitmap(this.bitmapBytes, this.bitmapIndex, this.bitmapSize)) { if (separator) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/serializers/PackedFirstLevelMapper.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.CopyBookException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.List; /* TODO: Calculate the number of set bits with bit masking and Long.numberOfTrailingZeros as this should be quicker String befor = debugBitmap(this.bitmapBytes, 0, 8); ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.put(this.bitmapBytes); buffer.flip();//need flip long stuff = buffer.getLong(); long mask = (Long.MAX_VALUE >> bitmapIndex - 1) & (Long.MAX_VALUE << (bitmapSize * 8 - bitmapIndex - maxOccurs)); long num2 = stuff & mask; long size2 = num2 > 0 ? 8 * 8 - Long.numberOfTrailingZeros(num2) - bitmapIndex : 0; long num3 = (stuff >> (8*8 - (bitmapIndex + maxOccurs))) & (Long.MAX_VALUE >> (8*8 - (bitmapIndex + maxOccurs))); long size3 = maxOccurs - Long.numberOfTrailingZeros(num3); ByteBuffer buffer2 = ByteBuffer.allocate(Long.BYTES); buffer2.putLong(num3); byte[] testbytes = buffer2.array(); String after = debugBitmap(testbytes, 0, 8); */ return size; } public byte[] get(int maxLength, boolean separator) { byte[] byteValue = null; if (getBitInBitmap(this.bitmapBytes, this.bitmapIndex, this.bitmapSize)) { if (separator) {
int index = ByteUtils.indexOf(this.buffer.array(), this.separatorByte, this.buffer.position() + 1, maxLength);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperPackedFirstLevelTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // }
import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.exceptions.CopyBookException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.junit.Assert.assertEquals;
@CopyBookLine("02 TITLE PIC X(5).") public String title; @CopyBookLine("02 BODY PIC X(10).") public String body; public RequestMessage() { } public RequestMessage(String title, String body) { this.title = title; this.body = body; } } @Test public void testSerializeDeserialize() throws Exception { // Build test object RequestTest requestTest = new RequestTest(); requestTest.id = 1; requestTest.command = "cmd1234"; requestTest.hello = new RequestMessage("Helo", "Body1234"); requestTest.hellos = new RequestMessage[] { new RequestMessage("abc", "1234ydob") }; requestTest.hellos_count = requestTest.hellos.length; requestTest.args = new String[]{ "do", "stuff" }; requestTest.args_count = requestTest.args.length; requestTest.messages = new RequestMessage[] { new RequestMessage("msg1", "stuff123"), new RequestMessage("msg2", "stuff1234") }; requestTest.messages_count = requestTest.messages.length; // Serializer and Deserializer object to and from bytes
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperPackedFirstLevelTest.java import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.exceptions.CopyBookException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.junit.Assert.assertEquals; @CopyBookLine("02 TITLE PIC X(5).") public String title; @CopyBookLine("02 BODY PIC X(10).") public String body; public RequestMessage() { } public RequestMessage(String title, String body) { this.title = title; this.body = body; } } @Test public void testSerializeDeserialize() throws Exception { // Build test object RequestTest requestTest = new RequestTest(); requestTest.id = 1; requestTest.command = "cmd1234"; requestTest.hello = new RequestMessage("Helo", "Body1234"); requestTest.hellos = new RequestMessage[] { new RequestMessage("abc", "1234ydob") }; requestTest.hellos_count = requestTest.hellos.length; requestTest.args = new String[]{ "do", "stuff" }; requestTest.args_count = requestTest.args.length; requestTest.messages = new RequestMessage[] { new RequestMessage("msg1", "stuff123"), new RequestMessage("msg2", "stuff1234") }; requestTest.messages_count = requestTest.messages.length; // Serializer and Deserializer object to and from bytes
CopyBookSerializer requestTestSerializer = new CopyBookSerializer(RequestTest.class);
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperPackedFirstLevelTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // }
import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.exceptions.CopyBookException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.junit.Assert.assertEquals;
RequestTest requestTest = new RequestTest(); requestTest.hellos = new RequestMessage[] { null }; requestTest.hellos_count = requestTest.hellos.length; // Serializer and Deserializer object to and from bytes CopyBookSerializer requestTestSerializer = new CopyBookSerializer(RequestTest.class); byte[] bytes = requestTestSerializer.serialize(requestTest); RequestTest requestTest1 = requestTestSerializer.deserialize(bytes, RequestTest.class); assertEquals(0, requestTest1.args.length); } @Test public void testSerializeDeserializeEmptyList() throws Exception { // Build test object RequestTest requestTest = new RequestTest(); requestTest.messages = new RequestMessage[] {}; requestTest.args = new String[]{}; // Serializer and Deserializer object to and from bytes CopyBookSerializer requestTestSerializer = new CopyBookSerializer(RequestTest.class); byte[] bytes = requestTestSerializer.serialize(requestTest); RequestTest requestTest1 = requestTestSerializer.deserialize(bytes, RequestTest.class); assertEquals(0, requestTest1.args.length); assertEquals(0, requestTest1.messages.length); } @org.junit.Test public void testSerializeDeserializeSeparatorByteException() throws Exception {
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/CopyBookSerializer.java // public class CopyBookSerializer { // private CopyBookMapper serializer; // // public CopyBookSerializer(Class<?> type) { // this(type, false); // } // // public CopyBookSerializer(Class<?> type, boolean debug) { // this(type, null, debug); // } // // public CopyBookSerializer(Class<?> type, Class<CopyBookMapper> mapper, boolean debug) { // CopyBookParser parser = new CopyBookParser(type, debug); // try { // if(mapper != null) { // serializer = mapper.getDeclaredConstructor().newInstance(); // // } else { // serializer = parser.getSerializerClass().getDeclaredConstructor().newInstance(); // } // serializer.initialize(parser.getConfig()); // // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // throw new CopyBookException("Failed to load Serialization class("+ parser.getSerializerClass().getSimpleName() +")", e); // } // } // // public <T> byte[] serialize(T obj) { // return serializer.serialize(obj); // } // // public <T> T deserialize(byte[] bytes, Class<T> type) { // return serializer.deserialize(bytes, type); // } // // public <T> T deserialize(InputStream inputStream, Class<T> type) throws IOException { // return deserialize(ByteUtils.toByteArray(inputStream), type); // } // // public List<CopyBookException> getErrors() { // return null; // TODO: Implement depending on errorValue // } // // public int getMinRecordSize() { // return serializer.getMinRecordSize(); // } // // public int getMaxRecordSize() { // return serializer.getMaxRecordSize(); // } // // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/CopyBookException.java // public class CopyBookException extends RuntimeException { // private static final long serialVersionUID = 28118369047109260L; // public CopyBookException(String message) { // super(message); // } // // public CopyBookException(String message, TypeConverterException ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // // public CopyBookException(String message, Exception ex) { // super(message + ": " + ex.getClass().getSimpleName() + " :" + ex.getMessage()); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/serializers/CopyBookMapperPackedFirstLevelTest.java import com.nordea.oss.copybook.CopyBookSerializer; import com.nordea.oss.copybook.annotations.CopyBook; import com.nordea.oss.copybook.annotations.CopyBookLine; import com.nordea.oss.copybook.exceptions.CopyBookException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.junit.Assert.assertEquals; RequestTest requestTest = new RequestTest(); requestTest.hellos = new RequestMessage[] { null }; requestTest.hellos_count = requestTest.hellos.length; // Serializer and Deserializer object to and from bytes CopyBookSerializer requestTestSerializer = new CopyBookSerializer(RequestTest.class); byte[] bytes = requestTestSerializer.serialize(requestTest); RequestTest requestTest1 = requestTestSerializer.deserialize(bytes, RequestTest.class); assertEquals(0, requestTest1.args.length); } @Test public void testSerializeDeserializeEmptyList() throws Exception { // Build test object RequestTest requestTest = new RequestTest(); requestTest.messages = new RequestMessage[] {}; requestTest.args = new String[]{}; // Serializer and Deserializer object to and from bytes CopyBookSerializer requestTestSerializer = new CopyBookSerializer(RequestTest.class); byte[] bytes = requestTestSerializer.serialize(requestTest); RequestTest requestTest1 = requestTestSerializer.deserialize(bytes, RequestTest.class); assertEquals(0, requestTest1.args.length); assertEquals(0, requestTest1.messages.length); } @org.junit.Test public void testSerializeDeserializeSeparatorByteException() throws Exception {
expectedEx.expect(CopyBookException.class);
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToString.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.util.Arrays;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToString extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimals) { if(!(String.class.equals(type))) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToString.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.util.Arrays; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToString extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimals) { if(!(String.class.equals(type))) {
throw new TypeConverterException("Only supports converting to and from String");
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToString.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.util.Arrays;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToString extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimals) { if(!(String.class.equals(type))) { throw new TypeConverterException("Only supports converting to and from String"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/StringToString.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; import java.util.Arrays; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToString extends TypeConverterBase { @Override public void validate(Class<?> type, int size, int decimals) { if(!(String.class.equals(type))) { throw new TypeConverterException("Only supports converting to and from String"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
if(ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/IntegerToLong.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToLong extends IntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(size > 21) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/IntegerToLong.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToLong extends IntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(size > 21) {
throw new TypeConverterException("Long is not large enough to hold possible value");
NordeaOSS/copybook4java
copybook4java/src/main/java/com/nordea/oss/copybook/converters/IntegerToLong.java
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToLong extends IntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(size > 21) { throw new TypeConverterException("Long is not large enough to hold possible value"); } if(!(Long.class.equals(type) || Long.TYPE.equals(type))) { throw new TypeConverterException("Only supports converting to and from long or Long"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
// Path: copybook4java/src/main/java/com/nordea/oss/ByteUtils.java // public class ByteUtils { // // public static boolean allEquals(byte[] array, byte value, int offset, int maxLength) { // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] != value) { // return false; // } // } // return true; // } // // public static int indexOf(byte[] array, byte needle, int offset, int maxLength) { // int result = -1; // maxLength = Math.min(offset + maxLength, array.length); // for(int i = offset; i < maxLength; i++) { // if(array[i] == needle) { // result = i; // break; // } // } // return result; // } // // public static byte[] trim(byte[] src, byte padding, boolean right, int minLength) { // if(src.length < minLength) { // throw new RuntimeException("src array is smaller than minLength: " + src.length + " < " + minLength); // } // if(right) { // int offset; // for (offset = src.length - 1; offset > minLength - 1; offset--) { // [44, 32] // if(padding != src[offset]) { // break; // } // } // if(offset < 0) { // return new byte[0]; // } else if (offset < src.length - 1){ // return Arrays.copyOfRange(src, 0, offset + 1); // } // // } else { // int offset; // for (offset = 0; offset < src.length - minLength; offset++) { // if(padding != src[offset]) { // break; // } // } // if(offset == src.length) { // return new byte[0]; // } else if(offset > 0) { // return Arrays.copyOfRange(src, offset, src.length); // } // } // // return src; // } // // public static byte[] toByteArray(InputStream inputStream) throws IOException { // ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // // byte[] buf = new byte[8192]; // while(true) { // int r = inputStream.read(buf); // if(r == -1) { // break; // } // outputStream.write(buf, 0, r); // } // // return outputStream.toByteArray(); // } // } // // Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/main/java/com/nordea/oss/copybook/converters/IntegerToLong.java import com.nordea.oss.ByteUtils; import com.nordea.oss.copybook.exceptions.TypeConverterException; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class IntegerToLong extends IntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(size > 21) { throw new TypeConverterException("Long is not large enough to hold possible value"); } if(!(Long.class.equals(type) || Long.TYPE.equals(type))) { throw new TypeConverterException("Only supports converting to and from long or Long"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) {
if(this.defaultValue != null && ByteUtils.allEquals(bytes, this.nullFillerByte, offset, bytes.length)) { // All of value is null filler
NordeaOSS/copybook4java
copybook4java/src/test/java/com/nordea/oss/copybook/converters/StringToBooleanTest.java
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // }
import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToBooleanTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); this.config.setFormat("Y|N"); typeConverter = new StringToBoolean(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Boolean.TYPE, 2, -1); }
// Path: copybook4java/src/main/java/com/nordea/oss/copybook/exceptions/TypeConverterException.java // public class TypeConverterException extends RuntimeException { // private static final long serialVersionUID = -7577535992947276304L; // public TypeConverterException(String message) { // super(message); // } // } // Path: copybook4java/src/test/java/com/nordea/oss/copybook/converters/StringToBooleanTest.java import com.nordea.oss.copybook.exceptions.TypeConverterException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.nio.charset.StandardCharsets; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Copyright (c) 2016. Nordea Bank AB * Licensed under the MIT license (LICENSE.txt) */ package com.nordea.oss.copybook.converters; public class StringToBooleanTest { private TypeConverter typeConverter; private TypeConverterConfig config; @Rule public ExpectedException expectedEx = ExpectedException.none(); @Before public void runBeforeEveryTest() { this.config = new TypeConverterConfig(); this.config.setCharset(StandardCharsets.UTF_8); this.config.setPaddingChar('0'); this.config.setFormat("Y|N"); typeConverter = new StringToBoolean(); typeConverter.initialize(config); } @Test public void testValidateSuccess() throws Exception { typeConverter.validate(Boolean.TYPE, 2, -1); }
@Test(expected = TypeConverterException.class)
mjuhasz/BDSup2Sub
src/main/java/bdsup2sub/gui/palette/DvdPaletteDialogView.java
// Path: src/main/java/bdsup2sub/gui/support/RequestFocusListener.java // public class RequestFocusListener implements AncestorListener // { // private boolean removeListener; // // /* // * Convenience constructor. The listener is only used once and then it is // * removed from the component. // */ // public RequestFocusListener() { // this(true); // } // // /* // * Constructor that controls whether this listen can be used once or // * multiple times. // * // * @param removeListener when true this listener is only invoked once // * otherwise it can be invoked multiple times. // */ // public RequestFocusListener(boolean removeListener) { // this.removeListener = removeListener; // } // // @Override // public void ancestorAdded(AncestorEvent e) { // JComponent component = e.getComponent(); // component.requestFocusInWindow(); // if (removeListener) { // component.removeAncestorListener(this); // } // } // // @Override // public void ancestorMoved(AncestorEvent e) { // } // // @Override // public void ancestorRemoved(AncestorEvent e) { // } // } // // Path: src/main/java/bdsup2sub/gui/support/GuiUtils.java // public static void centerRelativeToOwner(Window window) { // Window owner = window.getOwner(); // Point p = owner.getLocation(); // window.setLocation(p.x + owner.getWidth() / 2 - window.getWidth() / 2, p.y + owner.getHeight() / 2 - window.getHeight() / 2); // }
import bdsup2sub.gui.support.RequestFocusListener; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import static bdsup2sub.gui.support.GuiUtils.centerRelativeToOwner;
/* * Copyright 2014 Miklos Juhasz (mjuhasz) * * 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 bdsup2sub.gui.palette; class DvdPaletteDialogView extends JDialog { private JPanel jContentPane; private JScrollPane jScrollPane; private JList jListColor; private JButton jButtonOk; private JButton jButtonCancel; private JButton jButtonDefault; private JButton jButtonColor; private JButton jButtonSave; private JButton jButtonLoad; private final DvdPaletteDialogModel model; public DvdPaletteDialogView(DvdPaletteDialogModel model, Frame frame) { super(frame, "Choose Colors", true); this.model = model; initialize(); } private void initialize() { setContentPane(getJContentPane()); setSize(372, 231); setResizable(false);
// Path: src/main/java/bdsup2sub/gui/support/RequestFocusListener.java // public class RequestFocusListener implements AncestorListener // { // private boolean removeListener; // // /* // * Convenience constructor. The listener is only used once and then it is // * removed from the component. // */ // public RequestFocusListener() { // this(true); // } // // /* // * Constructor that controls whether this listen can be used once or // * multiple times. // * // * @param removeListener when true this listener is only invoked once // * otherwise it can be invoked multiple times. // */ // public RequestFocusListener(boolean removeListener) { // this.removeListener = removeListener; // } // // @Override // public void ancestorAdded(AncestorEvent e) { // JComponent component = e.getComponent(); // component.requestFocusInWindow(); // if (removeListener) { // component.removeAncestorListener(this); // } // } // // @Override // public void ancestorMoved(AncestorEvent e) { // } // // @Override // public void ancestorRemoved(AncestorEvent e) { // } // } // // Path: src/main/java/bdsup2sub/gui/support/GuiUtils.java // public static void centerRelativeToOwner(Window window) { // Window owner = window.getOwner(); // Point p = owner.getLocation(); // window.setLocation(p.x + owner.getWidth() / 2 - window.getWidth() / 2, p.y + owner.getHeight() / 2 - window.getHeight() / 2); // } // Path: src/main/java/bdsup2sub/gui/palette/DvdPaletteDialogView.java import bdsup2sub.gui.support.RequestFocusListener; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import static bdsup2sub.gui.support.GuiUtils.centerRelativeToOwner; /* * Copyright 2014 Miklos Juhasz (mjuhasz) * * 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 bdsup2sub.gui.palette; class DvdPaletteDialogView extends JDialog { private JPanel jContentPane; private JScrollPane jScrollPane; private JList jListColor; private JButton jButtonOk; private JButton jButtonCancel; private JButton jButtonDefault; private JButton jButtonColor; private JButton jButtonSave; private JButton jButtonLoad; private final DvdPaletteDialogModel model; public DvdPaletteDialogView(DvdPaletteDialogModel model, Frame frame) { super(frame, "Choose Colors", true); this.model = model; initialize(); } private void initialize() { setContentPane(getJContentPane()); setSize(372, 231); setResizable(false);
centerRelativeToOwner(this);
mjuhasz/BDSup2Sub
src/main/java/bdsup2sub/gui/palette/DvdPaletteDialogView.java
// Path: src/main/java/bdsup2sub/gui/support/RequestFocusListener.java // public class RequestFocusListener implements AncestorListener // { // private boolean removeListener; // // /* // * Convenience constructor. The listener is only used once and then it is // * removed from the component. // */ // public RequestFocusListener() { // this(true); // } // // /* // * Constructor that controls whether this listen can be used once or // * multiple times. // * // * @param removeListener when true this listener is only invoked once // * otherwise it can be invoked multiple times. // */ // public RequestFocusListener(boolean removeListener) { // this.removeListener = removeListener; // } // // @Override // public void ancestorAdded(AncestorEvent e) { // JComponent component = e.getComponent(); // component.requestFocusInWindow(); // if (removeListener) { // component.removeAncestorListener(this); // } // } // // @Override // public void ancestorMoved(AncestorEvent e) { // } // // @Override // public void ancestorRemoved(AncestorEvent e) { // } // } // // Path: src/main/java/bdsup2sub/gui/support/GuiUtils.java // public static void centerRelativeToOwner(Window window) { // Window owner = window.getOwner(); // Point p = owner.getLocation(); // window.setLocation(p.x + owner.getWidth() / 2 - window.getWidth() / 2, p.y + owner.getHeight() / 2 - window.getHeight() / 2); // }
import bdsup2sub.gui.support.RequestFocusListener; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import static bdsup2sub.gui.support.GuiUtils.centerRelativeToOwner;
centerRelativeToOwner(this); } private JPanel getJContentPane() { if(jContentPane == null) { JLabel lblColor = new JLabel(); jContentPane = new JPanel(); jContentPane.setLayout(null); lblColor.setText("Choose Color"); lblColor.setBounds(15, 9, 80, 16); jContentPane.add(lblColor, null); jContentPane.add(getJButtonOk(), null); jContentPane.add(getJButtonCancel(), null); jContentPane.add(getJButtonDefault(), null); jContentPane.add(getJButtonColor(), null); jContentPane.add(getJButtonSave(), null); jContentPane.add(getJButtonLoad(), null); jContentPane.add(getJScrollPane(), null); initColorList(); } return jContentPane; } private JButton getJButtonOk() { if (jButtonOk == null) { jButtonOk = new JButton(); jButtonOk.setBounds(280, 162, 66, 20); jButtonOk.setText("OK"); jButtonOk.setToolTipText("Apply changes and return"); jButtonOk.setMnemonic('o');
// Path: src/main/java/bdsup2sub/gui/support/RequestFocusListener.java // public class RequestFocusListener implements AncestorListener // { // private boolean removeListener; // // /* // * Convenience constructor. The listener is only used once and then it is // * removed from the component. // */ // public RequestFocusListener() { // this(true); // } // // /* // * Constructor that controls whether this listen can be used once or // * multiple times. // * // * @param removeListener when true this listener is only invoked once // * otherwise it can be invoked multiple times. // */ // public RequestFocusListener(boolean removeListener) { // this.removeListener = removeListener; // } // // @Override // public void ancestorAdded(AncestorEvent e) { // JComponent component = e.getComponent(); // component.requestFocusInWindow(); // if (removeListener) { // component.removeAncestorListener(this); // } // } // // @Override // public void ancestorMoved(AncestorEvent e) { // } // // @Override // public void ancestorRemoved(AncestorEvent e) { // } // } // // Path: src/main/java/bdsup2sub/gui/support/GuiUtils.java // public static void centerRelativeToOwner(Window window) { // Window owner = window.getOwner(); // Point p = owner.getLocation(); // window.setLocation(p.x + owner.getWidth() / 2 - window.getWidth() / 2, p.y + owner.getHeight() / 2 - window.getHeight() / 2); // } // Path: src/main/java/bdsup2sub/gui/palette/DvdPaletteDialogView.java import bdsup2sub.gui.support.RequestFocusListener; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import static bdsup2sub.gui.support.GuiUtils.centerRelativeToOwner; centerRelativeToOwner(this); } private JPanel getJContentPane() { if(jContentPane == null) { JLabel lblColor = new JLabel(); jContentPane = new JPanel(); jContentPane.setLayout(null); lblColor.setText("Choose Color"); lblColor.setBounds(15, 9, 80, 16); jContentPane.add(lblColor, null); jContentPane.add(getJButtonOk(), null); jContentPane.add(getJButtonCancel(), null); jContentPane.add(getJButtonDefault(), null); jContentPane.add(getJButtonColor(), null); jContentPane.add(getJButtonSave(), null); jContentPane.add(getJButtonLoad(), null); jContentPane.add(getJScrollPane(), null); initColorList(); } return jContentPane; } private JButton getJButtonOk() { if (jButtonOk == null) { jButtonOk = new JButton(); jButtonOk.setBounds(280, 162, 66, 20); jButtonOk.setText("OK"); jButtonOk.setToolTipText("Apply changes and return"); jButtonOk.setMnemonic('o');
jButtonOk.addAncestorListener(new RequestFocusListener());
mjuhasz/BDSup2Sub
src/main/java/bdsup2sub/bitmap/Palette.java
// Path: src/main/java/bdsup2sub/bitmap/ColorSpaceUtils.java // public static int[] RGB2YCbCr(int r, int g, int b, boolean useBT601) { // int[] yCbCr = new int[3]; // double y,cb,cr; // // if (useBT601) { // /* BT.601 for RGB 0..255 (PC) -> YCbCr 16..235 */ // y = r * 0.299 * 219 / 255 + g * 0.587 * 219 / 255 + b * 0.114 * 219 / 255; // cb = -r * 0.168736 * 224 / 255 - g * 0.331264 * 224 / 255 + b * 0.5 * 224 / 255; // cr = r * 0.5 * 224 / 255 - g * 0.418688 * 224 / 255 - b * 0.081312 * 224 / 255; // } else { // /* BT.709 for RGB 0..255 (PC) -> YCbCr 16..235 */ // y = r * 0.2126 * 219 / 255 + g * 0.7152 * 219 / 255 + b * 0.0722 * 219 / 255; // cb = -r * 0.2126 / 1.8556 * 224 / 255 - g * 0.7152 / 1.8556 * 224 / 255 + b * 0.5 * 224 / 255; // cr = r * 0.5 * 224 / 255 - g * 0.7152 / 1.5748 * 224 / 255 - b * 0.0722 / 1.5748 * 224 / 255; // } // yCbCr[0] = 16 + (int)(y + 0.5); // yCbCr[1] = 128 + (int)(cb + 0.5); // yCbCr[2] = 128 + (int)(cr + 0.5); // for (int i = 0; i < 3; i++) { // if (yCbCr[i] < 16) { // yCbCr[i] = 16; // } else { // if (i == 0) { // if (yCbCr[i] > 235) // yCbCr[i] = 235; // } else { // if (yCbCr[i] > 240) // yCbCr[i] = 240; // } // } // } // return yCbCr; // }
import java.awt.*; import java.awt.image.ColorModel; import java.awt.image.IndexColorModel; import java.util.Arrays; import static bdsup2sub.bitmap.ColorSpaceUtils.RGB2YCbCr;
/* * Copyright 2014 Volker Oth (0xdeadbeef) / Miklos Juhasz (mjuhasz) * * 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 bdsup2sub.bitmap; /** * Palette class for mixed representation of RGB/YCbCr palettes with alpha information. */ public class Palette { /** Number of palette entries */ private final int size; /** Byte buffer for RED info */ private final byte[] r; /** Byte buffer for GREEN info */ private final byte[] g; /** Byte buffer for BLUE info */ private final byte[] b; /** Byte buffer for alpha info */ private final byte[] a; /** Byte buffer for Y (luminance) info */ private final byte[] y; /** Byte buffer for Cb (chrominance blue) info */ private final byte[] cb; /** Byte buffer for Cr (chrominance red) info */ private final byte[] cr; /** Use BT.601 color model instead of BT.709 */ private final boolean useBT601; /** * Initializes palette with transparent black (RGBA: 0x00000000) * @param size Number of palette entries */ public Palette(int size, boolean useBT601) { this.size = size; this.useBT601 = useBT601; r = new byte[size]; g = new byte[size]; b = new byte[size]; a = new byte[size]; y = new byte[size]; cb = new byte[size]; cr = new byte[size]; // set at least all alpha values to invisible
// Path: src/main/java/bdsup2sub/bitmap/ColorSpaceUtils.java // public static int[] RGB2YCbCr(int r, int g, int b, boolean useBT601) { // int[] yCbCr = new int[3]; // double y,cb,cr; // // if (useBT601) { // /* BT.601 for RGB 0..255 (PC) -> YCbCr 16..235 */ // y = r * 0.299 * 219 / 255 + g * 0.587 * 219 / 255 + b * 0.114 * 219 / 255; // cb = -r * 0.168736 * 224 / 255 - g * 0.331264 * 224 / 255 + b * 0.5 * 224 / 255; // cr = r * 0.5 * 224 / 255 - g * 0.418688 * 224 / 255 - b * 0.081312 * 224 / 255; // } else { // /* BT.709 for RGB 0..255 (PC) -> YCbCr 16..235 */ // y = r * 0.2126 * 219 / 255 + g * 0.7152 * 219 / 255 + b * 0.0722 * 219 / 255; // cb = -r * 0.2126 / 1.8556 * 224 / 255 - g * 0.7152 / 1.8556 * 224 / 255 + b * 0.5 * 224 / 255; // cr = r * 0.5 * 224 / 255 - g * 0.7152 / 1.5748 * 224 / 255 - b * 0.0722 / 1.5748 * 224 / 255; // } // yCbCr[0] = 16 + (int)(y + 0.5); // yCbCr[1] = 128 + (int)(cb + 0.5); // yCbCr[2] = 128 + (int)(cr + 0.5); // for (int i = 0; i < 3; i++) { // if (yCbCr[i] < 16) { // yCbCr[i] = 16; // } else { // if (i == 0) { // if (yCbCr[i] > 235) // yCbCr[i] = 235; // } else { // if (yCbCr[i] > 240) // yCbCr[i] = 240; // } // } // } // return yCbCr; // } // Path: src/main/java/bdsup2sub/bitmap/Palette.java import java.awt.*; import java.awt.image.ColorModel; import java.awt.image.IndexColorModel; import java.util.Arrays; import static bdsup2sub.bitmap.ColorSpaceUtils.RGB2YCbCr; /* * Copyright 2014 Volker Oth (0xdeadbeef) / Miklos Juhasz (mjuhasz) * * 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 bdsup2sub.bitmap; /** * Palette class for mixed representation of RGB/YCbCr palettes with alpha information. */ public class Palette { /** Number of palette entries */ private final int size; /** Byte buffer for RED info */ private final byte[] r; /** Byte buffer for GREEN info */ private final byte[] g; /** Byte buffer for BLUE info */ private final byte[] b; /** Byte buffer for alpha info */ private final byte[] a; /** Byte buffer for Y (luminance) info */ private final byte[] y; /** Byte buffer for Cb (chrominance blue) info */ private final byte[] cb; /** Byte buffer for Cr (chrominance red) info */ private final byte[] cr; /** Use BT.601 color model instead of BT.709 */ private final boolean useBT601; /** * Initializes palette with transparent black (RGBA: 0x00000000) * @param size Number of palette entries */ public Palette(int size, boolean useBT601) { this.size = size; this.useBT601 = useBT601; r = new byte[size]; g = new byte[size]; b = new byte[size]; a = new byte[size]; y = new byte[size]; cb = new byte[size]; cr = new byte[size]; // set at least all alpha values to invisible
int[] yCbCr = RGB2YCbCr(0, 0, 0, useBT601);
mjuhasz/BDSup2Sub
src/main/java/bdsup2sub/utils/SubtitleUtils.java
// Path: src/main/java/bdsup2sub/core/Framerate.java // public enum Framerate { // FPS_23_976(24000.0/1001, 0x10), //24p // FPS_23_975(23.975, 0x10), // FPS_24(24.0, 0x20), // PAL(25.0, 0x30), // NTSC(30000.0/1001, 0x40), // PAL_I(50.0,0x60), // NTSC_I(60000.0/1001, 0x70); // // private final double value; // private final int id; // // private Framerate(double value, int id) { // this.value = value; // this.id = id; // } // // public double getValue() { // return value; // } // // public int getId() { // return id; // } // // public static double valueForId(int id) { // for (Framerate framerate : Framerate.values()) { // if (id == framerate.getId()) { // return framerate.getValue(); // } // } // throw new IllegalArgumentException("Unsupported id: " + id); // } // // public static int idForFramerate(double fps) { // for (Framerate framerate : Framerate.values()) { // if (fps == framerate.getValue()) { // return framerate.getId(); // } // } // throw new IllegalArgumentException("Unsupported framerate: " + fps); // } // } // // Path: src/main/java/bdsup2sub/core/Resolution.java // public enum Resolution { // NTSC { // @Override // public String toString() { // return "NTSC (720x480)"; // } // // @Override // public String getResolutionNameForXml() { // return "480i"; // } // // @Override // public int[] getDimensions() { // return new int[] {720, 480}; // } // }, // PAL { // @Override // public String toString() { // return "PAL (720x576)"; // } // // @Override // public String getResolutionNameForXml() { // return "576i"; // } // // @Override // public int[] getDimensions() { // return new int[]{720, 576}; // } // }, // HD_720 { // @Override // public String toString() { // return "720p (1280x720)"; // } // // @Override // public String getResolutionNameForXml() { // return "720p"; // } // // @Override // public int[] getDimensions() { // return new int[]{1280, 720}; // } // }, // HD_1440x1080 { // @Override // public String toString() { // return "1080p (1440x1080)"; // } // // @Override // public String getResolutionNameForXml() { // return "1440x1080"; // } // // @Override // public int[] getDimensions() { // return new int[]{1440, 1080}; // } // }, // HD_1080 { // @Override // public String toString() { // return "1080p (1920x1080)"; // } // // @Override // public String getResolutionNameForXml() { // return "1080p"; // } // // @Override // public int[] getDimensions() { // return new int[]{1920, 1080}; // } // }; // // public abstract String getResolutionNameForXml(); // public abstract int[] getDimensions(); // }
import bdsup2sub.core.Framerate; import bdsup2sub.core.Resolution;
/* * Copyright 2014 Volker Oth (0xdeadbeef) / Miklos Juhasz (mjuhasz) * * 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 bdsup2sub.utils; public final class SubtitleUtils { private SubtitleUtils() { } public static double getFps(String fps) { fps = fps.toLowerCase().trim(); if (fps.equals("pal") || fps.equals("25p") || fps.equals("25")) {
// Path: src/main/java/bdsup2sub/core/Framerate.java // public enum Framerate { // FPS_23_976(24000.0/1001, 0x10), //24p // FPS_23_975(23.975, 0x10), // FPS_24(24.0, 0x20), // PAL(25.0, 0x30), // NTSC(30000.0/1001, 0x40), // PAL_I(50.0,0x60), // NTSC_I(60000.0/1001, 0x70); // // private final double value; // private final int id; // // private Framerate(double value, int id) { // this.value = value; // this.id = id; // } // // public double getValue() { // return value; // } // // public int getId() { // return id; // } // // public static double valueForId(int id) { // for (Framerate framerate : Framerate.values()) { // if (id == framerate.getId()) { // return framerate.getValue(); // } // } // throw new IllegalArgumentException("Unsupported id: " + id); // } // // public static int idForFramerate(double fps) { // for (Framerate framerate : Framerate.values()) { // if (fps == framerate.getValue()) { // return framerate.getId(); // } // } // throw new IllegalArgumentException("Unsupported framerate: " + fps); // } // } // // Path: src/main/java/bdsup2sub/core/Resolution.java // public enum Resolution { // NTSC { // @Override // public String toString() { // return "NTSC (720x480)"; // } // // @Override // public String getResolutionNameForXml() { // return "480i"; // } // // @Override // public int[] getDimensions() { // return new int[] {720, 480}; // } // }, // PAL { // @Override // public String toString() { // return "PAL (720x576)"; // } // // @Override // public String getResolutionNameForXml() { // return "576i"; // } // // @Override // public int[] getDimensions() { // return new int[]{720, 576}; // } // }, // HD_720 { // @Override // public String toString() { // return "720p (1280x720)"; // } // // @Override // public String getResolutionNameForXml() { // return "720p"; // } // // @Override // public int[] getDimensions() { // return new int[]{1280, 720}; // } // }, // HD_1440x1080 { // @Override // public String toString() { // return "1080p (1440x1080)"; // } // // @Override // public String getResolutionNameForXml() { // return "1440x1080"; // } // // @Override // public int[] getDimensions() { // return new int[]{1440, 1080}; // } // }, // HD_1080 { // @Override // public String toString() { // return "1080p (1920x1080)"; // } // // @Override // public String getResolutionNameForXml() { // return "1080p"; // } // // @Override // public int[] getDimensions() { // return new int[]{1920, 1080}; // } // }; // // public abstract String getResolutionNameForXml(); // public abstract int[] getDimensions(); // } // Path: src/main/java/bdsup2sub/utils/SubtitleUtils.java import bdsup2sub.core.Framerate; import bdsup2sub.core.Resolution; /* * Copyright 2014 Volker Oth (0xdeadbeef) / Miklos Juhasz (mjuhasz) * * 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 bdsup2sub.utils; public final class SubtitleUtils { private SubtitleUtils() { } public static double getFps(String fps) { fps = fps.toLowerCase().trim(); if (fps.equals("pal") || fps.equals("25p") || fps.equals("25")) {
return Framerate.PAL.getValue();
mjuhasz/BDSup2Sub
src/main/java/bdsup2sub/utils/SubtitleUtils.java
// Path: src/main/java/bdsup2sub/core/Framerate.java // public enum Framerate { // FPS_23_976(24000.0/1001, 0x10), //24p // FPS_23_975(23.975, 0x10), // FPS_24(24.0, 0x20), // PAL(25.0, 0x30), // NTSC(30000.0/1001, 0x40), // PAL_I(50.0,0x60), // NTSC_I(60000.0/1001, 0x70); // // private final double value; // private final int id; // // private Framerate(double value, int id) { // this.value = value; // this.id = id; // } // // public double getValue() { // return value; // } // // public int getId() { // return id; // } // // public static double valueForId(int id) { // for (Framerate framerate : Framerate.values()) { // if (id == framerate.getId()) { // return framerate.getValue(); // } // } // throw new IllegalArgumentException("Unsupported id: " + id); // } // // public static int idForFramerate(double fps) { // for (Framerate framerate : Framerate.values()) { // if (fps == framerate.getValue()) { // return framerate.getId(); // } // } // throw new IllegalArgumentException("Unsupported framerate: " + fps); // } // } // // Path: src/main/java/bdsup2sub/core/Resolution.java // public enum Resolution { // NTSC { // @Override // public String toString() { // return "NTSC (720x480)"; // } // // @Override // public String getResolutionNameForXml() { // return "480i"; // } // // @Override // public int[] getDimensions() { // return new int[] {720, 480}; // } // }, // PAL { // @Override // public String toString() { // return "PAL (720x576)"; // } // // @Override // public String getResolutionNameForXml() { // return "576i"; // } // // @Override // public int[] getDimensions() { // return new int[]{720, 576}; // } // }, // HD_720 { // @Override // public String toString() { // return "720p (1280x720)"; // } // // @Override // public String getResolutionNameForXml() { // return "720p"; // } // // @Override // public int[] getDimensions() { // return new int[]{1280, 720}; // } // }, // HD_1440x1080 { // @Override // public String toString() { // return "1080p (1440x1080)"; // } // // @Override // public String getResolutionNameForXml() { // return "1440x1080"; // } // // @Override // public int[] getDimensions() { // return new int[]{1440, 1080}; // } // }, // HD_1080 { // @Override // public String toString() { // return "1080p (1920x1080)"; // } // // @Override // public String getResolutionNameForXml() { // return "1080p"; // } // // @Override // public int[] getDimensions() { // return new int[]{1920, 1080}; // } // }; // // public abstract String getResolutionNameForXml(); // public abstract int[] getDimensions(); // }
import bdsup2sub.core.Framerate; import bdsup2sub.core.Resolution;
} if (Math.abs(d - Framerate.PAL_I.getValue()) < 0.001) { return Framerate.PAL_I.getValue(); } return d; } /** * Synchronizes a time stamp in 90kHz resolution to the given frame rate. */ public static long syncTimePTS(long timeStamp, double fps, double fpsTrg) { long retval; // correct time stamps to fit to frames if (fps == Framerate.NTSC.getValue() || fps == Framerate.PAL.getValue() || fps == Framerate.FPS_24.getValue()) { // NTSC: 90000/(30000/1001) = 3003 // PAL: 90000/25 = 3600 // 24Hz: 90000/24 = 3750 int tpfi = (int)((90000+(fps/2))/fps); // target time per frame in 90kHz int tpfh = tpfi/2; retval = ((timeStamp + tpfh)/tpfi)*tpfi; } else if (fpsTrg == Framerate.FPS_23_976.getValue()) { // 90000/(24000/1001) = 3753.75 = 15015/4 retval = ((((timeStamp + 1877)*4)/15015)*15015)/4; } else { double tpf = (90000/fpsTrg); // target time per frame in 90kHz retval = (long)((long)(timeStamp/tpf)*tpf+0.5); } return retval; }
// Path: src/main/java/bdsup2sub/core/Framerate.java // public enum Framerate { // FPS_23_976(24000.0/1001, 0x10), //24p // FPS_23_975(23.975, 0x10), // FPS_24(24.0, 0x20), // PAL(25.0, 0x30), // NTSC(30000.0/1001, 0x40), // PAL_I(50.0,0x60), // NTSC_I(60000.0/1001, 0x70); // // private final double value; // private final int id; // // private Framerate(double value, int id) { // this.value = value; // this.id = id; // } // // public double getValue() { // return value; // } // // public int getId() { // return id; // } // // public static double valueForId(int id) { // for (Framerate framerate : Framerate.values()) { // if (id == framerate.getId()) { // return framerate.getValue(); // } // } // throw new IllegalArgumentException("Unsupported id: " + id); // } // // public static int idForFramerate(double fps) { // for (Framerate framerate : Framerate.values()) { // if (fps == framerate.getValue()) { // return framerate.getId(); // } // } // throw new IllegalArgumentException("Unsupported framerate: " + fps); // } // } // // Path: src/main/java/bdsup2sub/core/Resolution.java // public enum Resolution { // NTSC { // @Override // public String toString() { // return "NTSC (720x480)"; // } // // @Override // public String getResolutionNameForXml() { // return "480i"; // } // // @Override // public int[] getDimensions() { // return new int[] {720, 480}; // } // }, // PAL { // @Override // public String toString() { // return "PAL (720x576)"; // } // // @Override // public String getResolutionNameForXml() { // return "576i"; // } // // @Override // public int[] getDimensions() { // return new int[]{720, 576}; // } // }, // HD_720 { // @Override // public String toString() { // return "720p (1280x720)"; // } // // @Override // public String getResolutionNameForXml() { // return "720p"; // } // // @Override // public int[] getDimensions() { // return new int[]{1280, 720}; // } // }, // HD_1440x1080 { // @Override // public String toString() { // return "1080p (1440x1080)"; // } // // @Override // public String getResolutionNameForXml() { // return "1440x1080"; // } // // @Override // public int[] getDimensions() { // return new int[]{1440, 1080}; // } // }, // HD_1080 { // @Override // public String toString() { // return "1080p (1920x1080)"; // } // // @Override // public String getResolutionNameForXml() { // return "1080p"; // } // // @Override // public int[] getDimensions() { // return new int[]{1920, 1080}; // } // }; // // public abstract String getResolutionNameForXml(); // public abstract int[] getDimensions(); // } // Path: src/main/java/bdsup2sub/utils/SubtitleUtils.java import bdsup2sub.core.Framerate; import bdsup2sub.core.Resolution; } if (Math.abs(d - Framerate.PAL_I.getValue()) < 0.001) { return Framerate.PAL_I.getValue(); } return d; } /** * Synchronizes a time stamp in 90kHz resolution to the given frame rate. */ public static long syncTimePTS(long timeStamp, double fps, double fpsTrg) { long retval; // correct time stamps to fit to frames if (fps == Framerate.NTSC.getValue() || fps == Framerate.PAL.getValue() || fps == Framerate.FPS_24.getValue()) { // NTSC: 90000/(30000/1001) = 3003 // PAL: 90000/25 = 3600 // 24Hz: 90000/24 = 3750 int tpfi = (int)((90000+(fps/2))/fps); // target time per frame in 90kHz int tpfh = tpfi/2; retval = ((timeStamp + tpfh)/tpfi)*tpfi; } else if (fpsTrg == Framerate.FPS_23_976.getValue()) { // 90000/(24000/1001) = 3753.75 = 15015/4 retval = ((((timeStamp + 1877)*4)/15015)*15015)/4; } else { double tpf = (90000/fpsTrg); // target time per frame in 90kHz retval = (long)((long)(timeStamp/tpf)*tpf+0.5); } return retval; }
public static double getDefaultFramerateForResolution(Resolution resolution) {
mjuhasz/BDSup2Sub
src/test/java/bdsup2sub/cli/CommandLineParserTest.java
// Path: src/main/java/bdsup2sub/core/Configuration.java // public static final double MAX_FREE_SCALE_FACTOR = 2.0; // // Path: src/main/java/bdsup2sub/core/Configuration.java // public static final double MIN_FREE_SCALE_FACTOR = 0.5;
import bdsup2sub.core.*; import org.apache.commons.cli.ParseException; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FileOutputStream; import static bdsup2sub.core.Configuration.MAX_FREE_SCALE_FACTOR; import static bdsup2sub.core.Configuration.MIN_FREE_SCALE_FACTOR; import static org.junit.Assert.*;
} @Test public void shouldAcceptValidAlphaCropThresholdArg() throws Exception { subject.parse("--alpha-crop", "75"); assertEquals(75, subject.getAlphaCropThreshold().get().intValue()); } @Test(expected = ParseException.class) public void shouldRejectInvalidScaleXArg() throws Exception { subject.parse("--scale", "foo,2"); } @Test(expected = ParseException.class) public void shouldRejectInvalidScaleYArg() throws Exception { subject.parse("--scale", "2,foo"); } @Test(expected = ParseException.class) public void shouldRejectIfMissingScaleArg() throws Exception { subject.parse("--scale"); } @Test(expected = ParseException.class) public void shouldRejectIfMissingSecondScaleArg() throws Exception { subject.parse("--scale", "2"); } @Test(expected = ParseException.class) public void shouldRejectOutOfRangeXScaleArg() throws Exception {
// Path: src/main/java/bdsup2sub/core/Configuration.java // public static final double MAX_FREE_SCALE_FACTOR = 2.0; // // Path: src/main/java/bdsup2sub/core/Configuration.java // public static final double MIN_FREE_SCALE_FACTOR = 0.5; // Path: src/test/java/bdsup2sub/cli/CommandLineParserTest.java import bdsup2sub.core.*; import org.apache.commons.cli.ParseException; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FileOutputStream; import static bdsup2sub.core.Configuration.MAX_FREE_SCALE_FACTOR; import static bdsup2sub.core.Configuration.MIN_FREE_SCALE_FACTOR; import static org.junit.Assert.*; } @Test public void shouldAcceptValidAlphaCropThresholdArg() throws Exception { subject.parse("--alpha-crop", "75"); assertEquals(75, subject.getAlphaCropThreshold().get().intValue()); } @Test(expected = ParseException.class) public void shouldRejectInvalidScaleXArg() throws Exception { subject.parse("--scale", "foo,2"); } @Test(expected = ParseException.class) public void shouldRejectInvalidScaleYArg() throws Exception { subject.parse("--scale", "2,foo"); } @Test(expected = ParseException.class) public void shouldRejectIfMissingScaleArg() throws Exception { subject.parse("--scale"); } @Test(expected = ParseException.class) public void shouldRejectIfMissingSecondScaleArg() throws Exception { subject.parse("--scale", "2"); } @Test(expected = ParseException.class) public void shouldRejectOutOfRangeXScaleArg() throws Exception {
subject.parse("--scale", String.valueOf(MIN_FREE_SCALE_FACTOR - 1) + ",1");
mjuhasz/BDSup2Sub
src/test/java/bdsup2sub/cli/CommandLineParserTest.java
// Path: src/main/java/bdsup2sub/core/Configuration.java // public static final double MAX_FREE_SCALE_FACTOR = 2.0; // // Path: src/main/java/bdsup2sub/core/Configuration.java // public static final double MIN_FREE_SCALE_FACTOR = 0.5;
import bdsup2sub.core.*; import org.apache.commons.cli.ParseException; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FileOutputStream; import static bdsup2sub.core.Configuration.MAX_FREE_SCALE_FACTOR; import static bdsup2sub.core.Configuration.MIN_FREE_SCALE_FACTOR; import static org.junit.Assert.*;
assertEquals(75, subject.getAlphaCropThreshold().get().intValue()); } @Test(expected = ParseException.class) public void shouldRejectInvalidScaleXArg() throws Exception { subject.parse("--scale", "foo,2"); } @Test(expected = ParseException.class) public void shouldRejectInvalidScaleYArg() throws Exception { subject.parse("--scale", "2,foo"); } @Test(expected = ParseException.class) public void shouldRejectIfMissingScaleArg() throws Exception { subject.parse("--scale"); } @Test(expected = ParseException.class) public void shouldRejectIfMissingSecondScaleArg() throws Exception { subject.parse("--scale", "2"); } @Test(expected = ParseException.class) public void shouldRejectOutOfRangeXScaleArg() throws Exception { subject.parse("--scale", String.valueOf(MIN_FREE_SCALE_FACTOR - 1) + ",1"); } @Test(expected = ParseException.class) public void shouldRejectOutOfRangeYScaleArg() throws Exception {
// Path: src/main/java/bdsup2sub/core/Configuration.java // public static final double MAX_FREE_SCALE_FACTOR = 2.0; // // Path: src/main/java/bdsup2sub/core/Configuration.java // public static final double MIN_FREE_SCALE_FACTOR = 0.5; // Path: src/test/java/bdsup2sub/cli/CommandLineParserTest.java import bdsup2sub.core.*; import org.apache.commons.cli.ParseException; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FileOutputStream; import static bdsup2sub.core.Configuration.MAX_FREE_SCALE_FACTOR; import static bdsup2sub.core.Configuration.MIN_FREE_SCALE_FACTOR; import static org.junit.Assert.*; assertEquals(75, subject.getAlphaCropThreshold().get().intValue()); } @Test(expected = ParseException.class) public void shouldRejectInvalidScaleXArg() throws Exception { subject.parse("--scale", "foo,2"); } @Test(expected = ParseException.class) public void shouldRejectInvalidScaleYArg() throws Exception { subject.parse("--scale", "2,foo"); } @Test(expected = ParseException.class) public void shouldRejectIfMissingScaleArg() throws Exception { subject.parse("--scale"); } @Test(expected = ParseException.class) public void shouldRejectIfMissingSecondScaleArg() throws Exception { subject.parse("--scale", "2"); } @Test(expected = ParseException.class) public void shouldRejectOutOfRangeXScaleArg() throws Exception { subject.parse("--scale", String.valueOf(MIN_FREE_SCALE_FACTOR - 1) + ",1"); } @Test(expected = ParseException.class) public void shouldRejectOutOfRangeYScaleArg() throws Exception {
subject.parse("--scale", "1," + String.valueOf(MAX_FREE_SCALE_FACTOR + 1));
mjuhasz/BDSup2Sub
src/main/java/bdsup2sub/utils/TimeUtils.java
// Path: src/main/java/bdsup2sub/utils/ToolBox.java // public static String leftZeroPad(int value, int width) { // return String.format("%0" + width + "d", value); // }
import java.util.regex.Matcher; import java.util.regex.Pattern; import static bdsup2sub.utils.ToolBox.leftZeroPad;
/* * Copyright 2014 Volker Oth (0xdeadbeef) / Miklos Juhasz (mjuhasz) * * 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 bdsup2sub.utils; public class TimeUtils { private static final int PTS_FREQUENCY_IN_KHZ = 90; private static final Pattern TIME_PATTERN = Pattern.compile( "(\\d+):(\\d+):(\\d+)[:\\.](\\d+)" ); public static String ptsToTimeStr(long pts) { int time[] = ptsToTime(pts);
// Path: src/main/java/bdsup2sub/utils/ToolBox.java // public static String leftZeroPad(int value, int width) { // return String.format("%0" + width + "d", value); // } // Path: src/main/java/bdsup2sub/utils/TimeUtils.java import java.util.regex.Matcher; import java.util.regex.Pattern; import static bdsup2sub.utils.ToolBox.leftZeroPad; /* * Copyright 2014 Volker Oth (0xdeadbeef) / Miklos Juhasz (mjuhasz) * * 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 bdsup2sub.utils; public class TimeUtils { private static final int PTS_FREQUENCY_IN_KHZ = 90; private static final Pattern TIME_PATTERN = Pattern.compile( "(\\d+):(\\d+):(\\d+)[:\\.](\\d+)" ); public static String ptsToTimeStr(long pts) { int time[] = ptsToTime(pts);
return leftZeroPad(time[0], 2) + ":" + leftZeroPad(time[1], 2) + ":" + leftZeroPad(time[2], 2) + "." + leftZeroPad(time[3], 3);
790710371/bangbanghelper
app/src/main/java/com/mero/wyt_register/receiver/XposedModelIsOrNotInstalled.java
// Path: app/src/main/java/com/mero/wyt_register/Config.java // public class Config { // public static final String ID="prefs";//当前应用的ID // public static final String CHARSET="UTF-8";//编码格式 // public static final String DEBUGGING="T";//可调试开发阶段标志 // public static final String URL="www.haoma.com";//临时接码平台地址 // public static final String KEY_IS_FIRST_IN = "isFirstIn"; // public static final String KEY_IS_INSTALL_XPOSED = "isInstalledXposed";//是否安装XPOSED // public static final String KEY_IS_MODULE_INSTALLED = "isInstalledModule";//是否已经安装MODULE // public static final boolean VALUE_TRUE = true; // public static final boolean VALUE_FALSE = false; // public static final String VALUE_IS_INSTALL = "已安装"; // public static final String VALUE_NOT_INSTALLED = "未安装"; // } // // Path: app/src/main/java/com/mero/wyt_register/MyApplication.java // public class MyApplication extends Application { // public static MyApplication instance; // // @Override // public void onCreate() { // super.onCreate(); // instance = this; // } // public static MyApplication getMyApplication(){ // return instance; // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; import com.mero.wyt_register.Config; import com.mero.wyt_register.MyApplication;
package com.mero.wyt_register.receiver; /** * Created by chenlei on 2016/10/26. */ public class XposedModelIsOrNotInstalled extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals("xposed.isInstalledOrNot")){ Log.e("TAG","入口函数广播已接收到");
// Path: app/src/main/java/com/mero/wyt_register/Config.java // public class Config { // public static final String ID="prefs";//当前应用的ID // public static final String CHARSET="UTF-8";//编码格式 // public static final String DEBUGGING="T";//可调试开发阶段标志 // public static final String URL="www.haoma.com";//临时接码平台地址 // public static final String KEY_IS_FIRST_IN = "isFirstIn"; // public static final String KEY_IS_INSTALL_XPOSED = "isInstalledXposed";//是否安装XPOSED // public static final String KEY_IS_MODULE_INSTALLED = "isInstalledModule";//是否已经安装MODULE // public static final boolean VALUE_TRUE = true; // public static final boolean VALUE_FALSE = false; // public static final String VALUE_IS_INSTALL = "已安装"; // public static final String VALUE_NOT_INSTALLED = "未安装"; // } // // Path: app/src/main/java/com/mero/wyt_register/MyApplication.java // public class MyApplication extends Application { // public static MyApplication instance; // // @Override // public void onCreate() { // super.onCreate(); // instance = this; // } // public static MyApplication getMyApplication(){ // return instance; // } // } // Path: app/src/main/java/com/mero/wyt_register/receiver/XposedModelIsOrNotInstalled.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; import com.mero.wyt_register.Config; import com.mero.wyt_register.MyApplication; package com.mero.wyt_register.receiver; /** * Created by chenlei on 2016/10/26. */ public class XposedModelIsOrNotInstalled extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals("xposed.isInstalledOrNot")){ Log.e("TAG","入口函数广播已接收到");
SharedPreferences sharedPreferences = MyApplication.getMyApplication().getSharedPreferences(Config.ID,Context.MODE_PRIVATE);
790710371/bangbanghelper
app/src/main/java/com/mero/wyt_register/receiver/XposedModelIsOrNotInstalled.java
// Path: app/src/main/java/com/mero/wyt_register/Config.java // public class Config { // public static final String ID="prefs";//当前应用的ID // public static final String CHARSET="UTF-8";//编码格式 // public static final String DEBUGGING="T";//可调试开发阶段标志 // public static final String URL="www.haoma.com";//临时接码平台地址 // public static final String KEY_IS_FIRST_IN = "isFirstIn"; // public static final String KEY_IS_INSTALL_XPOSED = "isInstalledXposed";//是否安装XPOSED // public static final String KEY_IS_MODULE_INSTALLED = "isInstalledModule";//是否已经安装MODULE // public static final boolean VALUE_TRUE = true; // public static final boolean VALUE_FALSE = false; // public static final String VALUE_IS_INSTALL = "已安装"; // public static final String VALUE_NOT_INSTALLED = "未安装"; // } // // Path: app/src/main/java/com/mero/wyt_register/MyApplication.java // public class MyApplication extends Application { // public static MyApplication instance; // // @Override // public void onCreate() { // super.onCreate(); // instance = this; // } // public static MyApplication getMyApplication(){ // return instance; // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; import com.mero.wyt_register.Config; import com.mero.wyt_register.MyApplication;
package com.mero.wyt_register.receiver; /** * Created by chenlei on 2016/10/26. */ public class XposedModelIsOrNotInstalled extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals("xposed.isInstalledOrNot")){ Log.e("TAG","入口函数广播已接收到");
// Path: app/src/main/java/com/mero/wyt_register/Config.java // public class Config { // public static final String ID="prefs";//当前应用的ID // public static final String CHARSET="UTF-8";//编码格式 // public static final String DEBUGGING="T";//可调试开发阶段标志 // public static final String URL="www.haoma.com";//临时接码平台地址 // public static final String KEY_IS_FIRST_IN = "isFirstIn"; // public static final String KEY_IS_INSTALL_XPOSED = "isInstalledXposed";//是否安装XPOSED // public static final String KEY_IS_MODULE_INSTALLED = "isInstalledModule";//是否已经安装MODULE // public static final boolean VALUE_TRUE = true; // public static final boolean VALUE_FALSE = false; // public static final String VALUE_IS_INSTALL = "已安装"; // public static final String VALUE_NOT_INSTALLED = "未安装"; // } // // Path: app/src/main/java/com/mero/wyt_register/MyApplication.java // public class MyApplication extends Application { // public static MyApplication instance; // // @Override // public void onCreate() { // super.onCreate(); // instance = this; // } // public static MyApplication getMyApplication(){ // return instance; // } // } // Path: app/src/main/java/com/mero/wyt_register/receiver/XposedModelIsOrNotInstalled.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; import com.mero.wyt_register.Config; import com.mero.wyt_register.MyApplication; package com.mero.wyt_register.receiver; /** * Created by chenlei on 2016/10/26. */ public class XposedModelIsOrNotInstalled extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals("xposed.isInstalledOrNot")){ Log.e("TAG","入口函数广播已接收到");
SharedPreferences sharedPreferences = MyApplication.getMyApplication().getSharedPreferences(Config.ID,Context.MODE_PRIVATE);
790710371/bangbanghelper
app/src/main/java/com/mero/wyt_register/net/BaseHttpConnection.java
// Path: app/src/main/java/com/mero/wyt_register/Config.java // public class Config { // public static final String ID="prefs";//当前应用的ID // public static final String CHARSET="UTF-8";//编码格式 // public static final String DEBUGGING="T";//可调试开发阶段标志 // public static final String URL="www.haoma.com";//临时接码平台地址 // public static final String KEY_IS_FIRST_IN = "isFirstIn"; // public static final String KEY_IS_INSTALL_XPOSED = "isInstalledXposed";//是否安装XPOSED // public static final String KEY_IS_MODULE_INSTALLED = "isInstalledModule";//是否已经安装MODULE // public static final boolean VALUE_TRUE = true; // public static final boolean VALUE_FALSE = false; // public static final String VALUE_IS_INSTALL = "已安装"; // public static final String VALUE_NOT_INSTALLED = "未安装"; // } // // Path: app/src/main/java/com/mero/wyt_register/HttpMethod.java // public enum HttpMethod { // POST,GET // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import android.os.AsyncTask; import android.util.Log; import com.mero.wyt_register.Config; import com.mero.wyt_register.HttpMethod;
package com.mero.wyt_register.net; /** *@项目名称: 简易通注册助手 *@文件名称: BaseHttpConnection.java *@Date: 2016-7-14 *@Copyright: 2016 Technology Mero Inc. All rights reserved. *注意:由Mero开发,禁止外泄以及使用本程序于其他的商业目的 。 */ public class BaseHttpConnection{ private static final String TAG = "baseNetTag";//用于网络访问的TAG日志
// Path: app/src/main/java/com/mero/wyt_register/Config.java // public class Config { // public static final String ID="prefs";//当前应用的ID // public static final String CHARSET="UTF-8";//编码格式 // public static final String DEBUGGING="T";//可调试开发阶段标志 // public static final String URL="www.haoma.com";//临时接码平台地址 // public static final String KEY_IS_FIRST_IN = "isFirstIn"; // public static final String KEY_IS_INSTALL_XPOSED = "isInstalledXposed";//是否安装XPOSED // public static final String KEY_IS_MODULE_INSTALLED = "isInstalledModule";//是否已经安装MODULE // public static final boolean VALUE_TRUE = true; // public static final boolean VALUE_FALSE = false; // public static final String VALUE_IS_INSTALL = "已安装"; // public static final String VALUE_NOT_INSTALLED = "未安装"; // } // // Path: app/src/main/java/com/mero/wyt_register/HttpMethod.java // public enum HttpMethod { // POST,GET // } // Path: app/src/main/java/com/mero/wyt_register/net/BaseHttpConnection.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import android.os.AsyncTask; import android.util.Log; import com.mero.wyt_register.Config; import com.mero.wyt_register.HttpMethod; package com.mero.wyt_register.net; /** *@项目名称: 简易通注册助手 *@文件名称: BaseHttpConnection.java *@Date: 2016-7-14 *@Copyright: 2016 Technology Mero Inc. All rights reserved. *注意:由Mero开发,禁止外泄以及使用本程序于其他的商业目的 。 */ public class BaseHttpConnection{ private static final String TAG = "baseNetTag";//用于网络访问的TAG日志
public BaseHttpConnection(final String url,final HttpMethod httpMethod,final ISuccessCallback successCallback,final IFailedCallback failedCallback,String...params){
790710371/bangbanghelper
app/src/main/java/com/mero/wyt_register/net/BaseHttpConnection.java
// Path: app/src/main/java/com/mero/wyt_register/Config.java // public class Config { // public static final String ID="prefs";//当前应用的ID // public static final String CHARSET="UTF-8";//编码格式 // public static final String DEBUGGING="T";//可调试开发阶段标志 // public static final String URL="www.haoma.com";//临时接码平台地址 // public static final String KEY_IS_FIRST_IN = "isFirstIn"; // public static final String KEY_IS_INSTALL_XPOSED = "isInstalledXposed";//是否安装XPOSED // public static final String KEY_IS_MODULE_INSTALLED = "isInstalledModule";//是否已经安装MODULE // public static final boolean VALUE_TRUE = true; // public static final boolean VALUE_FALSE = false; // public static final String VALUE_IS_INSTALL = "已安装"; // public static final String VALUE_NOT_INSTALLED = "未安装"; // } // // Path: app/src/main/java/com/mero/wyt_register/HttpMethod.java // public enum HttpMethod { // POST,GET // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import android.os.AsyncTask; import android.util.Log; import com.mero.wyt_register.Config; import com.mero.wyt_register.HttpMethod;
package com.mero.wyt_register.net; /** *@项目名称: 简易通注册助手 *@文件名称: BaseHttpConnection.java *@Date: 2016-7-14 *@Copyright: 2016 Technology Mero Inc. All rights reserved. *注意:由Mero开发,禁止外泄以及使用本程序于其他的商业目的 。 */ public class BaseHttpConnection{ private static final String TAG = "baseNetTag";//用于网络访问的TAG日志 public BaseHttpConnection(final String url,final HttpMethod httpMethod,final ISuccessCallback successCallback,final IFailedCallback failedCallback,String...params){ new AsyncTask<Void, Void, String>(){ @Override protected String doInBackground(Void... params) { StringBuffer buffer=new StringBuffer();//创建字符串连接对象 for(int i=0;i<params.length;i+=2){ buffer.append(params[i]).append("=").append(params[i+1]).append("&"); } buffer.deleteCharAt(buffer.length()-1); Log.e(TAG, url+buffer.toString()); try{ URLConnection conn=null; switch(httpMethod){ case POST: conn = new URL(url).openConnection();//打开链接 conn.setDoInput(true);//数据通道设置
// Path: app/src/main/java/com/mero/wyt_register/Config.java // public class Config { // public static final String ID="prefs";//当前应用的ID // public static final String CHARSET="UTF-8";//编码格式 // public static final String DEBUGGING="T";//可调试开发阶段标志 // public static final String URL="www.haoma.com";//临时接码平台地址 // public static final String KEY_IS_FIRST_IN = "isFirstIn"; // public static final String KEY_IS_INSTALL_XPOSED = "isInstalledXposed";//是否安装XPOSED // public static final String KEY_IS_MODULE_INSTALLED = "isInstalledModule";//是否已经安装MODULE // public static final boolean VALUE_TRUE = true; // public static final boolean VALUE_FALSE = false; // public static final String VALUE_IS_INSTALL = "已安装"; // public static final String VALUE_NOT_INSTALLED = "未安装"; // } // // Path: app/src/main/java/com/mero/wyt_register/HttpMethod.java // public enum HttpMethod { // POST,GET // } // Path: app/src/main/java/com/mero/wyt_register/net/BaseHttpConnection.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import android.os.AsyncTask; import android.util.Log; import com.mero.wyt_register.Config; import com.mero.wyt_register.HttpMethod; package com.mero.wyt_register.net; /** *@项目名称: 简易通注册助手 *@文件名称: BaseHttpConnection.java *@Date: 2016-7-14 *@Copyright: 2016 Technology Mero Inc. All rights reserved. *注意:由Mero开发,禁止外泄以及使用本程序于其他的商业目的 。 */ public class BaseHttpConnection{ private static final String TAG = "baseNetTag";//用于网络访问的TAG日志 public BaseHttpConnection(final String url,final HttpMethod httpMethod,final ISuccessCallback successCallback,final IFailedCallback failedCallback,String...params){ new AsyncTask<Void, Void, String>(){ @Override protected String doInBackground(Void... params) { StringBuffer buffer=new StringBuffer();//创建字符串连接对象 for(int i=0;i<params.length;i+=2){ buffer.append(params[i]).append("=").append(params[i+1]).append("&"); } buffer.deleteCharAt(buffer.length()-1); Log.e(TAG, url+buffer.toString()); try{ URLConnection conn=null; switch(httpMethod){ case POST: conn = new URL(url).openConnection();//打开链接 conn.setDoInput(true);//数据通道设置
BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), Config.CHARSET));
Sonoport/freesound-java
src/test/java/com/sonoport/freesound/response/mapping/CommentMapperTest.java
// Path: src/main/java/com/sonoport/freesound/response/Comment.java // public class Comment { // // /** The username of the person making the comment. */ // private String username; // // /** The comment itself. */ // private String comment; // // /** The date/time the comment was made. */ // private Date created; // // /** // * @return the username // */ // public String getUsername() { // return username; // } // // /** // * @param username the username to set // */ // public void setUsername(final String username) { // this.username = username; // } // // /** // * @return the comment // */ // public String getComment() { // return comment; // } // // /** // * @param comment the comment to set // */ // public void setComment(final String comment) { // this.comment = comment; // } // // /** // * @return the created // */ // public Date getCreated() { // return created; // } // // /** // * @param created the created to set // */ // public void setCreated(final Date created) { // this.created = created; // } // }
import static org.junit.Assert.assertEquals; import java.util.Date; import org.json.JSONObject; import org.junit.Test; import com.sonoport.freesound.response.Comment;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.response.mapping; /** * Unit tests to ensure the correct operation of {@link CommentMapper}. * * Source data for tests can be found at <code>/src/test/resources/comment.json</code>. */ public class CommentMapperTest extends MapperTest { /** The username in the comment. */ private static final String USERNAME = "cjrowe"; /** The comment itself. */ private static final String COMMENT = "This is great!"; /** Date/time the comment was made. */ private static final Date CREATED = new Date(1417016748000L); /** Instance of {@link CommentMapper} to use in tests. */ private final CommentMapper mapper = new CommentMapper(); /** * Ensure that {@link CommentMapper} correctly processes a valid JSON representation of a comment. * * @throws Exception Any exceptions thrown in test */ @Test public void parseComment() throws Exception { final JSONObject commentJSON = readJSONFile("/comment.json");
// Path: src/main/java/com/sonoport/freesound/response/Comment.java // public class Comment { // // /** The username of the person making the comment. */ // private String username; // // /** The comment itself. */ // private String comment; // // /** The date/time the comment was made. */ // private Date created; // // /** // * @return the username // */ // public String getUsername() { // return username; // } // // /** // * @param username the username to set // */ // public void setUsername(final String username) { // this.username = username; // } // // /** // * @return the comment // */ // public String getComment() { // return comment; // } // // /** // * @param comment the comment to set // */ // public void setComment(final String comment) { // this.comment = comment; // } // // /** // * @return the created // */ // public Date getCreated() { // return created; // } // // /** // * @param created the created to set // */ // public void setCreated(final Date created) { // this.created = created; // } // } // Path: src/test/java/com/sonoport/freesound/response/mapping/CommentMapperTest.java import static org.junit.Assert.assertEquals; import java.util.Date; import org.json.JSONObject; import org.junit.Test; import com.sonoport.freesound.response.Comment; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.response.mapping; /** * Unit tests to ensure the correct operation of {@link CommentMapper}. * * Source data for tests can be found at <code>/src/test/resources/comment.json</code>. */ public class CommentMapperTest extends MapperTest { /** The username in the comment. */ private static final String USERNAME = "cjrowe"; /** The comment itself. */ private static final String COMMENT = "This is great!"; /** Date/time the comment was made. */ private static final Date CREATED = new Date(1417016748000L); /** Instance of {@link CommentMapper} to use in tests. */ private final CommentMapper mapper = new CommentMapper(); /** * Ensure that {@link CommentMapper} correctly processes a valid JSON representation of a comment. * * @throws Exception Any exceptions thrown in test */ @Test public void parseComment() throws Exception { final JSONObject commentJSON = readJSONFile("/comment.json");
final Comment comment = mapper.map(commentJSON);
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/search/TextSearch.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/SoundPagingQuery.java // public abstract class SoundPagingQuery<Q extends SoundPagingQuery<Q>> extends PagingQuery<Q, Sound> { // // /** Name of parameter to include the list of fields to return, if specified. */ // public static final String FIELDS_PARAMETER = "fields"; // // /** The fields to retrieve as part of the query. If values are specified here, only those fields will be returned. // * If no values are specified, freesound will return a default set. */ // private Set<String> fields; // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path The URI path to the API endpoint // */ // protected SoundPagingQuery(final HTTPRequestMethod httpRequestMethod, final String path) { // super(httpRequestMethod, path, new PagingResponseMapper<>(new SoundMapper())); // } // // @Override // public Map<String, Object> getQueryParameters() { // final Map<String, Object> params = super.getQueryParameters(); // // if ((fields != null) && !fields.isEmpty()) { // final StringBuilder fieldsString = new StringBuilder(); // for (final String field : fields) { // fieldsString.append(field.trim()); // fieldsString.append(','); // } // fieldsString.deleteCharAt(fieldsString.lastIndexOf(",")); // // params.put(FIELDS_PARAMETER, fieldsString.toString()); // } // // return params; // } // // /** // * Specify a field to return in the results using the Fluent API approach. Users may specify this method multiple // * times to define the collection of fields they want returning, and/or use // * {@link SoundPagingQuery#includeFields(Set)} to define them as a batch. // * // * @param field The field to include in the results // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeField(final String field) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (field != null) { // this.fields.add(field); // } // // return (Q) this; // } // // /** // * Specify the set of fields to return in the results. Defined using the Fluent API approach. // * // * @param fields The fields to return // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeFields(final Set<String> fields) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (fields != null) { // this.fields.addAll(fields); // } // // return (Q) this; // } // }
import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.SoundPagingQuery;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.search; /** * Class used to represent a Text Search of the freesound.org content library. The class presents a fluent API to allow * queries to be constructed more easily. * * Full details of the query can be found at http://www.freesound.org/docs/api/resources_apiv2.html#text-search. */ public class TextSearch extends SoundPagingQuery<TextSearch> { /** Name of the parameter to pass the names of fields to include in responses as. */ protected static final String FIELDS_PARAMETER = "fields"; /** The name of the query parameter to pass the search string over as. */ private static final String SEARCH_STRING_PARAMETER = "query"; /** The name of the query parameter to pass the sort order over as. */ private static final String SORT_ORDER_PARAMETER = "sort"; /** The name of the parameter to pass the 'group by pack' flag over as. */ private static final String GROUP_BY_PACK_PARAMETER = "group_by_pack"; /** The string to use as the search criteria. This value is used to populate the 'query' parameter on the request, * so the full range of expressions permitted by the API can be specified. */ private String searchString; /** The order in which to request results are sorted. The enum specified here contains the appropriate value to pass * in the HTTP call. */ private SortOrder sortOrder; /** Collection of filters that should be applied as part of the query. */ private Set<SearchFilter> filters; /** Whether to group results by the pack to which they belong. */ private Boolean groupByPack; /** * No-arg constructor. */ public TextSearch() {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/SoundPagingQuery.java // public abstract class SoundPagingQuery<Q extends SoundPagingQuery<Q>> extends PagingQuery<Q, Sound> { // // /** Name of parameter to include the list of fields to return, if specified. */ // public static final String FIELDS_PARAMETER = "fields"; // // /** The fields to retrieve as part of the query. If values are specified here, only those fields will be returned. // * If no values are specified, freesound will return a default set. */ // private Set<String> fields; // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path The URI path to the API endpoint // */ // protected SoundPagingQuery(final HTTPRequestMethod httpRequestMethod, final String path) { // super(httpRequestMethod, path, new PagingResponseMapper<>(new SoundMapper())); // } // // @Override // public Map<String, Object> getQueryParameters() { // final Map<String, Object> params = super.getQueryParameters(); // // if ((fields != null) && !fields.isEmpty()) { // final StringBuilder fieldsString = new StringBuilder(); // for (final String field : fields) { // fieldsString.append(field.trim()); // fieldsString.append(','); // } // fieldsString.deleteCharAt(fieldsString.lastIndexOf(",")); // // params.put(FIELDS_PARAMETER, fieldsString.toString()); // } // // return params; // } // // /** // * Specify a field to return in the results using the Fluent API approach. Users may specify this method multiple // * times to define the collection of fields they want returning, and/or use // * {@link SoundPagingQuery#includeFields(Set)} to define them as a batch. // * // * @param field The field to include in the results // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeField(final String field) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (field != null) { // this.fields.add(field); // } // // return (Q) this; // } // // /** // * Specify the set of fields to return in the results. Defined using the Fluent API approach. // * // * @param fields The fields to return // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeFields(final Set<String> fields) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (fields != null) { // this.fields.addAll(fields); // } // // return (Q) this; // } // } // Path: src/main/java/com/sonoport/freesound/query/search/TextSearch.java import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.SoundPagingQuery; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.search; /** * Class used to represent a Text Search of the freesound.org content library. The class presents a fluent API to allow * queries to be constructed more easily. * * Full details of the query can be found at http://www.freesound.org/docs/api/resources_apiv2.html#text-search. */ public class TextSearch extends SoundPagingQuery<TextSearch> { /** Name of the parameter to pass the names of fields to include in responses as. */ protected static final String FIELDS_PARAMETER = "fields"; /** The name of the query parameter to pass the search string over as. */ private static final String SEARCH_STRING_PARAMETER = "query"; /** The name of the query parameter to pass the sort order over as. */ private static final String SORT_ORDER_PARAMETER = "sort"; /** The name of the parameter to pass the 'group by pack' flag over as. */ private static final String GROUP_BY_PACK_PARAMETER = "group_by_pack"; /** The string to use as the search criteria. This value is used to populate the 'query' parameter on the request, * so the full range of expressions permitted by the API can be specified. */ private String searchString; /** The order in which to request results are sorted. The enum specified here contains the appropriate value to pass * in the HTTP call. */ private SortOrder sortOrder; /** Collection of filters that should be applied as part of the query. */ private Set<SearchFilter> filters; /** Whether to group results by the pack to which they belong. */ private Boolean groupByPack; /** * No-arg constructor. */ public TextSearch() {
super(HTTPRequestMethod.GET, "/search/text/");
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/sound/CommentSound.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/DetailStringMapper.java // public class DetailStringMapper extends Mapper<JSONObject, String> { // // @Override // public String map(final JSONObject source) { // return extractFieldValue(source, "detail", String.class); // } // // }
import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.mapping.DetailStringMapper;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query class that allows users to add comments to sounds. */ public class CommentSound extends JSONResponseQuery<String> implements OAuthQuery { /** Name of route parameter to be replaced with teh sound identifier. */ protected static final String SOUND_IDENTIFIER_ROUTE_PARAMETER = "sound_id"; /** Path to API endpoint. */ private static final String PATH = String.format("/sounds/{%s}/comment/", SOUND_IDENTIFIER_ROUTE_PARAMETER); /** Parameter to pass comment through as. */ protected static final String COMMENT_PARAMETER_NAME = "comment"; /** Identifier of sound to add comment to. */ private final int soundIdentifier; /** Comment to add. */ private final String comment; /** OAuth taken to present. */ private final String oauthToken; /** * @param soundIdentifier Identifier of sound * @param comment Comment to add * @param oauthToken Token to present */ public CommentSound(final int soundIdentifier, final String comment, final String oauthToken) {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/DetailStringMapper.java // public class DetailStringMapper extends Mapper<JSONObject, String> { // // @Override // public String map(final JSONObject source) { // return extractFieldValue(source, "detail", String.class); // } // // } // Path: src/main/java/com/sonoport/freesound/query/sound/CommentSound.java import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.mapping.DetailStringMapper; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query class that allows users to add comments to sounds. */ public class CommentSound extends JSONResponseQuery<String> implements OAuthQuery { /** Name of route parameter to be replaced with teh sound identifier. */ protected static final String SOUND_IDENTIFIER_ROUTE_PARAMETER = "sound_id"; /** Path to API endpoint. */ private static final String PATH = String.format("/sounds/{%s}/comment/", SOUND_IDENTIFIER_ROUTE_PARAMETER); /** Parameter to pass comment through as. */ protected static final String COMMENT_PARAMETER_NAME = "comment"; /** Identifier of sound to add comment to. */ private final int soundIdentifier; /** Comment to add. */ private final String comment; /** OAuth taken to present. */ private final String oauthToken; /** * @param soundIdentifier Identifier of sound * @param comment Comment to add * @param oauthToken Token to present */ public CommentSound(final int soundIdentifier, final String comment, final String oauthToken) {
super(HTTPRequestMethod.POST, PATH, new DetailStringMapper());
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/sound/CommentSound.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/DetailStringMapper.java // public class DetailStringMapper extends Mapper<JSONObject, String> { // // @Override // public String map(final JSONObject source) { // return extractFieldValue(source, "detail", String.class); // } // // }
import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.mapping.DetailStringMapper;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query class that allows users to add comments to sounds. */ public class CommentSound extends JSONResponseQuery<String> implements OAuthQuery { /** Name of route parameter to be replaced with teh sound identifier. */ protected static final String SOUND_IDENTIFIER_ROUTE_PARAMETER = "sound_id"; /** Path to API endpoint. */ private static final String PATH = String.format("/sounds/{%s}/comment/", SOUND_IDENTIFIER_ROUTE_PARAMETER); /** Parameter to pass comment through as. */ protected static final String COMMENT_PARAMETER_NAME = "comment"; /** Identifier of sound to add comment to. */ private final int soundIdentifier; /** Comment to add. */ private final String comment; /** OAuth taken to present. */ private final String oauthToken; /** * @param soundIdentifier Identifier of sound * @param comment Comment to add * @param oauthToken Token to present */ public CommentSound(final int soundIdentifier, final String comment, final String oauthToken) {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/DetailStringMapper.java // public class DetailStringMapper extends Mapper<JSONObject, String> { // // @Override // public String map(final JSONObject source) { // return extractFieldValue(source, "detail", String.class); // } // // } // Path: src/main/java/com/sonoport/freesound/query/sound/CommentSound.java import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.mapping.DetailStringMapper; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query class that allows users to add comments to sounds. */ public class CommentSound extends JSONResponseQuery<String> implements OAuthQuery { /** Name of route parameter to be replaced with teh sound identifier. */ protected static final String SOUND_IDENTIFIER_ROUTE_PARAMETER = "sound_id"; /** Path to API endpoint. */ private static final String PATH = String.format("/sounds/{%s}/comment/", SOUND_IDENTIFIER_ROUTE_PARAMETER); /** Parameter to pass comment through as. */ protected static final String COMMENT_PARAMETER_NAME = "comment"; /** Identifier of sound to add comment to. */ private final int soundIdentifier; /** Comment to add. */ private final String comment; /** OAuth taken to present. */ private final String oauthToken; /** * @param soundIdentifier Identifier of sound * @param comment Comment to add * @param oauthToken Token to present */ public CommentSound(final int soundIdentifier, final String comment, final String oauthToken) {
super(HTTPRequestMethod.POST, PATH, new DetailStringMapper());
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/sound/EditSoundDescription.java
// Path: src/main/java/com/sonoport/freesound/response/mapping/DetailStringMapper.java // public class DetailStringMapper extends Mapper<JSONObject, String> { // // @Override // public String map(final JSONObject source) { // return extractFieldValue(source, "detail", String.class); // } // // }
import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.response.mapping.DetailStringMapper;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query class used to update the description associated with one of the user's previously uploaded sounds. */ public class EditSoundDescription extends AbstractSoundUploadQuery<String, EditSoundDescription> { /** Route parameter that will be replaced with sound identifier. */ protected static final String SOUND_IDENTIFIER_ROUTE_PARAMETER = "sound_id"; /** API endpoint path. */ private static final String PATH = String.format("/sounds/{%s}/edit/", SOUND_IDENTIFIER_ROUTE_PARAMETER); /** Identifier of sound to modify. */ private final int soundIdentifier; /** * @param soundIdentifier Identifier of sound to modify * @param oauthToken OAuth2 token to present */ public EditSoundDescription(final int soundIdentifier, final String oauthToken) {
// Path: src/main/java/com/sonoport/freesound/response/mapping/DetailStringMapper.java // public class DetailStringMapper extends Mapper<JSONObject, String> { // // @Override // public String map(final JSONObject source) { // return extractFieldValue(source, "detail", String.class); // } // // } // Path: src/main/java/com/sonoport/freesound/query/sound/EditSoundDescription.java import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.response.mapping.DetailStringMapper; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query class used to update the description associated with one of the user's previously uploaded sounds. */ public class EditSoundDescription extends AbstractSoundUploadQuery<String, EditSoundDescription> { /** Route parameter that will be replaced with sound identifier. */ protected static final String SOUND_IDENTIFIER_ROUTE_PARAMETER = "sound_id"; /** API endpoint path. */ private static final String PATH = String.format("/sounds/{%s}/edit/", SOUND_IDENTIFIER_ROUTE_PARAMETER); /** Identifier of sound to modify. */ private final int soundIdentifier; /** * @param soundIdentifier Identifier of sound to modify * @param oauthToken OAuth2 token to present */ public EditSoundDescription(final int soundIdentifier, final String oauthToken) {
super(PATH, oauthToken, new DetailStringMapper());
Sonoport/freesound-java
src/test/java/com/sonoport/freesound/response/mapping/BookmarkCategoryMapperTest.java
// Path: src/main/java/com/sonoport/freesound/response/BookmarkCategory.java // public class BookmarkCategory { // // /** URI of the bookmark category in Freesound. */ // private String url; // // /** Name that the user has given to the bookmark category. */ // private String name; // // /** Number of sounds under the bookmark category. */ // private int numberOfSounds; // // /** URI to a page with the list of sounds in this bookmark category. */ // private String soundsURL; // // /** // * @return the url // */ // public String getUrl() { // return url; // } // // /** // * @param url the url to set // */ // public void setUrl(final String url) { // this.url = url; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(final String name) { // this.name = name; // } // // /** // * @return the numberOfSounds // */ // public int getNumberOfSounds() { // return numberOfSounds; // } // // /** // * @param numberOfSounds the numberOfSounds to set // */ // public void setNumberOfSounds(final int numberOfSounds) { // this.numberOfSounds = numberOfSounds; // } // // /** // * @return the soundsURL // */ // public String getSoundsURL() { // return soundsURL; // } // // /** // * @param soundsURL the soundsURL to set // */ // public void setSoundsURL(final String soundsURL) { // this.soundsURL = soundsURL; // } // // }
import static org.junit.Assert.assertEquals; import org.json.JSONObject; import org.junit.Test; import com.sonoport.freesound.response.BookmarkCategory;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.response.mapping; /** * Unit tests to ensure the correct operation of {@link BookmarkCategoryMapper}. */ public class BookmarkCategoryMapperTest extends MapperTest { /** URL to use in tests. */ private static final String URL = "http://www.freesound.org/people/frederic.font/bookmarks/category/23840/"; /** Name of category. */ private static final String NAME = "Rooms"; /** Number of sounds in category. */ private static final int NUMBER_OF_SOUNDS = 1; /** URL to list of sounds in category. */ private static final String SOUNDS_URL = "http://www.freesound.org/apiv2/users/frederic.font/bookmark_categories/23840/sounds/"; /** Instance of {@link BookmarkCategoryMapper} to use in tests. */ private final BookmarkCategoryMapper mapper = new BookmarkCategoryMapper(); /** * Ensure that a properly formatted JSON representation of a bookmark category is correctly converted into a * {@link BookmarkCategory} object. * * @throws Exception Any exceptions thrown in test */ @Test public void parseBookmarkCategory() throws Exception { final JSONObject bookmarkCategoryJSON = readJSONFile("/bookmark-category.json");
// Path: src/main/java/com/sonoport/freesound/response/BookmarkCategory.java // public class BookmarkCategory { // // /** URI of the bookmark category in Freesound. */ // private String url; // // /** Name that the user has given to the bookmark category. */ // private String name; // // /** Number of sounds under the bookmark category. */ // private int numberOfSounds; // // /** URI to a page with the list of sounds in this bookmark category. */ // private String soundsURL; // // /** // * @return the url // */ // public String getUrl() { // return url; // } // // /** // * @param url the url to set // */ // public void setUrl(final String url) { // this.url = url; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(final String name) { // this.name = name; // } // // /** // * @return the numberOfSounds // */ // public int getNumberOfSounds() { // return numberOfSounds; // } // // /** // * @param numberOfSounds the numberOfSounds to set // */ // public void setNumberOfSounds(final int numberOfSounds) { // this.numberOfSounds = numberOfSounds; // } // // /** // * @return the soundsURL // */ // public String getSoundsURL() { // return soundsURL; // } // // /** // * @param soundsURL the soundsURL to set // */ // public void setSoundsURL(final String soundsURL) { // this.soundsURL = soundsURL; // } // // } // Path: src/test/java/com/sonoport/freesound/response/mapping/BookmarkCategoryMapperTest.java import static org.junit.Assert.assertEquals; import org.json.JSONObject; import org.junit.Test; import com.sonoport.freesound.response.BookmarkCategory; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.response.mapping; /** * Unit tests to ensure the correct operation of {@link BookmarkCategoryMapper}. */ public class BookmarkCategoryMapperTest extends MapperTest { /** URL to use in tests. */ private static final String URL = "http://www.freesound.org/people/frederic.font/bookmarks/category/23840/"; /** Name of category. */ private static final String NAME = "Rooms"; /** Number of sounds in category. */ private static final int NUMBER_OF_SOUNDS = 1; /** URL to list of sounds in category. */ private static final String SOUNDS_URL = "http://www.freesound.org/apiv2/users/frederic.font/bookmark_categories/23840/sounds/"; /** Instance of {@link BookmarkCategoryMapper} to use in tests. */ private final BookmarkCategoryMapper mapper = new BookmarkCategoryMapper(); /** * Ensure that a properly formatted JSON representation of a bookmark category is correctly converted into a * {@link BookmarkCategory} object. * * @throws Exception Any exceptions thrown in test */ @Test public void parseBookmarkCategory() throws Exception { final JSONObject bookmarkCategoryJSON = readJSONFile("/bookmark-category.json");
final BookmarkCategory bookmarkCategory = mapper.map(bookmarkCategoryJSON);
Sonoport/freesound-java
src/test/java/com/sonoport/freesound/response/mapping/UploadedSoundDetailsMapperTest.java
// Path: src/main/java/com/sonoport/freesound/response/UploadedSoundDetails.java // public class UploadedSoundDetails { // // /** Detail message received. */ // private String detail; // // /** Id of the uploaded sound. */ // private Integer id; // // /** Filename of the uploaded sound. */ // private String filename; // // /** // * @return the detail // */ // public String getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(final String detail) { // this.detail = detail; // } // // /** // * @return the id // */ // public Integer getId() { // return id; // } // // /** // * @param id the id to set // */ // public void setId(final Integer id) { // this.id = id; // } // // /** // * @return the filename // */ // public String getFilename() { // return filename; // } // // /** // * @param filename the filename to set // */ // public void setFilename(final String filename) { // this.filename = filename; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.json.JSONObject; import org.junit.Test; import com.sonoport.freesound.response.UploadedSoundDetails;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.response.mapping; /** * Unit tests to ensure the correct operation of {@link UploadedSoundDetailsMapper}. * * Test data can be found at: * <code>/src/test/resources/uploaded-described-sound.json</code> * <code>/src/test/resources/uploaded-undescribed-sound.json</code> */ public class UploadedSoundDetailsMapperTest extends MapperTest { /** Detail message in 'described sound' response. */ private static final String DESCRIBED_SOUND_DETAIL = "Audio file successfully uploaded and described (now pending processing and moderation)"; /** Sound id in 'described sound' response. */ private static final Integer DESCRIBED_SOUND_ID = 12345; /** Detail message in 'undescribed sound' response. */ private static final String UNDESCRIBED_SOUND_DETAIL = "Audio file successfully uploaded (2000 bytes, now pending description)"; /** Sound filename in 'undescribed sound' response. */ private static final String UNDESCRIBED_SOUND_FILENAME = "foo.wav"; /** Instance of {@link UploadedSoundDetailsMapper} to use in tests. */ private final UploadedSoundDetailsMapper mapper = new UploadedSoundDetailsMapper(); /** * Transform the response to uploading a sound with a description. * * @throws Exception Any exceptions thrown in test */ @Test public void transformDescribedUploadedSoundResponse() throws Exception { final JSONObject uploadedSoundJSON = readJSONFile("/uploaded-described-sound.json");
// Path: src/main/java/com/sonoport/freesound/response/UploadedSoundDetails.java // public class UploadedSoundDetails { // // /** Detail message received. */ // private String detail; // // /** Id of the uploaded sound. */ // private Integer id; // // /** Filename of the uploaded sound. */ // private String filename; // // /** // * @return the detail // */ // public String getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(final String detail) { // this.detail = detail; // } // // /** // * @return the id // */ // public Integer getId() { // return id; // } // // /** // * @param id the id to set // */ // public void setId(final Integer id) { // this.id = id; // } // // /** // * @return the filename // */ // public String getFilename() { // return filename; // } // // /** // * @param filename the filename to set // */ // public void setFilename(final String filename) { // this.filename = filename; // } // } // Path: src/test/java/com/sonoport/freesound/response/mapping/UploadedSoundDetailsMapperTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.json.JSONObject; import org.junit.Test; import com.sonoport.freesound.response.UploadedSoundDetails; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.response.mapping; /** * Unit tests to ensure the correct operation of {@link UploadedSoundDetailsMapper}. * * Test data can be found at: * <code>/src/test/resources/uploaded-described-sound.json</code> * <code>/src/test/resources/uploaded-undescribed-sound.json</code> */ public class UploadedSoundDetailsMapperTest extends MapperTest { /** Detail message in 'described sound' response. */ private static final String DESCRIBED_SOUND_DETAIL = "Audio file successfully uploaded and described (now pending processing and moderation)"; /** Sound id in 'described sound' response. */ private static final Integer DESCRIBED_SOUND_ID = 12345; /** Detail message in 'undescribed sound' response. */ private static final String UNDESCRIBED_SOUND_DETAIL = "Audio file successfully uploaded (2000 bytes, now pending description)"; /** Sound filename in 'undescribed sound' response. */ private static final String UNDESCRIBED_SOUND_FILENAME = "foo.wav"; /** Instance of {@link UploadedSoundDetailsMapper} to use in tests. */ private final UploadedSoundDetailsMapper mapper = new UploadedSoundDetailsMapper(); /** * Transform the response to uploading a sound with a description. * * @throws Exception Any exceptions thrown in test */ @Test public void transformDescribedUploadedSoundResponse() throws Exception { final JSONObject uploadedSoundJSON = readJSONFile("/uploaded-described-sound.json");
final UploadedSoundDetails uploadedSoundDetails = mapper.map(uploadedSoundJSON);
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/BinaryResponseQuery.java
// Path: src/main/java/com/sonoport/freesound/response/mapping/InputStreamMapper.java // public class InputStreamMapper extends Mapper<InputStream, InputStream> { // // @Override // public InputStream map(final InputStream source) { // return source; // } // // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.json.JSONException; import org.json.JSONObject; import com.sonoport.freesound.response.mapping.InputStreamMapper;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query; /** * Abstract representation of a {@link Query} that returns a binary response. These queries will return an * {@link InputStream} object representing the binary content returned by the API - it is the responsibility of the * caller to properly close this. */ public abstract class BinaryResponseQuery extends Query<InputStream, InputStream> { /** Error message to return if a non-JSON-formatted error response is received. */ protected static final String JSON_EXCEPTION_MESSAGE = "A non-JSON formatted error response was received"; /** Error message to return if there is a problem processing the {@link InputStream} received. */ protected static final String IO_EXCEPTION_MESSAGE = "An error occurred processing the error response received"; /** * @param httpRequestMethod HTTP method to use for query * @param path Endpoint to submit the query to */ protected BinaryResponseQuery(final HTTPRequestMethod httpRequestMethod, final String path) {
// Path: src/main/java/com/sonoport/freesound/response/mapping/InputStreamMapper.java // public class InputStreamMapper extends Mapper<InputStream, InputStream> { // // @Override // public InputStream map(final InputStream source) { // return source; // } // // } // Path: src/main/java/com/sonoport/freesound/query/BinaryResponseQuery.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.json.JSONException; import org.json.JSONObject; import com.sonoport.freesound.response.mapping.InputStreamMapper; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query; /** * Abstract representation of a {@link Query} that returns a binary response. These queries will return an * {@link InputStream} object representing the binary content returned by the API - it is the responsibility of the * caller to properly close this. */ public abstract class BinaryResponseQuery extends Query<InputStream, InputStream> { /** Error message to return if a non-JSON-formatted error response is received. */ protected static final String JSON_EXCEPTION_MESSAGE = "A non-JSON formatted error response was received"; /** Error message to return if there is a problem processing the {@link InputStream} received. */ protected static final String IO_EXCEPTION_MESSAGE = "An error occurred processing the error response received"; /** * @param httpRequestMethod HTTP method to use for query * @param path Endpoint to submit the query to */ protected BinaryResponseQuery(final HTTPRequestMethod httpRequestMethod, final String path) {
super(httpRequestMethod, path, new InputStreamMapper());
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/sound/SimilarSoundsQuery.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/SoundPagingQuery.java // public abstract class SoundPagingQuery<Q extends SoundPagingQuery<Q>> extends PagingQuery<Q, Sound> { // // /** Name of parameter to include the list of fields to return, if specified. */ // public static final String FIELDS_PARAMETER = "fields"; // // /** The fields to retrieve as part of the query. If values are specified here, only those fields will be returned. // * If no values are specified, freesound will return a default set. */ // private Set<String> fields; // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path The URI path to the API endpoint // */ // protected SoundPagingQuery(final HTTPRequestMethod httpRequestMethod, final String path) { // super(httpRequestMethod, path, new PagingResponseMapper<>(new SoundMapper())); // } // // @Override // public Map<String, Object> getQueryParameters() { // final Map<String, Object> params = super.getQueryParameters(); // // if ((fields != null) && !fields.isEmpty()) { // final StringBuilder fieldsString = new StringBuilder(); // for (final String field : fields) { // fieldsString.append(field.trim()); // fieldsString.append(','); // } // fieldsString.deleteCharAt(fieldsString.lastIndexOf(",")); // // params.put(FIELDS_PARAMETER, fieldsString.toString()); // } // // return params; // } // // /** // * Specify a field to return in the results using the Fluent API approach. Users may specify this method multiple // * times to define the collection of fields they want returning, and/or use // * {@link SoundPagingQuery#includeFields(Set)} to define them as a batch. // * // * @param field The field to include in the results // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeField(final String field) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (field != null) { // this.fields.add(field); // } // // return (Q) this; // } // // /** // * Specify the set of fields to return in the results. Defined using the Fluent API approach. // * // * @param fields The fields to return // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeFields(final Set<String> fields) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (fields != null) { // this.fields.addAll(fields); // } // // return (Q) this; // } // }
import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.SoundPagingQuery;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query used to retrieve a list of sounds similar to the on specified. * * API documentation at: http://www.freesound.org/docs/api/resources_apiv2.html#similar-sounds */ public class SimilarSoundsQuery extends SoundPagingQuery<SimilarSoundsQuery> { /** Route parameter to be replaced with the identifier to retrieve similar sounds for. */ protected static final String SOUND_ID_ROUTE_PARAMETER = "sound_id"; /** Path to the API endpoint. */ private static final String PATH = String.format("/sounds/{%s}/similar/", SOUND_ID_ROUTE_PARAMETER); /** Identifier of the sound to retrieve similar sounds for. */ private final int soundId; /** * @param soundId Identifier of the sound to retrieve similar sounds for */ public SimilarSoundsQuery(final int soundId) {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/SoundPagingQuery.java // public abstract class SoundPagingQuery<Q extends SoundPagingQuery<Q>> extends PagingQuery<Q, Sound> { // // /** Name of parameter to include the list of fields to return, if specified. */ // public static final String FIELDS_PARAMETER = "fields"; // // /** The fields to retrieve as part of the query. If values are specified here, only those fields will be returned. // * If no values are specified, freesound will return a default set. */ // private Set<String> fields; // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path The URI path to the API endpoint // */ // protected SoundPagingQuery(final HTTPRequestMethod httpRequestMethod, final String path) { // super(httpRequestMethod, path, new PagingResponseMapper<>(new SoundMapper())); // } // // @Override // public Map<String, Object> getQueryParameters() { // final Map<String, Object> params = super.getQueryParameters(); // // if ((fields != null) && !fields.isEmpty()) { // final StringBuilder fieldsString = new StringBuilder(); // for (final String field : fields) { // fieldsString.append(field.trim()); // fieldsString.append(','); // } // fieldsString.deleteCharAt(fieldsString.lastIndexOf(",")); // // params.put(FIELDS_PARAMETER, fieldsString.toString()); // } // // return params; // } // // /** // * Specify a field to return in the results using the Fluent API approach. Users may specify this method multiple // * times to define the collection of fields they want returning, and/or use // * {@link SoundPagingQuery#includeFields(Set)} to define them as a batch. // * // * @param field The field to include in the results // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeField(final String field) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (field != null) { // this.fields.add(field); // } // // return (Q) this; // } // // /** // * Specify the set of fields to return in the results. Defined using the Fluent API approach. // * // * @param fields The fields to return // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeFields(final Set<String> fields) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (fields != null) { // this.fields.addAll(fields); // } // // return (Q) this; // } // } // Path: src/main/java/com/sonoport/freesound/query/sound/SimilarSoundsQuery.java import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.SoundPagingQuery; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query used to retrieve a list of sounds similar to the on specified. * * API documentation at: http://www.freesound.org/docs/api/resources_apiv2.html#similar-sounds */ public class SimilarSoundsQuery extends SoundPagingQuery<SimilarSoundsQuery> { /** Route parameter to be replaced with the identifier to retrieve similar sounds for. */ protected static final String SOUND_ID_ROUTE_PARAMETER = "sound_id"; /** Path to the API endpoint. */ private static final String PATH = String.format("/sounds/{%s}/similar/", SOUND_ID_ROUTE_PARAMETER); /** Identifier of the sound to retrieve similar sounds for. */ private final int soundId; /** * @param soundId Identifier of the sound to retrieve similar sounds for */ public SimilarSoundsQuery(final int soundId) {
super(HTTPRequestMethod.GET, PATH);
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/user/UserBookmarkCategorySoundsQuery.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/SoundPagingQuery.java // public abstract class SoundPagingQuery<Q extends SoundPagingQuery<Q>> extends PagingQuery<Q, Sound> { // // /** Name of parameter to include the list of fields to return, if specified. */ // public static final String FIELDS_PARAMETER = "fields"; // // /** The fields to retrieve as part of the query. If values are specified here, only those fields will be returned. // * If no values are specified, freesound will return a default set. */ // private Set<String> fields; // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path The URI path to the API endpoint // */ // protected SoundPagingQuery(final HTTPRequestMethod httpRequestMethod, final String path) { // super(httpRequestMethod, path, new PagingResponseMapper<>(new SoundMapper())); // } // // @Override // public Map<String, Object> getQueryParameters() { // final Map<String, Object> params = super.getQueryParameters(); // // if ((fields != null) && !fields.isEmpty()) { // final StringBuilder fieldsString = new StringBuilder(); // for (final String field : fields) { // fieldsString.append(field.trim()); // fieldsString.append(','); // } // fieldsString.deleteCharAt(fieldsString.lastIndexOf(",")); // // params.put(FIELDS_PARAMETER, fieldsString.toString()); // } // // return params; // } // // /** // * Specify a field to return in the results using the Fluent API approach. Users may specify this method multiple // * times to define the collection of fields they want returning, and/or use // * {@link SoundPagingQuery#includeFields(Set)} to define them as a batch. // * // * @param field The field to include in the results // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeField(final String field) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (field != null) { // this.fields.add(field); // } // // return (Q) this; // } // // /** // * Specify the set of fields to return in the results. Defined using the Fluent API approach. // * // * @param fields The fields to return // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeFields(final Set<String> fields) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (fields != null) { // this.fields.addAll(fields); // } // // return (Q) this; // } // }
import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.SoundPagingQuery;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.user; /** * Query used to retrieve list of all sounds bookmarked under a particular category by a given user. * * API documentation at: http://www.freesound.org/docs/api/resources_apiv2.html#user-bookmark-category-sounds */ public class UserBookmarkCategorySoundsQuery extends SoundPagingQuery<UserBookmarkCategorySoundsQuery> { /** Route parameter to be replaced with user name of user to retrieve sounds for. */ protected static final String USERNAME_ROUTE_PARAMETER = "username"; /** Route parameter to be replaced with category id to retrieve sounds for. */ protected static final String BOOKMARK_CATEGORY_ID_ROUTE_PARAMETER = "bookmark_category_id"; /** Path to API endpoint. */ private static final String PATH = String.format( "/users/{%s}/bookmark_categories/{%s}/sounds/", USERNAME_ROUTE_PARAMETER, BOOKMARK_CATEGORY_ID_ROUTE_PARAMETER); /** The username of the user to retrieve sounds in category for. */ private final String username; /** Identifier of the bookmark category to retrieve sounds for. */ private final int bookmarkCategoryId; /** * @param username Username of the user to retrieve sounds in category for * @param bookmarkCategoryId Identifier of the bookmark category to retrieve sounds for */ public UserBookmarkCategorySoundsQuery(final String username, final int bookmarkCategoryId) {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/SoundPagingQuery.java // public abstract class SoundPagingQuery<Q extends SoundPagingQuery<Q>> extends PagingQuery<Q, Sound> { // // /** Name of parameter to include the list of fields to return, if specified. */ // public static final String FIELDS_PARAMETER = "fields"; // // /** The fields to retrieve as part of the query. If values are specified here, only those fields will be returned. // * If no values are specified, freesound will return a default set. */ // private Set<String> fields; // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path The URI path to the API endpoint // */ // protected SoundPagingQuery(final HTTPRequestMethod httpRequestMethod, final String path) { // super(httpRequestMethod, path, new PagingResponseMapper<>(new SoundMapper())); // } // // @Override // public Map<String, Object> getQueryParameters() { // final Map<String, Object> params = super.getQueryParameters(); // // if ((fields != null) && !fields.isEmpty()) { // final StringBuilder fieldsString = new StringBuilder(); // for (final String field : fields) { // fieldsString.append(field.trim()); // fieldsString.append(','); // } // fieldsString.deleteCharAt(fieldsString.lastIndexOf(",")); // // params.put(FIELDS_PARAMETER, fieldsString.toString()); // } // // return params; // } // // /** // * Specify a field to return in the results using the Fluent API approach. Users may specify this method multiple // * times to define the collection of fields they want returning, and/or use // * {@link SoundPagingQuery#includeFields(Set)} to define them as a batch. // * // * @param field The field to include in the results // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeField(final String field) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (field != null) { // this.fields.add(field); // } // // return (Q) this; // } // // /** // * Specify the set of fields to return in the results. Defined using the Fluent API approach. // * // * @param fields The fields to return // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeFields(final Set<String> fields) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (fields != null) { // this.fields.addAll(fields); // } // // return (Q) this; // } // } // Path: src/main/java/com/sonoport/freesound/query/user/UserBookmarkCategorySoundsQuery.java import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.SoundPagingQuery; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.user; /** * Query used to retrieve list of all sounds bookmarked under a particular category by a given user. * * API documentation at: http://www.freesound.org/docs/api/resources_apiv2.html#user-bookmark-category-sounds */ public class UserBookmarkCategorySoundsQuery extends SoundPagingQuery<UserBookmarkCategorySoundsQuery> { /** Route parameter to be replaced with user name of user to retrieve sounds for. */ protected static final String USERNAME_ROUTE_PARAMETER = "username"; /** Route parameter to be replaced with category id to retrieve sounds for. */ protected static final String BOOKMARK_CATEGORY_ID_ROUTE_PARAMETER = "bookmark_category_id"; /** Path to API endpoint. */ private static final String PATH = String.format( "/users/{%s}/bookmark_categories/{%s}/sounds/", USERNAME_ROUTE_PARAMETER, BOOKMARK_CATEGORY_ID_ROUTE_PARAMETER); /** The username of the user to retrieve sounds in category for. */ private final String username; /** Identifier of the bookmark category to retrieve sounds for. */ private final int bookmarkCategoryId; /** * @param username Username of the user to retrieve sounds in category for * @param bookmarkCategoryId Identifier of the bookmark category to retrieve sounds for */ public UserBookmarkCategorySoundsQuery(final String username, final int bookmarkCategoryId) {
super(HTTPRequestMethod.GET, PATH);
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/pack/PackSoundsQuery.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/SoundPagingQuery.java // public abstract class SoundPagingQuery<Q extends SoundPagingQuery<Q>> extends PagingQuery<Q, Sound> { // // /** Name of parameter to include the list of fields to return, if specified. */ // public static final String FIELDS_PARAMETER = "fields"; // // /** The fields to retrieve as part of the query. If values are specified here, only those fields will be returned. // * If no values are specified, freesound will return a default set. */ // private Set<String> fields; // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path The URI path to the API endpoint // */ // protected SoundPagingQuery(final HTTPRequestMethod httpRequestMethod, final String path) { // super(httpRequestMethod, path, new PagingResponseMapper<>(new SoundMapper())); // } // // @Override // public Map<String, Object> getQueryParameters() { // final Map<String, Object> params = super.getQueryParameters(); // // if ((fields != null) && !fields.isEmpty()) { // final StringBuilder fieldsString = new StringBuilder(); // for (final String field : fields) { // fieldsString.append(field.trim()); // fieldsString.append(','); // } // fieldsString.deleteCharAt(fieldsString.lastIndexOf(",")); // // params.put(FIELDS_PARAMETER, fieldsString.toString()); // } // // return params; // } // // /** // * Specify a field to return in the results using the Fluent API approach. Users may specify this method multiple // * times to define the collection of fields they want returning, and/or use // * {@link SoundPagingQuery#includeFields(Set)} to define them as a batch. // * // * @param field The field to include in the results // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeField(final String field) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (field != null) { // this.fields.add(field); // } // // return (Q) this; // } // // /** // * Specify the set of fields to return in the results. Defined using the Fluent API approach. // * // * @param fields The fields to return // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeFields(final Set<String> fields) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (fields != null) { // this.fields.addAll(fields); // } // // return (Q) this; // } // }
import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.SoundPagingQuery;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.pack; /** * Query used to return details of all sounds in a given pack. * * API documentation at: http://www.freesound.org/docs/api/resources_apiv2.html#pack-sounds */ public class PackSoundsQuery extends SoundPagingQuery<PackSoundsQuery> { /** Route parameter to substitute with pack identifier. */ protected static final String PACK_ID_ROUTE_PARAMETER = "pack_id"; /** Path to API endpoint. */ private static final String PATH = String.format("/packs/{%s}/sounds/", PACK_ID_ROUTE_PARAMETER); /** Identifier of pack to retrieve sounds for. */ private final int packId; /** * @param packId Identifier of pack to retrieve sounds for */ public PackSoundsQuery(final int packId) {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/SoundPagingQuery.java // public abstract class SoundPagingQuery<Q extends SoundPagingQuery<Q>> extends PagingQuery<Q, Sound> { // // /** Name of parameter to include the list of fields to return, if specified. */ // public static final String FIELDS_PARAMETER = "fields"; // // /** The fields to retrieve as part of the query. If values are specified here, only those fields will be returned. // * If no values are specified, freesound will return a default set. */ // private Set<String> fields; // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path The URI path to the API endpoint // */ // protected SoundPagingQuery(final HTTPRequestMethod httpRequestMethod, final String path) { // super(httpRequestMethod, path, new PagingResponseMapper<>(new SoundMapper())); // } // // @Override // public Map<String, Object> getQueryParameters() { // final Map<String, Object> params = super.getQueryParameters(); // // if ((fields != null) && !fields.isEmpty()) { // final StringBuilder fieldsString = new StringBuilder(); // for (final String field : fields) { // fieldsString.append(field.trim()); // fieldsString.append(','); // } // fieldsString.deleteCharAt(fieldsString.lastIndexOf(",")); // // params.put(FIELDS_PARAMETER, fieldsString.toString()); // } // // return params; // } // // /** // * Specify a field to return in the results using the Fluent API approach. Users may specify this method multiple // * times to define the collection of fields they want returning, and/or use // * {@link SoundPagingQuery#includeFields(Set)} to define them as a batch. // * // * @param field The field to include in the results // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeField(final String field) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (field != null) { // this.fields.add(field); // } // // return (Q) this; // } // // /** // * Specify the set of fields to return in the results. Defined using the Fluent API approach. // * // * @param fields The fields to return // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeFields(final Set<String> fields) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (fields != null) { // this.fields.addAll(fields); // } // // return (Q) this; // } // } // Path: src/main/java/com/sonoport/freesound/query/pack/PackSoundsQuery.java import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.SoundPagingQuery; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.pack; /** * Query used to return details of all sounds in a given pack. * * API documentation at: http://www.freesound.org/docs/api/resources_apiv2.html#pack-sounds */ public class PackSoundsQuery extends SoundPagingQuery<PackSoundsQuery> { /** Route parameter to substitute with pack identifier. */ protected static final String PACK_ID_ROUTE_PARAMETER = "pack_id"; /** Path to API endpoint. */ private static final String PATH = String.format("/packs/{%s}/sounds/", PACK_ID_ROUTE_PARAMETER); /** Identifier of pack to retrieve sounds for. */ private final int packId; /** * @param packId Identifier of pack to retrieve sounds for */ public PackSoundsQuery(final int packId) {
super(HTTPRequestMethod.GET, PATH);
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/sound/BookmarkSound.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/DetailStringMapper.java // public class DetailStringMapper extends Mapper<JSONObject, String> { // // @Override // public String map(final JSONObject source) { // return extractFieldValue(source, "detail", String.class); // } // // }
import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.mapping.DetailStringMapper;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Class that allows the currently authorised user to bookmark a sound. By default the bookmark will use the name of the * sound and be uncategorised - this can be overridden by using the {@link #name(String)} and {@link #category(String)} * methods. * * API documentation: http://www.freesound.org/docs/api/resources_apiv2.html#bookmark-sound-oauth2-required * * Note that there is currently a bug in the Freesound API that means both name and category of the bookmark must be * specified at present (despite the documentation stating they are optional). A bug has been raised on GitHub covering * this issue: https://github.com/MTG/freesound/issues/642. */ public class BookmarkSound extends JSONResponseQuery<String> implements OAuthQuery { /** Route parameter to be replaced with the identifier of the sound to be bookmarked. */ protected static final String SOUND_ID_ROUTE_PARAMETER = "sound_id"; /** Path to the API endpoint. */ private static final String PATH = String.format("/sounds/{%s}/bookmark/", SOUND_ID_ROUTE_PARAMETER); /** Parameter to pass the (optional) name of the bookmark on as. */ protected static final String BOOKMARK_NAME_PARAMETER = "name"; /** Parameter to pass the (optional) category of the bookmark on as. */ protected static final String BOOKMARK_CATEGORY_PARAMETER = "category"; /** Identifier of the sound to bookmark. */ private final int soundId; /** Name to give the bookmark. */ private String bookmarkName; /** Category to group the bookmark under. */ private String bookmarkCategory; /** OAuth2 bearer token to present with request. */ private final String oauthToken; /** * @param soundId Identifier of sound to bookmark * @param oauthToken OAuth token to present with request */ public BookmarkSound(final int soundId, final String oauthToken) { this(soundId, oauthToken, null, null); } /** * @param soundId Identifier of sound to bookmark * @param oauthToken OAuth token to present with request * @param bookmarkName Name to give the bookmark * @param bookmarkCategory Category to assign the bookmark to */ public BookmarkSound( final int soundId, final String oauthToken, final String bookmarkName, final String bookmarkCategory) {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/DetailStringMapper.java // public class DetailStringMapper extends Mapper<JSONObject, String> { // // @Override // public String map(final JSONObject source) { // return extractFieldValue(source, "detail", String.class); // } // // } // Path: src/main/java/com/sonoport/freesound/query/sound/BookmarkSound.java import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.mapping.DetailStringMapper; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Class that allows the currently authorised user to bookmark a sound. By default the bookmark will use the name of the * sound and be uncategorised - this can be overridden by using the {@link #name(String)} and {@link #category(String)} * methods. * * API documentation: http://www.freesound.org/docs/api/resources_apiv2.html#bookmark-sound-oauth2-required * * Note that there is currently a bug in the Freesound API that means both name and category of the bookmark must be * specified at present (despite the documentation stating they are optional). A bug has been raised on GitHub covering * this issue: https://github.com/MTG/freesound/issues/642. */ public class BookmarkSound extends JSONResponseQuery<String> implements OAuthQuery { /** Route parameter to be replaced with the identifier of the sound to be bookmarked. */ protected static final String SOUND_ID_ROUTE_PARAMETER = "sound_id"; /** Path to the API endpoint. */ private static final String PATH = String.format("/sounds/{%s}/bookmark/", SOUND_ID_ROUTE_PARAMETER); /** Parameter to pass the (optional) name of the bookmark on as. */ protected static final String BOOKMARK_NAME_PARAMETER = "name"; /** Parameter to pass the (optional) category of the bookmark on as. */ protected static final String BOOKMARK_CATEGORY_PARAMETER = "category"; /** Identifier of the sound to bookmark. */ private final int soundId; /** Name to give the bookmark. */ private String bookmarkName; /** Category to group the bookmark under. */ private String bookmarkCategory; /** OAuth2 bearer token to present with request. */ private final String oauthToken; /** * @param soundId Identifier of sound to bookmark * @param oauthToken OAuth token to present with request */ public BookmarkSound(final int soundId, final String oauthToken) { this(soundId, oauthToken, null, null); } /** * @param soundId Identifier of sound to bookmark * @param oauthToken OAuth token to present with request * @param bookmarkName Name to give the bookmark * @param bookmarkCategory Category to assign the bookmark to */ public BookmarkSound( final int soundId, final String oauthToken, final String bookmarkName, final String bookmarkCategory) {
super(HTTPRequestMethod.POST, PATH, new DetailStringMapper());
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/sound/BookmarkSound.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/DetailStringMapper.java // public class DetailStringMapper extends Mapper<JSONObject, String> { // // @Override // public String map(final JSONObject source) { // return extractFieldValue(source, "detail", String.class); // } // // }
import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.mapping.DetailStringMapper;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Class that allows the currently authorised user to bookmark a sound. By default the bookmark will use the name of the * sound and be uncategorised - this can be overridden by using the {@link #name(String)} and {@link #category(String)} * methods. * * API documentation: http://www.freesound.org/docs/api/resources_apiv2.html#bookmark-sound-oauth2-required * * Note that there is currently a bug in the Freesound API that means both name and category of the bookmark must be * specified at present (despite the documentation stating they are optional). A bug has been raised on GitHub covering * this issue: https://github.com/MTG/freesound/issues/642. */ public class BookmarkSound extends JSONResponseQuery<String> implements OAuthQuery { /** Route parameter to be replaced with the identifier of the sound to be bookmarked. */ protected static final String SOUND_ID_ROUTE_PARAMETER = "sound_id"; /** Path to the API endpoint. */ private static final String PATH = String.format("/sounds/{%s}/bookmark/", SOUND_ID_ROUTE_PARAMETER); /** Parameter to pass the (optional) name of the bookmark on as. */ protected static final String BOOKMARK_NAME_PARAMETER = "name"; /** Parameter to pass the (optional) category of the bookmark on as. */ protected static final String BOOKMARK_CATEGORY_PARAMETER = "category"; /** Identifier of the sound to bookmark. */ private final int soundId; /** Name to give the bookmark. */ private String bookmarkName; /** Category to group the bookmark under. */ private String bookmarkCategory; /** OAuth2 bearer token to present with request. */ private final String oauthToken; /** * @param soundId Identifier of sound to bookmark * @param oauthToken OAuth token to present with request */ public BookmarkSound(final int soundId, final String oauthToken) { this(soundId, oauthToken, null, null); } /** * @param soundId Identifier of sound to bookmark * @param oauthToken OAuth token to present with request * @param bookmarkName Name to give the bookmark * @param bookmarkCategory Category to assign the bookmark to */ public BookmarkSound( final int soundId, final String oauthToken, final String bookmarkName, final String bookmarkCategory) {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/DetailStringMapper.java // public class DetailStringMapper extends Mapper<JSONObject, String> { // // @Override // public String map(final JSONObject source) { // return extractFieldValue(source, "detail", String.class); // } // // } // Path: src/main/java/com/sonoport/freesound/query/sound/BookmarkSound.java import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.mapping.DetailStringMapper; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Class that allows the currently authorised user to bookmark a sound. By default the bookmark will use the name of the * sound and be uncategorised - this can be overridden by using the {@link #name(String)} and {@link #category(String)} * methods. * * API documentation: http://www.freesound.org/docs/api/resources_apiv2.html#bookmark-sound-oauth2-required * * Note that there is currently a bug in the Freesound API that means both name and category of the bookmark must be * specified at present (despite the documentation stating they are optional). A bug has been raised on GitHub covering * this issue: https://github.com/MTG/freesound/issues/642. */ public class BookmarkSound extends JSONResponseQuery<String> implements OAuthQuery { /** Route parameter to be replaced with the identifier of the sound to be bookmarked. */ protected static final String SOUND_ID_ROUTE_PARAMETER = "sound_id"; /** Path to the API endpoint. */ private static final String PATH = String.format("/sounds/{%s}/bookmark/", SOUND_ID_ROUTE_PARAMETER); /** Parameter to pass the (optional) name of the bookmark on as. */ protected static final String BOOKMARK_NAME_PARAMETER = "name"; /** Parameter to pass the (optional) category of the bookmark on as. */ protected static final String BOOKMARK_CATEGORY_PARAMETER = "category"; /** Identifier of the sound to bookmark. */ private final int soundId; /** Name to give the bookmark. */ private String bookmarkName; /** Category to group the bookmark under. */ private String bookmarkCategory; /** OAuth2 bearer token to present with request. */ private final String oauthToken; /** * @param soundId Identifier of sound to bookmark * @param oauthToken OAuth token to present with request */ public BookmarkSound(final int soundId, final String oauthToken) { this(soundId, oauthToken, null, null); } /** * @param soundId Identifier of sound to bookmark * @param oauthToken OAuth token to present with request * @param bookmarkName Name to give the bookmark * @param bookmarkCategory Category to assign the bookmark to */ public BookmarkSound( final int soundId, final String oauthToken, final String bookmarkName, final String bookmarkCategory) {
super(HTTPRequestMethod.POST, PATH, new DetailStringMapper());
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/other/MeQuery.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/CurrentUser.java // public class CurrentUser extends User { // // /** Unique identifier associated with the user. */ // private Integer uniqueIdentifier; // // /** Email address of the user. */ // private String email; // // /** // * @return the uniqueIdentifier // */ // public Integer getUniqueIdentifier() { // return uniqueIdentifier; // } // // /** // * @param uniqueIdentifier the uniqueIdentifier to set // */ // public void setUniqueIdentifier(final Integer uniqueIdentifier) { // this.uniqueIdentifier = uniqueIdentifier; // } // // /** // * @return the email // */ // public String getEmail() { // return email; // } // // /** // * @param email the email to set // */ // public void setEmail(final String email) { // this.email = email; // } // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/CurrentUserMapper.java // public class CurrentUserMapper extends AbstractUserMapper<CurrentUser> { // // /** // * No-arg constructor. // */ // public CurrentUserMapper() { // super(CurrentUser.class); // } // // @Override // public CurrentUser map(final JSONObject source) { // final CurrentUser currentUser = super.map(source); // // currentUser.setEmail(extractFieldValue(source, "email", String.class)); // currentUser.setUniqueIdentifier(extractFieldValue(source, "unique_id", Integer.class)); // // return currentUser; // } // // }
import java.util.Collections; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.CurrentUser; import com.sonoport.freesound.response.mapping.CurrentUserMapper;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.other; /** * Query used to retrieve full details of the currently authorised user. */ public class MeQuery extends JSONResponseQuery<CurrentUser> implements OAuthQuery { /** The OAuth bearer token to be presented with the request. */ private final String oauthToken; /** * @param oauthToken The OAuth token associated with the user */ public MeQuery(final String oauthToken) {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/CurrentUser.java // public class CurrentUser extends User { // // /** Unique identifier associated with the user. */ // private Integer uniqueIdentifier; // // /** Email address of the user. */ // private String email; // // /** // * @return the uniqueIdentifier // */ // public Integer getUniqueIdentifier() { // return uniqueIdentifier; // } // // /** // * @param uniqueIdentifier the uniqueIdentifier to set // */ // public void setUniqueIdentifier(final Integer uniqueIdentifier) { // this.uniqueIdentifier = uniqueIdentifier; // } // // /** // * @return the email // */ // public String getEmail() { // return email; // } // // /** // * @param email the email to set // */ // public void setEmail(final String email) { // this.email = email; // } // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/CurrentUserMapper.java // public class CurrentUserMapper extends AbstractUserMapper<CurrentUser> { // // /** // * No-arg constructor. // */ // public CurrentUserMapper() { // super(CurrentUser.class); // } // // @Override // public CurrentUser map(final JSONObject source) { // final CurrentUser currentUser = super.map(source); // // currentUser.setEmail(extractFieldValue(source, "email", String.class)); // currentUser.setUniqueIdentifier(extractFieldValue(source, "unique_id", Integer.class)); // // return currentUser; // } // // } // Path: src/main/java/com/sonoport/freesound/query/other/MeQuery.java import java.util.Collections; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.CurrentUser; import com.sonoport.freesound.response.mapping.CurrentUserMapper; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.other; /** * Query used to retrieve full details of the currently authorised user. */ public class MeQuery extends JSONResponseQuery<CurrentUser> implements OAuthQuery { /** The OAuth bearer token to be presented with the request. */ private final String oauthToken; /** * @param oauthToken The OAuth token associated with the user */ public MeQuery(final String oauthToken) {
super(HTTPRequestMethod.GET, "/me/", new CurrentUserMapper());
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/other/MeQuery.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/CurrentUser.java // public class CurrentUser extends User { // // /** Unique identifier associated with the user. */ // private Integer uniqueIdentifier; // // /** Email address of the user. */ // private String email; // // /** // * @return the uniqueIdentifier // */ // public Integer getUniqueIdentifier() { // return uniqueIdentifier; // } // // /** // * @param uniqueIdentifier the uniqueIdentifier to set // */ // public void setUniqueIdentifier(final Integer uniqueIdentifier) { // this.uniqueIdentifier = uniqueIdentifier; // } // // /** // * @return the email // */ // public String getEmail() { // return email; // } // // /** // * @param email the email to set // */ // public void setEmail(final String email) { // this.email = email; // } // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/CurrentUserMapper.java // public class CurrentUserMapper extends AbstractUserMapper<CurrentUser> { // // /** // * No-arg constructor. // */ // public CurrentUserMapper() { // super(CurrentUser.class); // } // // @Override // public CurrentUser map(final JSONObject source) { // final CurrentUser currentUser = super.map(source); // // currentUser.setEmail(extractFieldValue(source, "email", String.class)); // currentUser.setUniqueIdentifier(extractFieldValue(source, "unique_id", Integer.class)); // // return currentUser; // } // // }
import java.util.Collections; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.CurrentUser; import com.sonoport.freesound.response.mapping.CurrentUserMapper;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.other; /** * Query used to retrieve full details of the currently authorised user. */ public class MeQuery extends JSONResponseQuery<CurrentUser> implements OAuthQuery { /** The OAuth bearer token to be presented with the request. */ private final String oauthToken; /** * @param oauthToken The OAuth token associated with the user */ public MeQuery(final String oauthToken) {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/CurrentUser.java // public class CurrentUser extends User { // // /** Unique identifier associated with the user. */ // private Integer uniqueIdentifier; // // /** Email address of the user. */ // private String email; // // /** // * @return the uniqueIdentifier // */ // public Integer getUniqueIdentifier() { // return uniqueIdentifier; // } // // /** // * @param uniqueIdentifier the uniqueIdentifier to set // */ // public void setUniqueIdentifier(final Integer uniqueIdentifier) { // this.uniqueIdentifier = uniqueIdentifier; // } // // /** // * @return the email // */ // public String getEmail() { // return email; // } // // /** // * @param email the email to set // */ // public void setEmail(final String email) { // this.email = email; // } // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/CurrentUserMapper.java // public class CurrentUserMapper extends AbstractUserMapper<CurrentUser> { // // /** // * No-arg constructor. // */ // public CurrentUserMapper() { // super(CurrentUser.class); // } // // @Override // public CurrentUser map(final JSONObject source) { // final CurrentUser currentUser = super.map(source); // // currentUser.setEmail(extractFieldValue(source, "email", String.class)); // currentUser.setUniqueIdentifier(extractFieldValue(source, "unique_id", Integer.class)); // // return currentUser; // } // // } // Path: src/main/java/com/sonoport/freesound/query/other/MeQuery.java import java.util.Collections; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.CurrentUser; import com.sonoport.freesound.response.mapping.CurrentUserMapper; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.other; /** * Query used to retrieve full details of the currently authorised user. */ public class MeQuery extends JSONResponseQuery<CurrentUser> implements OAuthQuery { /** The OAuth bearer token to be presented with the request. */ private final String oauthToken; /** * @param oauthToken The OAuth token associated with the user */ public MeQuery(final String oauthToken) {
super(HTTPRequestMethod.GET, "/me/", new CurrentUserMapper());
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/user/UserSoundsQuery.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/SoundPagingQuery.java // public abstract class SoundPagingQuery<Q extends SoundPagingQuery<Q>> extends PagingQuery<Q, Sound> { // // /** Name of parameter to include the list of fields to return, if specified. */ // public static final String FIELDS_PARAMETER = "fields"; // // /** The fields to retrieve as part of the query. If values are specified here, only those fields will be returned. // * If no values are specified, freesound will return a default set. */ // private Set<String> fields; // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path The URI path to the API endpoint // */ // protected SoundPagingQuery(final HTTPRequestMethod httpRequestMethod, final String path) { // super(httpRequestMethod, path, new PagingResponseMapper<>(new SoundMapper())); // } // // @Override // public Map<String, Object> getQueryParameters() { // final Map<String, Object> params = super.getQueryParameters(); // // if ((fields != null) && !fields.isEmpty()) { // final StringBuilder fieldsString = new StringBuilder(); // for (final String field : fields) { // fieldsString.append(field.trim()); // fieldsString.append(','); // } // fieldsString.deleteCharAt(fieldsString.lastIndexOf(",")); // // params.put(FIELDS_PARAMETER, fieldsString.toString()); // } // // return params; // } // // /** // * Specify a field to return in the results using the Fluent API approach. Users may specify this method multiple // * times to define the collection of fields they want returning, and/or use // * {@link SoundPagingQuery#includeFields(Set)} to define them as a batch. // * // * @param field The field to include in the results // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeField(final String field) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (field != null) { // this.fields.add(field); // } // // return (Q) this; // } // // /** // * Specify the set of fields to return in the results. Defined using the Fluent API approach. // * // * @param fields The fields to return // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeFields(final Set<String> fields) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (fields != null) { // this.fields.addAll(fields); // } // // return (Q) this; // } // }
import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.SoundPagingQuery;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.user; /** * Query used to retrieve all the sounds owned by a particular user. */ public class UserSoundsQuery extends SoundPagingQuery<UserSoundsQuery> { /** Name of the parameter in the path to replace with the username of owner of the sounds to retrieve. */ protected static final String USERNAME_ROUTE_PARAMETER = "username"; /** Path to the API endpoint. */ private static final String PATH = String.format("/users/{%s}/sounds/", USERNAME_ROUTE_PARAMETER); /** The username of the owner of the sounds to retrieve. */ private final String username; /** * @param username Username of the owner of the sounds to retrieve */ public UserSoundsQuery(final String username) {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/SoundPagingQuery.java // public abstract class SoundPagingQuery<Q extends SoundPagingQuery<Q>> extends PagingQuery<Q, Sound> { // // /** Name of parameter to include the list of fields to return, if specified. */ // public static final String FIELDS_PARAMETER = "fields"; // // /** The fields to retrieve as part of the query. If values are specified here, only those fields will be returned. // * If no values are specified, freesound will return a default set. */ // private Set<String> fields; // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path The URI path to the API endpoint // */ // protected SoundPagingQuery(final HTTPRequestMethod httpRequestMethod, final String path) { // super(httpRequestMethod, path, new PagingResponseMapper<>(new SoundMapper())); // } // // @Override // public Map<String, Object> getQueryParameters() { // final Map<String, Object> params = super.getQueryParameters(); // // if ((fields != null) && !fields.isEmpty()) { // final StringBuilder fieldsString = new StringBuilder(); // for (final String field : fields) { // fieldsString.append(field.trim()); // fieldsString.append(','); // } // fieldsString.deleteCharAt(fieldsString.lastIndexOf(",")); // // params.put(FIELDS_PARAMETER, fieldsString.toString()); // } // // return params; // } // // /** // * Specify a field to return in the results using the Fluent API approach. Users may specify this method multiple // * times to define the collection of fields they want returning, and/or use // * {@link SoundPagingQuery#includeFields(Set)} to define them as a batch. // * // * @param field The field to include in the results // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeField(final String field) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (field != null) { // this.fields.add(field); // } // // return (Q) this; // } // // /** // * Specify the set of fields to return in the results. Defined using the Fluent API approach. // * // * @param fields The fields to return // * @return The current query // */ // @SuppressWarnings("unchecked") // public Q includeFields(final Set<String> fields) { // if (this.fields == null) { // this.fields = new HashSet<>(); // } // // if (fields != null) { // this.fields.addAll(fields); // } // // return (Q) this; // } // } // Path: src/main/java/com/sonoport/freesound/query/user/UserSoundsQuery.java import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.SoundPagingQuery; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.user; /** * Query used to retrieve all the sounds owned by a particular user. */ public class UserSoundsQuery extends SoundPagingQuery<UserSoundsQuery> { /** Name of the parameter in the path to replace with the username of owner of the sounds to retrieve. */ protected static final String USERNAME_ROUTE_PARAMETER = "username"; /** Path to the API endpoint. */ private static final String PATH = String.format("/users/{%s}/sounds/", USERNAME_ROUTE_PARAMETER); /** The username of the owner of the sounds to retrieve. */ private final String username; /** * @param username Username of the owner of the sounds to retrieve */ public UserSoundsQuery(final String username) {
super(HTTPRequestMethod.GET, PATH);
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/pack/DownloadPack.java
// Path: src/main/java/com/sonoport/freesound/query/BinaryResponseQuery.java // public abstract class BinaryResponseQuery extends Query<InputStream, InputStream> { // // /** Error message to return if a non-JSON-formatted error response is received. */ // protected static final String JSON_EXCEPTION_MESSAGE = "A non-JSON formatted error response was received"; // // /** Error message to return if there is a problem processing the {@link InputStream} received. */ // protected static final String IO_EXCEPTION_MESSAGE = "An error occurred processing the error response received"; // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // */ // protected BinaryResponseQuery(final HTTPRequestMethod httpRequestMethod, final String path) { // super(httpRequestMethod, path, new InputStreamMapper()); // } // // @Override // protected String extractErrorMessage(final InputStream freesoundResponse) { // try { // final BufferedReader streamReader = new BufferedReader(new InputStreamReader(freesoundResponse, "UTF-8")); // final StringBuilder responseStrBuilder = new StringBuilder(); // // String streamContent; // while ((streamContent = streamReader.readLine()) != null) { // responseStrBuilder.append(streamContent); // } // // final JSONObject jsonResponse = new JSONObject(responseStrBuilder.toString()); // // return jsonResponse.getString("detail"); // } catch (final JSONException e) { // e.printStackTrace(); // return JSON_EXCEPTION_MESSAGE; // } catch (final IOException e) { // e.printStackTrace(); // return IO_EXCEPTION_MESSAGE; // } // } // // } // // Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // }
import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.BinaryResponseQuery; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.OAuthQuery;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.pack; /** * Class used to download all sounds within a given pack. The response from the API is a ZIP file containing the sounds. * * API documentation at: http://www.freesound.org/docs/api/resources_apiv2.html#download-pack-oauth2-required */ public class DownloadPack extends BinaryResponseQuery implements OAuthQuery { /** Route parameter to replace with pack identifier. */ protected static final String PACK_ID_ROUTE_PARAMETER = "pack_id"; /** Path to API endpoint. */ private static final String PATH = String.format("/packs/{%s}/download/", PACK_ID_ROUTE_PARAMETER); /** Identifier of pack to download. */ private final int packId; /** OAuth2 Access token to present with request. */ private final String oauthToken; /** * @param packId Identifier of pack to download * @param oauthToken OAuth2 Access token to present with request */ public DownloadPack(final int packId, final String oauthToken) {
// Path: src/main/java/com/sonoport/freesound/query/BinaryResponseQuery.java // public abstract class BinaryResponseQuery extends Query<InputStream, InputStream> { // // /** Error message to return if a non-JSON-formatted error response is received. */ // protected static final String JSON_EXCEPTION_MESSAGE = "A non-JSON formatted error response was received"; // // /** Error message to return if there is a problem processing the {@link InputStream} received. */ // protected static final String IO_EXCEPTION_MESSAGE = "An error occurred processing the error response received"; // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // */ // protected BinaryResponseQuery(final HTTPRequestMethod httpRequestMethod, final String path) { // super(httpRequestMethod, path, new InputStreamMapper()); // } // // @Override // protected String extractErrorMessage(final InputStream freesoundResponse) { // try { // final BufferedReader streamReader = new BufferedReader(new InputStreamReader(freesoundResponse, "UTF-8")); // final StringBuilder responseStrBuilder = new StringBuilder(); // // String streamContent; // while ((streamContent = streamReader.readLine()) != null) { // responseStrBuilder.append(streamContent); // } // // final JSONObject jsonResponse = new JSONObject(responseStrBuilder.toString()); // // return jsonResponse.getString("detail"); // } catch (final JSONException e) { // e.printStackTrace(); // return JSON_EXCEPTION_MESSAGE; // } catch (final IOException e) { // e.printStackTrace(); // return IO_EXCEPTION_MESSAGE; // } // } // // } // // Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // Path: src/main/java/com/sonoport/freesound/query/pack/DownloadPack.java import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.BinaryResponseQuery; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.OAuthQuery; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.pack; /** * Class used to download all sounds within a given pack. The response from the API is a ZIP file containing the sounds. * * API documentation at: http://www.freesound.org/docs/api/resources_apiv2.html#download-pack-oauth2-required */ public class DownloadPack extends BinaryResponseQuery implements OAuthQuery { /** Route parameter to replace with pack identifier. */ protected static final String PACK_ID_ROUTE_PARAMETER = "pack_id"; /** Path to API endpoint. */ private static final String PATH = String.format("/packs/{%s}/download/", PACK_ID_ROUTE_PARAMETER); /** Identifier of pack to download. */ private final int packId; /** OAuth2 Access token to present with request. */ private final String oauthToken; /** * @param packId Identifier of pack to download * @param oauthToken OAuth2 Access token to present with request */ public DownloadPack(final int packId, final String oauthToken) {
super(HTTPRequestMethod.GET, PATH);
Sonoport/freesound-java
src/test/java/com/sonoport/freesound/response/mapping/CurrentUserMapperTest.java
// Path: src/main/java/com/sonoport/freesound/response/CurrentUser.java // public class CurrentUser extends User { // // /** Unique identifier associated with the user. */ // private Integer uniqueIdentifier; // // /** Email address of the user. */ // private String email; // // /** // * @return the uniqueIdentifier // */ // public Integer getUniqueIdentifier() { // return uniqueIdentifier; // } // // /** // * @param uniqueIdentifier the uniqueIdentifier to set // */ // public void setUniqueIdentifier(final Integer uniqueIdentifier) { // this.uniqueIdentifier = uniqueIdentifier; // } // // /** // * @return the email // */ // public String getEmail() { // return email; // } // // /** // * @param email the email to set // */ // public void setEmail(final String email) { // this.email = email; // } // }
import static org.junit.Assert.assertEquals; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.json.JSONObject; import org.junit.Test; import com.sonoport.freesound.response.CurrentUser;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.response.mapping; /** * Unit tests to ensure the correct operation of {@link CurrentUserMapper}. */ public class CurrentUserMapperTest extends MapperTest { /** User URL. */ private static final String URL = "http://www.freesound.org/people/wluna/"; /** Username. */ private static final String USERNAME = "wluna"; /** User 'about' details. */ private static final String ABOUT = "Hello, my name is Wilmar.\r\n\r\nI am the author of a sci-fi superheroine book called The Silver Ninja and am also a professional motion graphics animator and video editor.\r\n\r\nI love video games, films, and art. Please feel free to check out my book at thesilverninja.com, thanks!"; /** User's home page. */ private static final String HOME_PAGE = "http://www.thesilverninja.com/"; /** Collection of URIs to user's avatars. */ private static final Map<String, String> AVATAR_URIS; static { AVATAR_URIS = new HashMap<String, String>(); AVATAR_URIS.put("small", "http://www.freesound.org/data/avatars/4038/4038431_S.jpg"); AVATAR_URIS.put("medium", "http://www.freesound.org/data/avatars/4038/4038431_M.jpg"); AVATAR_URIS.put("large", "http://www.freesound.org/data/avatars/4038/4038431_L.jpg"); }; /** Date user joined freesound. Long value is the millisecond-since-epoch representation of the String * "2014-01-28T01:04:15.047" presented by freesound. */ private static final Date DATE_JOINED = new Date(1390871055000L); /** Number of sounds belonging to user. */ private static final int NUMBER_OF_SOUNDS = 6; /** URI of user's sounds. */ private static final String SOUNDS_URI = "http://www.freesound.org/apiv2/users/wluna/sounds/"; /** Number of packs belonging to user. */ private static final int NUMBER_OF_PACKS = 1; /** URI to user;s packs. */ private static final String PACKS_URI = "http://www.freesound.org/apiv2/users/wluna/packs/"; /** Number of forum posts. */ private static final int NUMBER_OF_POSTS = 0; /** Number of comments. */ private static final int NUMBER_OF_COMMENTS = 2; /** URI to user's bookmark categories. */ private static final String BOOKMARK_CATEGORIES_URI = "http://www.freesound.org/apiv2/users/wluna/bookmark_categories/"; /** Email associated with the user account. */ private static final String EMAIL = "[email protected]"; /** Unique identifier associated with the user account. */ private static final int UNIQUE_ID = 1234567; /** Instance of {@link CurrentUserMapper} to use in tests. */ private final CurrentUserMapper mapper = new CurrentUserMapper(); /** * Ensure {@link CurrentUserMapper} correctly processes a valid current user record. * * @throws Exception Any exceptions thrown in test */ @Test public void parseCurrentUserDetails() throws Exception { final JSONObject currentUserJSON = readJSONFile("/current-user.json");
// Path: src/main/java/com/sonoport/freesound/response/CurrentUser.java // public class CurrentUser extends User { // // /** Unique identifier associated with the user. */ // private Integer uniqueIdentifier; // // /** Email address of the user. */ // private String email; // // /** // * @return the uniqueIdentifier // */ // public Integer getUniqueIdentifier() { // return uniqueIdentifier; // } // // /** // * @param uniqueIdentifier the uniqueIdentifier to set // */ // public void setUniqueIdentifier(final Integer uniqueIdentifier) { // this.uniqueIdentifier = uniqueIdentifier; // } // // /** // * @return the email // */ // public String getEmail() { // return email; // } // // /** // * @param email the email to set // */ // public void setEmail(final String email) { // this.email = email; // } // } // Path: src/test/java/com/sonoport/freesound/response/mapping/CurrentUserMapperTest.java import static org.junit.Assert.assertEquals; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.json.JSONObject; import org.junit.Test; import com.sonoport.freesound.response.CurrentUser; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.response.mapping; /** * Unit tests to ensure the correct operation of {@link CurrentUserMapper}. */ public class CurrentUserMapperTest extends MapperTest { /** User URL. */ private static final String URL = "http://www.freesound.org/people/wluna/"; /** Username. */ private static final String USERNAME = "wluna"; /** User 'about' details. */ private static final String ABOUT = "Hello, my name is Wilmar.\r\n\r\nI am the author of a sci-fi superheroine book called The Silver Ninja and am also a professional motion graphics animator and video editor.\r\n\r\nI love video games, films, and art. Please feel free to check out my book at thesilverninja.com, thanks!"; /** User's home page. */ private static final String HOME_PAGE = "http://www.thesilverninja.com/"; /** Collection of URIs to user's avatars. */ private static final Map<String, String> AVATAR_URIS; static { AVATAR_URIS = new HashMap<String, String>(); AVATAR_URIS.put("small", "http://www.freesound.org/data/avatars/4038/4038431_S.jpg"); AVATAR_URIS.put("medium", "http://www.freesound.org/data/avatars/4038/4038431_M.jpg"); AVATAR_URIS.put("large", "http://www.freesound.org/data/avatars/4038/4038431_L.jpg"); }; /** Date user joined freesound. Long value is the millisecond-since-epoch representation of the String * "2014-01-28T01:04:15.047" presented by freesound. */ private static final Date DATE_JOINED = new Date(1390871055000L); /** Number of sounds belonging to user. */ private static final int NUMBER_OF_SOUNDS = 6; /** URI of user's sounds. */ private static final String SOUNDS_URI = "http://www.freesound.org/apiv2/users/wluna/sounds/"; /** Number of packs belonging to user. */ private static final int NUMBER_OF_PACKS = 1; /** URI to user;s packs. */ private static final String PACKS_URI = "http://www.freesound.org/apiv2/users/wluna/packs/"; /** Number of forum posts. */ private static final int NUMBER_OF_POSTS = 0; /** Number of comments. */ private static final int NUMBER_OF_COMMENTS = 2; /** URI to user's bookmark categories. */ private static final String BOOKMARK_CATEGORIES_URI = "http://www.freesound.org/apiv2/users/wluna/bookmark_categories/"; /** Email associated with the user account. */ private static final String EMAIL = "[email protected]"; /** Unique identifier associated with the user account. */ private static final int UNIQUE_ID = 1234567; /** Instance of {@link CurrentUserMapper} to use in tests. */ private final CurrentUserMapper mapper = new CurrentUserMapper(); /** * Ensure {@link CurrentUserMapper} correctly processes a valid current user record. * * @throws Exception Any exceptions thrown in test */ @Test public void parseCurrentUserDetails() throws Exception { final JSONObject currentUserJSON = readJSONFile("/current-user.json");
final CurrentUser currentUser = mapper.map(currentUserJSON);
Sonoport/freesound-java
src/test/java/com/sonoport/freesound/response/mapping/AccessTokenDetailsMapperTest.java
// Path: src/main/java/com/sonoport/freesound/response/AccessTokenDetails.java // public class AccessTokenDetails { // // /** The OAuth2 token that can be used as a credential for making calls to protected resources. */ // private String accessToken; // // /** Scope(s) associated with the credential. */ // private String scope; // // /** Amount of time (in seconds) that the token is valid. */ // private int expiresIn; // // /** Token used to request a new access token once this one has expired. */ // private String refreshToken; // // /** // * @return the accessToken // */ // public String getAccessToken() { // return accessToken; // } // // /** // * @param accessToken the accessToken to set // */ // public void setAccessToken(final String accessToken) { // this.accessToken = accessToken; // } // // /** // * @return the scope // */ // public String getScope() { // return scope; // } // // /** // * @param scope the scope to set // */ // public void setScope(final String scope) { // this.scope = scope; // } // // /** // * @return the expiresIn // */ // public int getExpiresIn() { // return expiresIn; // } // // /** // * @param expiresIn the expiresIn to set // */ // public void setExpiresIn(final int expiresIn) { // this.expiresIn = expiresIn; // } // // /** // * @return the refreshToken // */ // public String getRefreshToken() { // return refreshToken; // } // // /** // * @param refreshToken the refreshToken to set // */ // public void setRefreshToken(final String refreshToken) { // this.refreshToken = refreshToken; // } // }
import static org.junit.Assert.assertEquals; import org.json.JSONObject; import org.junit.Test; import com.sonoport.freesound.response.AccessTokenDetails;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.response.mapping; /** * Unit tests to ensure that {@link AccessTokenDetailsMapper} correctly processes responses from the OAuth2 token * endpoint. * * Test data is located at <code>/src/test/resources/access-token.json</code>. */ public class AccessTokenDetailsMapperTest extends MapperTest { /** The access token returned. */ private static final String ACCESS_TOKEN = "64c64660ceed813476b314f52136d9698e075622"; /** The scope associated with the access token. */ private static final String SCOPE = "read write read+write"; /** Number of seconds the token is valid for. */ private static final int EXPIRES_IN = 86399; /** Refresh token for generating further access tokens. */ private static final String REFRESH_TOKEN = "0354489231f6a874331aer4927569297c7fea4d5"; /** Instance of {@link AccessTokenDetailsMapper} to use in tests. */ private final AccessTokenDetailsMapper mapper = new AccessTokenDetailsMapper(); /** * Ensure that a valid response is correctly parsed. * * @throws Exception Any exceptions thrown in test */ @Test public void parseAccessTokenDetails() throws Exception { final JSONObject accessTokenJSON = readJSONFile("/access-token.json");
// Path: src/main/java/com/sonoport/freesound/response/AccessTokenDetails.java // public class AccessTokenDetails { // // /** The OAuth2 token that can be used as a credential for making calls to protected resources. */ // private String accessToken; // // /** Scope(s) associated with the credential. */ // private String scope; // // /** Amount of time (in seconds) that the token is valid. */ // private int expiresIn; // // /** Token used to request a new access token once this one has expired. */ // private String refreshToken; // // /** // * @return the accessToken // */ // public String getAccessToken() { // return accessToken; // } // // /** // * @param accessToken the accessToken to set // */ // public void setAccessToken(final String accessToken) { // this.accessToken = accessToken; // } // // /** // * @return the scope // */ // public String getScope() { // return scope; // } // // /** // * @param scope the scope to set // */ // public void setScope(final String scope) { // this.scope = scope; // } // // /** // * @return the expiresIn // */ // public int getExpiresIn() { // return expiresIn; // } // // /** // * @param expiresIn the expiresIn to set // */ // public void setExpiresIn(final int expiresIn) { // this.expiresIn = expiresIn; // } // // /** // * @return the refreshToken // */ // public String getRefreshToken() { // return refreshToken; // } // // /** // * @param refreshToken the refreshToken to set // */ // public void setRefreshToken(final String refreshToken) { // this.refreshToken = refreshToken; // } // } // Path: src/test/java/com/sonoport/freesound/response/mapping/AccessTokenDetailsMapperTest.java import static org.junit.Assert.assertEquals; import org.json.JSONObject; import org.junit.Test; import com.sonoport.freesound.response.AccessTokenDetails; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.response.mapping; /** * Unit tests to ensure that {@link AccessTokenDetailsMapper} correctly processes responses from the OAuth2 token * endpoint. * * Test data is located at <code>/src/test/resources/access-token.json</code>. */ public class AccessTokenDetailsMapperTest extends MapperTest { /** The access token returned. */ private static final String ACCESS_TOKEN = "64c64660ceed813476b314f52136d9698e075622"; /** The scope associated with the access token. */ private static final String SCOPE = "read write read+write"; /** Number of seconds the token is valid for. */ private static final int EXPIRES_IN = 86399; /** Refresh token for generating further access tokens. */ private static final String REFRESH_TOKEN = "0354489231f6a874331aer4927569297c7fea4d5"; /** Instance of {@link AccessTokenDetailsMapper} to use in tests. */ private final AccessTokenDetailsMapper mapper = new AccessTokenDetailsMapper(); /** * Ensure that a valid response is correctly parsed. * * @throws Exception Any exceptions thrown in test */ @Test public void parseAccessTokenDetails() throws Exception { final JSONObject accessTokenJSON = readJSONFile("/access-token.json");
final AccessTokenDetails accessTokenDetails = mapper.map(accessTokenJSON);
Sonoport/freesound-java
src/test/java/com/sonoport/freesound/response/mapping/PackMapperTest.java
// Path: src/main/java/com/sonoport/freesound/response/Pack.java // public class Pack { // // /** The unique identifier of this pack. */ // private int id; // // /** The URI for this pack on the Freesound website. */ // private String url; // // /** The description the user gave to the pack (if any). */ // private String description; // // /** The date when the pack was created. */ // private Date created; // // /** The name user gave to the pack. */ // private String name; // // /** Username of the creator of the pack. */ // private String username; // // /** The number of sounds in the pack. */ // private int numberOfSounds; // // /** The URI for a list of sounds in the pack. */ // private String soundsURI; // // /** The number of times this pack has been downloaded. */ // private int numberOfDownloads; // // /** // * @return the id // */ // public int getId() { // return id; // } // // /** // * @param id the id to set // */ // public void setId(final int id) { // this.id = id; // } // // /** // * @return the url // */ // public String getUrl() { // return url; // } // // /** // * @param url the url to set // */ // public void setUrl(final String url) { // this.url = url; // } // // /** // * @return the description // */ // public String getDescription() { // return description; // } // // /** // * @param description the description to set // */ // public void setDescription(final String description) { // this.description = description; // } // // /** // * @return the created // */ // public Date getCreated() { // return created; // } // // /** // * @param created the created to set // */ // public void setCreated(final Date created) { // this.created = created; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(final String name) { // this.name = name; // } // // /** // * @return the username // */ // public String getUsername() { // return username; // } // // /** // * @param username the username to set // */ // public void setUsername(final String username) { // this.username = username; // } // // /** // * @return the numberOfSounds // */ // public int getNumberOfSounds() { // return numberOfSounds; // } // // /** // * @param numberOfSounds the numberOfSounds to set // */ // public void setNumberOfSounds(final int numberOfSounds) { // this.numberOfSounds = numberOfSounds; // } // // /** // * @return the numberOfDownloads // */ // public int getNumberOfDownloads() { // return numberOfDownloads; // } // // /** // * @param numberOfDownloads the numberOfDownloads to set // */ // public void setNumberOfDownloads(final int numberOfDownloads) { // this.numberOfDownloads = numberOfDownloads; // } // // /** // * @return the soundsURI // */ // public String getSoundsURI() { // return soundsURI; // } // // /** // * @param soundsURI the soundsURI to set // */ // public void setSoundsURI(final String soundsURI) { // this.soundsURI = soundsURI; // } // // }
import static org.junit.Assert.assertEquals; import java.util.Date; import org.json.JSONObject; import org.junit.Test; import com.sonoport.freesound.response.Pack;
package com.sonoport.freesound.response.mapping; /** * Unit tests to ensure the correct operation of {@link PackMapper}. Test data is located as * <code>/src/test/resources/pack.json</code>. */ public class PackMapperTest extends MapperTest { /** Id of the pack. */ private static final int ID = 15292; /** URL of the pack. */ private static final String URL = "http://www.freesound.org/people/clarinet_pablo_proj/packs/15292/"; /** Description of the pack. */ private static final String DESCRIPTION = "Pack description"; /** Date the pack was created. */ private static final Date DATE_CREATED = new Date(1410973300000L); /** Name of the pack. */ private static final String PACK_NAME = "Pablo_Project clarinet overall quality of single note"; /** User name of the pack creator. */ private static final String USERNAME = "clarinet_pablo_proj"; /** Number of sounds in the pack. */ private static final int NUMBER_OF_SOUNDS = 794; /** URL link to sounds in pack. */ private static final String SOUNDS_URI = "http://www.freesound.org/apiv2/packs/15292/sounds/"; /** Number of times the pack has been downloaded. */ private static final int NUMBER_OF_DOWNLOADS = 12; /** Instance of {@link PackMapper} to use in tests. */ private final PackMapper packMapper = new PackMapper(); /** * Test that {@link PackMapper} correctly maps the JSON representation of a sound pack into a {@link Pack} DTO. * * @throws Exception Any exceptions thrown in test */ @Test public void parsePackRecord() throws Exception { final JSONObject packJSON = readJSONFile("/pack.json");
// Path: src/main/java/com/sonoport/freesound/response/Pack.java // public class Pack { // // /** The unique identifier of this pack. */ // private int id; // // /** The URI for this pack on the Freesound website. */ // private String url; // // /** The description the user gave to the pack (if any). */ // private String description; // // /** The date when the pack was created. */ // private Date created; // // /** The name user gave to the pack. */ // private String name; // // /** Username of the creator of the pack. */ // private String username; // // /** The number of sounds in the pack. */ // private int numberOfSounds; // // /** The URI for a list of sounds in the pack. */ // private String soundsURI; // // /** The number of times this pack has been downloaded. */ // private int numberOfDownloads; // // /** // * @return the id // */ // public int getId() { // return id; // } // // /** // * @param id the id to set // */ // public void setId(final int id) { // this.id = id; // } // // /** // * @return the url // */ // public String getUrl() { // return url; // } // // /** // * @param url the url to set // */ // public void setUrl(final String url) { // this.url = url; // } // // /** // * @return the description // */ // public String getDescription() { // return description; // } // // /** // * @param description the description to set // */ // public void setDescription(final String description) { // this.description = description; // } // // /** // * @return the created // */ // public Date getCreated() { // return created; // } // // /** // * @param created the created to set // */ // public void setCreated(final Date created) { // this.created = created; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(final String name) { // this.name = name; // } // // /** // * @return the username // */ // public String getUsername() { // return username; // } // // /** // * @param username the username to set // */ // public void setUsername(final String username) { // this.username = username; // } // // /** // * @return the numberOfSounds // */ // public int getNumberOfSounds() { // return numberOfSounds; // } // // /** // * @param numberOfSounds the numberOfSounds to set // */ // public void setNumberOfSounds(final int numberOfSounds) { // this.numberOfSounds = numberOfSounds; // } // // /** // * @return the numberOfDownloads // */ // public int getNumberOfDownloads() { // return numberOfDownloads; // } // // /** // * @param numberOfDownloads the numberOfDownloads to set // */ // public void setNumberOfDownloads(final int numberOfDownloads) { // this.numberOfDownloads = numberOfDownloads; // } // // /** // * @return the soundsURI // */ // public String getSoundsURI() { // return soundsURI; // } // // /** // * @param soundsURI the soundsURI to set // */ // public void setSoundsURI(final String soundsURI) { // this.soundsURI = soundsURI; // } // // } // Path: src/test/java/com/sonoport/freesound/response/mapping/PackMapperTest.java import static org.junit.Assert.assertEquals; import java.util.Date; import org.json.JSONObject; import org.junit.Test; import com.sonoport.freesound.response.Pack; package com.sonoport.freesound.response.mapping; /** * Unit tests to ensure the correct operation of {@link PackMapper}. Test data is located as * <code>/src/test/resources/pack.json</code>. */ public class PackMapperTest extends MapperTest { /** Id of the pack. */ private static final int ID = 15292; /** URL of the pack. */ private static final String URL = "http://www.freesound.org/people/clarinet_pablo_proj/packs/15292/"; /** Description of the pack. */ private static final String DESCRIPTION = "Pack description"; /** Date the pack was created. */ private static final Date DATE_CREATED = new Date(1410973300000L); /** Name of the pack. */ private static final String PACK_NAME = "Pablo_Project clarinet overall quality of single note"; /** User name of the pack creator. */ private static final String USERNAME = "clarinet_pablo_proj"; /** Number of sounds in the pack. */ private static final int NUMBER_OF_SOUNDS = 794; /** URL link to sounds in pack. */ private static final String SOUNDS_URI = "http://www.freesound.org/apiv2/packs/15292/sounds/"; /** Number of times the pack has been downloaded. */ private static final int NUMBER_OF_DOWNLOADS = 12; /** Instance of {@link PackMapper} to use in tests. */ private final PackMapper packMapper = new PackMapper(); /** * Test that {@link PackMapper} correctly maps the JSON representation of a sound pack into a {@link Pack} DTO. * * @throws Exception Any exceptions thrown in test */ @Test public void parsePackRecord() throws Exception { final JSONObject packJSON = readJSONFile("/pack.json");
final Pack pack = packMapper.map(packJSON);
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/response/Sound.java
// Path: src/main/java/com/sonoport/freesound/License.java // public enum License { // // /** Creative Commons 0 (Public Domain) license. */ // CC_0("Creative Commons 0", "http://creativecommons.org/publicdomain/zero/"), // // /** Creative Commons By-Attribution license. */ // CC_ATTRIBUTION("Attribution", "http://creativecommons.org/licenses/by/"), // // /** Creative Commons By-Attribution Non-commercial license. */ // CC_ATTRIBUTION_NONCOMMERCIAL("Attribution Noncommercial", "http://creativecommons.org/licenses/by-nc/"); // // /** {@link Map} used to lookup the {@link License} type by the textual description. */ // private static final Map<String, License> LICENSE_BY_DESCRIPTION; // static { // LICENSE_BY_DESCRIPTION = new HashMap<String, License>(); // // for (final License license : License.values()) { // LICENSE_BY_DESCRIPTION.put(license.getDescription(), license); // } // } // // /** // * {@link Map} used to lookup the {@link License} type based on the URI. As different versions of the same license // * exist (and additional versions may be added in the future), we hold the common prefix as the key. By testing the // * received URI against the key using {@link String#startsWith(String)}, we can be version-agnostic. // */ // private static final Map<String, License> LICENSE_BY_URI_PREFIX; // static { // LICENSE_BY_URI_PREFIX = new HashMap<String, License>(); // // for (final License license : License.values()) { // LICENSE_BY_URI_PREFIX.put(license.getURIPrefix(), license); // } // } // // /** The textual representation of the license used in the API. */ // private String description; // // /** Prefix of the URI(s) used for this license type. */ // private String uriPrefix; // // /** // * @param description The textual representation of the license // * @param uriPrefix Prefix of the URI(s) // */ // private License(final String description, final String uriPrefix) { // this.description = description; // this.uriPrefix = uriPrefix; // } // // /** // * Lookup the appropriate {@link License} enum based on the description. // * // * @param description Description of the license // * @return The relevant {@link License} enum // */ // public static License fromDescription(final String description) { // return LICENSE_BY_DESCRIPTION.get(description); // } // // /** // * Lookup the appropriate {@link License} enum based on the URI. // * // * @param uri The URI of the license // * @return The relevant {@link License} enum // */ // public static License fromURI(final String uri) { // License license = null; // // if (uri != null) { // for (final Entry<String, License> entry : LICENSE_BY_URI_PREFIX.entrySet()) { // if (uri.startsWith(entry.getKey())) { // license = entry.getValue(); // break; // } // } // } // return license; // } // // /** // * @return the description // */ // public String getDescription() { // return description; // } // // /** // * @return the uriPrefix // */ // public String getURIPrefix() { // return uriPrefix; // } // }
import java.util.Date; import java.util.Map; import java.util.Set; import com.sonoport.freesound.License;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.response; /** * Object representing the data associated with a single sound instance on freesound.org. Full documentation of the data * structure can be found at http://www.freesound.org/docs/api/resources_apiv2.html#sound-resources. */ public class Sound { /** The sound’s unique identifier. */ private Integer id; /** The URI for this sound on the Freesound website. */ private String url; /** The name user gave to the sound. */ private String name; /** An array of tags the user gave to the sound. */ private Set<String> tags; /** The description the user gave to the sound. */ private String description; /** Latitude and longitude of the geotag separated by spaces (e.g. “41.0082325664 28.9731252193”, only for sounds * that have been geotagged). */ private String geotag; /** The date when the sound was uploaded. */ private Date created; /** The license under which the sound is available. */
// Path: src/main/java/com/sonoport/freesound/License.java // public enum License { // // /** Creative Commons 0 (Public Domain) license. */ // CC_0("Creative Commons 0", "http://creativecommons.org/publicdomain/zero/"), // // /** Creative Commons By-Attribution license. */ // CC_ATTRIBUTION("Attribution", "http://creativecommons.org/licenses/by/"), // // /** Creative Commons By-Attribution Non-commercial license. */ // CC_ATTRIBUTION_NONCOMMERCIAL("Attribution Noncommercial", "http://creativecommons.org/licenses/by-nc/"); // // /** {@link Map} used to lookup the {@link License} type by the textual description. */ // private static final Map<String, License> LICENSE_BY_DESCRIPTION; // static { // LICENSE_BY_DESCRIPTION = new HashMap<String, License>(); // // for (final License license : License.values()) { // LICENSE_BY_DESCRIPTION.put(license.getDescription(), license); // } // } // // /** // * {@link Map} used to lookup the {@link License} type based on the URI. As different versions of the same license // * exist (and additional versions may be added in the future), we hold the common prefix as the key. By testing the // * received URI against the key using {@link String#startsWith(String)}, we can be version-agnostic. // */ // private static final Map<String, License> LICENSE_BY_URI_PREFIX; // static { // LICENSE_BY_URI_PREFIX = new HashMap<String, License>(); // // for (final License license : License.values()) { // LICENSE_BY_URI_PREFIX.put(license.getURIPrefix(), license); // } // } // // /** The textual representation of the license used in the API. */ // private String description; // // /** Prefix of the URI(s) used for this license type. */ // private String uriPrefix; // // /** // * @param description The textual representation of the license // * @param uriPrefix Prefix of the URI(s) // */ // private License(final String description, final String uriPrefix) { // this.description = description; // this.uriPrefix = uriPrefix; // } // // /** // * Lookup the appropriate {@link License} enum based on the description. // * // * @param description Description of the license // * @return The relevant {@link License} enum // */ // public static License fromDescription(final String description) { // return LICENSE_BY_DESCRIPTION.get(description); // } // // /** // * Lookup the appropriate {@link License} enum based on the URI. // * // * @param uri The URI of the license // * @return The relevant {@link License} enum // */ // public static License fromURI(final String uri) { // License license = null; // // if (uri != null) { // for (final Entry<String, License> entry : LICENSE_BY_URI_PREFIX.entrySet()) { // if (uri.startsWith(entry.getKey())) { // license = entry.getValue(); // break; // } // } // } // return license; // } // // /** // * @return the description // */ // public String getDescription() { // return description; // } // // /** // * @return the uriPrefix // */ // public String getURIPrefix() { // return uriPrefix; // } // } // Path: src/main/java/com/sonoport/freesound/response/Sound.java import java.util.Date; import java.util.Map; import java.util.Set; import com.sonoport.freesound.License; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.response; /** * Object representing the data associated with a single sound instance on freesound.org. Full documentation of the data * structure can be found at http://www.freesound.org/docs/api/resources_apiv2.html#sound-resources. */ public class Sound { /** The sound’s unique identifier. */ private Integer id; /** The URI for this sound on the Freesound website. */ private String url; /** The name user gave to the sound. */ private String name; /** An array of tags the user gave to the sound. */ private Set<String> tags; /** The description the user gave to the sound. */ private String description; /** Latitude and longitude of the geotag separated by spaces (e.g. “41.0082325664 28.9731252193”, only for sounds * that have been geotagged). */ private String geotag; /** The date when the sound was uploaded. */ private Date created; /** The license under which the sound is available. */
private License license;
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/sound/RateSound.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/DetailStringMapper.java // public class DetailStringMapper extends Mapper<JSONObject, String> { // // @Override // public String map(final JSONObject source) { // return extractFieldValue(source, "detail", String.class); // } // // }
import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.mapping.DetailStringMapper;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query class to allow users to rate sounds on the freesound.org platform. */ public class RateSound extends JSONResponseQuery<String> implements OAuthQuery { /** Name of route parameter to be replaced with the sound identifier. */ protected static final String SOUND_IDENTIFIER_ROUTE_PARAMETER = "sound_id"; /** Parameter name to pass the rating across as. */ protected static final String RATING_PARAMETER_NAME = "rating"; /** Path to API endpoint. */ private static final String PATH = String.format("/sounds/{%s}/rate/", SOUND_IDENTIFIER_ROUTE_PARAMETER); /** Identifier of sound to add comment to. */ private final int soundIdentifier; /** Rating to give the sound. */ private final int rating; /** OAuth taken to present. */ private final String oauthToken; /** * @param soundIdentifier Identifier of sound * @param rating Rating to apply * @param oauthToken OAuth2 token to present */ public RateSound(final int soundIdentifier, final int rating, final String oauthToken) {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/DetailStringMapper.java // public class DetailStringMapper extends Mapper<JSONObject, String> { // // @Override // public String map(final JSONObject source) { // return extractFieldValue(source, "detail", String.class); // } // // } // Path: src/main/java/com/sonoport/freesound/query/sound/RateSound.java import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.mapping.DetailStringMapper; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query class to allow users to rate sounds on the freesound.org platform. */ public class RateSound extends JSONResponseQuery<String> implements OAuthQuery { /** Name of route parameter to be replaced with the sound identifier. */ protected static final String SOUND_IDENTIFIER_ROUTE_PARAMETER = "sound_id"; /** Parameter name to pass the rating across as. */ protected static final String RATING_PARAMETER_NAME = "rating"; /** Path to API endpoint. */ private static final String PATH = String.format("/sounds/{%s}/rate/", SOUND_IDENTIFIER_ROUTE_PARAMETER); /** Identifier of sound to add comment to. */ private final int soundIdentifier; /** Rating to give the sound. */ private final int rating; /** OAuth taken to present. */ private final String oauthToken; /** * @param soundIdentifier Identifier of sound * @param rating Rating to apply * @param oauthToken OAuth2 token to present */ public RateSound(final int soundIdentifier, final int rating, final String oauthToken) {
super(HTTPRequestMethod.POST, PATH, new DetailStringMapper());
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/sound/RateSound.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/DetailStringMapper.java // public class DetailStringMapper extends Mapper<JSONObject, String> { // // @Override // public String map(final JSONObject source) { // return extractFieldValue(source, "detail", String.class); // } // // }
import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.mapping.DetailStringMapper;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query class to allow users to rate sounds on the freesound.org platform. */ public class RateSound extends JSONResponseQuery<String> implements OAuthQuery { /** Name of route parameter to be replaced with the sound identifier. */ protected static final String SOUND_IDENTIFIER_ROUTE_PARAMETER = "sound_id"; /** Parameter name to pass the rating across as. */ protected static final String RATING_PARAMETER_NAME = "rating"; /** Path to API endpoint. */ private static final String PATH = String.format("/sounds/{%s}/rate/", SOUND_IDENTIFIER_ROUTE_PARAMETER); /** Identifier of sound to add comment to. */ private final int soundIdentifier; /** Rating to give the sound. */ private final int rating; /** OAuth taken to present. */ private final String oauthToken; /** * @param soundIdentifier Identifier of sound * @param rating Rating to apply * @param oauthToken OAuth2 token to present */ public RateSound(final int soundIdentifier, final int rating, final String oauthToken) {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/DetailStringMapper.java // public class DetailStringMapper extends Mapper<JSONObject, String> { // // @Override // public String map(final JSONObject source) { // return extractFieldValue(source, "detail", String.class); // } // // } // Path: src/main/java/com/sonoport/freesound/query/sound/RateSound.java import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.mapping.DetailStringMapper; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query class to allow users to rate sounds on the freesound.org platform. */ public class RateSound extends JSONResponseQuery<String> implements OAuthQuery { /** Name of route parameter to be replaced with the sound identifier. */ protected static final String SOUND_IDENTIFIER_ROUTE_PARAMETER = "sound_id"; /** Parameter name to pass the rating across as. */ protected static final String RATING_PARAMETER_NAME = "rating"; /** Path to API endpoint. */ private static final String PATH = String.format("/sounds/{%s}/rate/", SOUND_IDENTIFIER_ROUTE_PARAMETER); /** Identifier of sound to add comment to. */ private final int soundIdentifier; /** Rating to give the sound. */ private final int rating; /** OAuth taken to present. */ private final String oauthToken; /** * @param soundIdentifier Identifier of sound * @param rating Rating to apply * @param oauthToken OAuth2 token to present */ public RateSound(final int soundIdentifier, final int rating, final String oauthToken) {
super(HTTPRequestMethod.POST, PATH, new DetailStringMapper());
Sonoport/freesound-java
src/test/java/com/sonoport/freesound/response/mapping/AudioDescriptorsMapperTest.java
// Path: src/main/java/com/sonoport/freesound/response/AudioDescriptors.java // public class AudioDescriptors { // // /** Fixed length descriptors that take a single value (e.g. pitch). */ // private Set<String> fixedLengthOneDimensional; // // /** Fixed length descriptors that take a multiple values (e.g. mfcc). */ // private Set<String> fixedLengthMultiDimensional; // // /** Descriptors that have different values depending on the sound. */ // private Set<String> variableLength; // // /** // * @return the fixedLengthOneDimensional // */ // public Set<String> getFixedLengthOneDimensional() { // return fixedLengthOneDimensional; // } // // /** // * @param fixedLengthOneDimensional the fixedLengthOneDimensional to set // */ // public void setFixedLengthOneDimensional(final Set<String> fixedLengthOneDimensional) { // this.fixedLengthOneDimensional = fixedLengthOneDimensional; // } // // /** // * @return the fixedLengthMultiDimensional // */ // public Set<String> getFixedLengthMultiDimensional() { // return fixedLengthMultiDimensional; // } // // /** // * @param fixedLengthMultiDimensional the fixedLengthMultiDimensional to set // */ // public void setFixedLengthMultiDimensional( // final Set<String> fixedLengthMultiDimensional) { // this.fixedLengthMultiDimensional = fixedLengthMultiDimensional; // } // // /** // * @return the variableLength // */ // public Set<String> getVariableLength() { // return variableLength; // } // // /** // * @param variableLength the variableLength to set // */ // public void setVariableLength(final Set<String> variableLength) { // this.variableLength = variableLength; // } // }
import static org.junit.Assert.assertTrue; import org.json.JSONObject; import org.junit.Test; import com.sonoport.freesound.response.AudioDescriptors;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.response.mapping; /** * Unit tests to ensure the correct operation of {@link AudioDescriptorsMapper}. * * Test data is located at <code>/src/test/resources/audio-descriptors.json</code>. */ public class AudioDescriptorsMapperTest extends MapperTest { /** Descriptor from test file. */ private static final String ONE_DIMENSIONAL_DESCRIPTOR_1 = "lowlevel.average_loudness"; /** Descriptor from test file. */ private static final String ONE_DIMENSIONAL_DESCRIPTOR_2 = "lowlevel.barkbands.dmean"; /** Descriptor from test file. */ private static final String MULTI_DIMENSIONAL_DESCRIPTOR_1 = "lowlevel.barkbands.dmean"; /** Descriptor from test file. */ private static final String MULTI_DIMENSIONAL_DESCRIPTOR_2 = "lowlevel.barkbands.dmean2"; /** Descriptor from test file. */ private static final String VARIABLE_LENGTH_DESCRIPTOR = "rhythm.beats_position"; /** Instance of {@link AudioDescriptorsMapper} to use in tests. */ private final AudioDescriptorsMapper mapper = new AudioDescriptorsMapper(); /** * Ensure that correctly formatted JSON message is correctly converted into a {@link AudioDescriptors} object. * * @throws Exception Any exceptions trown in test */ @Test public void audioDescriptorsMapping() throws Exception { final JSONObject audioDescriptorsJSON = readJSONFile("/audio-descriptors.json");
// Path: src/main/java/com/sonoport/freesound/response/AudioDescriptors.java // public class AudioDescriptors { // // /** Fixed length descriptors that take a single value (e.g. pitch). */ // private Set<String> fixedLengthOneDimensional; // // /** Fixed length descriptors that take a multiple values (e.g. mfcc). */ // private Set<String> fixedLengthMultiDimensional; // // /** Descriptors that have different values depending on the sound. */ // private Set<String> variableLength; // // /** // * @return the fixedLengthOneDimensional // */ // public Set<String> getFixedLengthOneDimensional() { // return fixedLengthOneDimensional; // } // // /** // * @param fixedLengthOneDimensional the fixedLengthOneDimensional to set // */ // public void setFixedLengthOneDimensional(final Set<String> fixedLengthOneDimensional) { // this.fixedLengthOneDimensional = fixedLengthOneDimensional; // } // // /** // * @return the fixedLengthMultiDimensional // */ // public Set<String> getFixedLengthMultiDimensional() { // return fixedLengthMultiDimensional; // } // // /** // * @param fixedLengthMultiDimensional the fixedLengthMultiDimensional to set // */ // public void setFixedLengthMultiDimensional( // final Set<String> fixedLengthMultiDimensional) { // this.fixedLengthMultiDimensional = fixedLengthMultiDimensional; // } // // /** // * @return the variableLength // */ // public Set<String> getVariableLength() { // return variableLength; // } // // /** // * @param variableLength the variableLength to set // */ // public void setVariableLength(final Set<String> variableLength) { // this.variableLength = variableLength; // } // } // Path: src/test/java/com/sonoport/freesound/response/mapping/AudioDescriptorsMapperTest.java import static org.junit.Assert.assertTrue; import org.json.JSONObject; import org.junit.Test; import com.sonoport.freesound.response.AudioDescriptors; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.response.mapping; /** * Unit tests to ensure the correct operation of {@link AudioDescriptorsMapper}. * * Test data is located at <code>/src/test/resources/audio-descriptors.json</code>. */ public class AudioDescriptorsMapperTest extends MapperTest { /** Descriptor from test file. */ private static final String ONE_DIMENSIONAL_DESCRIPTOR_1 = "lowlevel.average_loudness"; /** Descriptor from test file. */ private static final String ONE_DIMENSIONAL_DESCRIPTOR_2 = "lowlevel.barkbands.dmean"; /** Descriptor from test file. */ private static final String MULTI_DIMENSIONAL_DESCRIPTOR_1 = "lowlevel.barkbands.dmean"; /** Descriptor from test file. */ private static final String MULTI_DIMENSIONAL_DESCRIPTOR_2 = "lowlevel.barkbands.dmean2"; /** Descriptor from test file. */ private static final String VARIABLE_LENGTH_DESCRIPTOR = "rhythm.beats_position"; /** Instance of {@link AudioDescriptorsMapper} to use in tests. */ private final AudioDescriptorsMapper mapper = new AudioDescriptorsMapper(); /** * Ensure that correctly formatted JSON message is correctly converted into a {@link AudioDescriptors} object. * * @throws Exception Any exceptions trown in test */ @Test public void audioDescriptorsMapping() throws Exception { final JSONObject audioDescriptorsJSON = readJSONFile("/audio-descriptors.json");
final AudioDescriptors audioDescriptors = mapper.map(audioDescriptorsJSON);
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/sound/DownloadSound.java
// Path: src/main/java/com/sonoport/freesound/query/BinaryResponseQuery.java // public abstract class BinaryResponseQuery extends Query<InputStream, InputStream> { // // /** Error message to return if a non-JSON-formatted error response is received. */ // protected static final String JSON_EXCEPTION_MESSAGE = "A non-JSON formatted error response was received"; // // /** Error message to return if there is a problem processing the {@link InputStream} received. */ // protected static final String IO_EXCEPTION_MESSAGE = "An error occurred processing the error response received"; // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // */ // protected BinaryResponseQuery(final HTTPRequestMethod httpRequestMethod, final String path) { // super(httpRequestMethod, path, new InputStreamMapper()); // } // // @Override // protected String extractErrorMessage(final InputStream freesoundResponse) { // try { // final BufferedReader streamReader = new BufferedReader(new InputStreamReader(freesoundResponse, "UTF-8")); // final StringBuilder responseStrBuilder = new StringBuilder(); // // String streamContent; // while ((streamContent = streamReader.readLine()) != null) { // responseStrBuilder.append(streamContent); // } // // final JSONObject jsonResponse = new JSONObject(responseStrBuilder.toString()); // // return jsonResponse.getString("detail"); // } catch (final JSONException e) { // e.printStackTrace(); // return JSON_EXCEPTION_MESSAGE; // } catch (final IOException e) { // e.printStackTrace(); // return IO_EXCEPTION_MESSAGE; // } // } // // } // // Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // }
import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.BinaryResponseQuery; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.OAuthQuery;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query class used to download a given sound from freesound.org. */ public class DownloadSound extends BinaryResponseQuery implements OAuthQuery { /** The name of the path parameter used to determine the sound to retrieve. */ protected static final String SOUND_IDENTIFIER_PARAMETER = "sound_id"; /** * The path to the freesound endpoint. Sound identifier is specified as a named parameter which will be populated * at runtime by the <code>routeParam(String, String)</code> method. */ private static final String REQUEST_PATH = String.format("/sounds/{%s}/download/", SOUND_IDENTIFIER_PARAMETER); /** The identifier of the sound to retrieve. */ private final int soundId; /** Bearer token used to authenticate request. */ private final String oauthToken; /** * @param soundId Identifier of sound to download * @param oauthToken Token to use as authorisation */ public DownloadSound(final int soundId, final String oauthToken) {
// Path: src/main/java/com/sonoport/freesound/query/BinaryResponseQuery.java // public abstract class BinaryResponseQuery extends Query<InputStream, InputStream> { // // /** Error message to return if a non-JSON-formatted error response is received. */ // protected static final String JSON_EXCEPTION_MESSAGE = "A non-JSON formatted error response was received"; // // /** Error message to return if there is a problem processing the {@link InputStream} received. */ // protected static final String IO_EXCEPTION_MESSAGE = "An error occurred processing the error response received"; // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // */ // protected BinaryResponseQuery(final HTTPRequestMethod httpRequestMethod, final String path) { // super(httpRequestMethod, path, new InputStreamMapper()); // } // // @Override // protected String extractErrorMessage(final InputStream freesoundResponse) { // try { // final BufferedReader streamReader = new BufferedReader(new InputStreamReader(freesoundResponse, "UTF-8")); // final StringBuilder responseStrBuilder = new StringBuilder(); // // String streamContent; // while ((streamContent = streamReader.readLine()) != null) { // responseStrBuilder.append(streamContent); // } // // final JSONObject jsonResponse = new JSONObject(responseStrBuilder.toString()); // // return jsonResponse.getString("detail"); // } catch (final JSONException e) { // e.printStackTrace(); // return JSON_EXCEPTION_MESSAGE; // } catch (final IOException e) { // e.printStackTrace(); // return IO_EXCEPTION_MESSAGE; // } // } // // } // // Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // Path: src/main/java/com/sonoport/freesound/query/sound/DownloadSound.java import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.sonoport.freesound.query.BinaryResponseQuery; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.OAuthQuery; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query class used to download a given sound from freesound.org. */ public class DownloadSound extends BinaryResponseQuery implements OAuthQuery { /** The name of the path parameter used to determine the sound to retrieve. */ protected static final String SOUND_IDENTIFIER_PARAMETER = "sound_id"; /** * The path to the freesound endpoint. Sound identifier is specified as a named parameter which will be populated * at runtime by the <code>routeParam(String, String)</code> method. */ private static final String REQUEST_PATH = String.format("/sounds/{%s}/download/", SOUND_IDENTIFIER_PARAMETER); /** The identifier of the sound to retrieve. */ private final int soundId; /** Bearer token used to authenticate request. */ private final String oauthToken; /** * @param soundId Identifier of sound to download * @param oauthToken Token to use as authorisation */ public DownloadSound(final int soundId, final String oauthToken) {
super(HTTPRequestMethod.GET, REQUEST_PATH);
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/other/AvailableAudioDescriptorsQuery.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/response/AudioDescriptors.java // public class AudioDescriptors { // // /** Fixed length descriptors that take a single value (e.g. pitch). */ // private Set<String> fixedLengthOneDimensional; // // /** Fixed length descriptors that take a multiple values (e.g. mfcc). */ // private Set<String> fixedLengthMultiDimensional; // // /** Descriptors that have different values depending on the sound. */ // private Set<String> variableLength; // // /** // * @return the fixedLengthOneDimensional // */ // public Set<String> getFixedLengthOneDimensional() { // return fixedLengthOneDimensional; // } // // /** // * @param fixedLengthOneDimensional the fixedLengthOneDimensional to set // */ // public void setFixedLengthOneDimensional(final Set<String> fixedLengthOneDimensional) { // this.fixedLengthOneDimensional = fixedLengthOneDimensional; // } // // /** // * @return the fixedLengthMultiDimensional // */ // public Set<String> getFixedLengthMultiDimensional() { // return fixedLengthMultiDimensional; // } // // /** // * @param fixedLengthMultiDimensional the fixedLengthMultiDimensional to set // */ // public void setFixedLengthMultiDimensional( // final Set<String> fixedLengthMultiDimensional) { // this.fixedLengthMultiDimensional = fixedLengthMultiDimensional; // } // // /** // * @return the variableLength // */ // public Set<String> getVariableLength() { // return variableLength; // } // // /** // * @param variableLength the variableLength to set // */ // public void setVariableLength(final Set<String> variableLength) { // this.variableLength = variableLength; // } // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/AudioDescriptorsMapper.java // public class AudioDescriptorsMapper extends Mapper<JSONObject, AudioDescriptors> { // // @Override // public AudioDescriptors map(final JSONObject source) { // final AudioDescriptors audioDescriptors = new AudioDescriptors(); // // final JSONObject fixedLengthDescriptors = extractFieldValue(source, "fixed-length", JSONObject.class); // final JSONArray fixedLengthOneDimensionalDescriptors = // extractFieldValue(fixedLengthDescriptors, "one-dimensional", JSONArray.class); // audioDescriptors.setFixedLengthOneDimensional(new TreeSet<>(parseArray(fixedLengthOneDimensionalDescriptors))); // // final JSONArray fixedLengthMultiDimensionalDescriptors = // extractFieldValue(fixedLengthDescriptors, "multi-dimensional", JSONArray.class); // audioDescriptors.setFixedLengthMultiDimensional( // new TreeSet<>(parseArray(fixedLengthMultiDimensionalDescriptors))); // // final JSONArray variableLengthDescriptors = extractFieldValue(source, "variable-length", JSONArray.class); // audioDescriptors.setVariableLength(new TreeSet<>(parseArray(variableLengthDescriptors))); // // return audioDescriptors; // } // // }
import java.util.Collections; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.response.AudioDescriptors; import com.sonoport.freesound.response.mapping.AudioDescriptorsMapper;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.other; /** * Query used to retrieve all available audio descriptors used in content searches. * * API documentation at: http://www.freesound.org/docs/api/resources_apiv2.html#available-audio-descriptors. */ public class AvailableAudioDescriptorsQuery extends JSONResponseQuery<AudioDescriptors> { /** Path to API endpoint. */ private static final String PATH = "/descriptors/"; /** * No-arg constructor. */ public AvailableAudioDescriptorsQuery() {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/response/AudioDescriptors.java // public class AudioDescriptors { // // /** Fixed length descriptors that take a single value (e.g. pitch). */ // private Set<String> fixedLengthOneDimensional; // // /** Fixed length descriptors that take a multiple values (e.g. mfcc). */ // private Set<String> fixedLengthMultiDimensional; // // /** Descriptors that have different values depending on the sound. */ // private Set<String> variableLength; // // /** // * @return the fixedLengthOneDimensional // */ // public Set<String> getFixedLengthOneDimensional() { // return fixedLengthOneDimensional; // } // // /** // * @param fixedLengthOneDimensional the fixedLengthOneDimensional to set // */ // public void setFixedLengthOneDimensional(final Set<String> fixedLengthOneDimensional) { // this.fixedLengthOneDimensional = fixedLengthOneDimensional; // } // // /** // * @return the fixedLengthMultiDimensional // */ // public Set<String> getFixedLengthMultiDimensional() { // return fixedLengthMultiDimensional; // } // // /** // * @param fixedLengthMultiDimensional the fixedLengthMultiDimensional to set // */ // public void setFixedLengthMultiDimensional( // final Set<String> fixedLengthMultiDimensional) { // this.fixedLengthMultiDimensional = fixedLengthMultiDimensional; // } // // /** // * @return the variableLength // */ // public Set<String> getVariableLength() { // return variableLength; // } // // /** // * @param variableLength the variableLength to set // */ // public void setVariableLength(final Set<String> variableLength) { // this.variableLength = variableLength; // } // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/AudioDescriptorsMapper.java // public class AudioDescriptorsMapper extends Mapper<JSONObject, AudioDescriptors> { // // @Override // public AudioDescriptors map(final JSONObject source) { // final AudioDescriptors audioDescriptors = new AudioDescriptors(); // // final JSONObject fixedLengthDescriptors = extractFieldValue(source, "fixed-length", JSONObject.class); // final JSONArray fixedLengthOneDimensionalDescriptors = // extractFieldValue(fixedLengthDescriptors, "one-dimensional", JSONArray.class); // audioDescriptors.setFixedLengthOneDimensional(new TreeSet<>(parseArray(fixedLengthOneDimensionalDescriptors))); // // final JSONArray fixedLengthMultiDimensionalDescriptors = // extractFieldValue(fixedLengthDescriptors, "multi-dimensional", JSONArray.class); // audioDescriptors.setFixedLengthMultiDimensional( // new TreeSet<>(parseArray(fixedLengthMultiDimensionalDescriptors))); // // final JSONArray variableLengthDescriptors = extractFieldValue(source, "variable-length", JSONArray.class); // audioDescriptors.setVariableLength(new TreeSet<>(parseArray(variableLengthDescriptors))); // // return audioDescriptors; // } // // } // Path: src/main/java/com/sonoport/freesound/query/other/AvailableAudioDescriptorsQuery.java import java.util.Collections; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.response.AudioDescriptors; import com.sonoport.freesound.response.mapping.AudioDescriptorsMapper; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.other; /** * Query used to retrieve all available audio descriptors used in content searches. * * API documentation at: http://www.freesound.org/docs/api/resources_apiv2.html#available-audio-descriptors. */ public class AvailableAudioDescriptorsQuery extends JSONResponseQuery<AudioDescriptors> { /** Path to API endpoint. */ private static final String PATH = "/descriptors/"; /** * No-arg constructor. */ public AvailableAudioDescriptorsQuery() {
super(HTTPRequestMethod.GET, PATH, new AudioDescriptorsMapper());
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/other/AvailableAudioDescriptorsQuery.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/response/AudioDescriptors.java // public class AudioDescriptors { // // /** Fixed length descriptors that take a single value (e.g. pitch). */ // private Set<String> fixedLengthOneDimensional; // // /** Fixed length descriptors that take a multiple values (e.g. mfcc). */ // private Set<String> fixedLengthMultiDimensional; // // /** Descriptors that have different values depending on the sound. */ // private Set<String> variableLength; // // /** // * @return the fixedLengthOneDimensional // */ // public Set<String> getFixedLengthOneDimensional() { // return fixedLengthOneDimensional; // } // // /** // * @param fixedLengthOneDimensional the fixedLengthOneDimensional to set // */ // public void setFixedLengthOneDimensional(final Set<String> fixedLengthOneDimensional) { // this.fixedLengthOneDimensional = fixedLengthOneDimensional; // } // // /** // * @return the fixedLengthMultiDimensional // */ // public Set<String> getFixedLengthMultiDimensional() { // return fixedLengthMultiDimensional; // } // // /** // * @param fixedLengthMultiDimensional the fixedLengthMultiDimensional to set // */ // public void setFixedLengthMultiDimensional( // final Set<String> fixedLengthMultiDimensional) { // this.fixedLengthMultiDimensional = fixedLengthMultiDimensional; // } // // /** // * @return the variableLength // */ // public Set<String> getVariableLength() { // return variableLength; // } // // /** // * @param variableLength the variableLength to set // */ // public void setVariableLength(final Set<String> variableLength) { // this.variableLength = variableLength; // } // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/AudioDescriptorsMapper.java // public class AudioDescriptorsMapper extends Mapper<JSONObject, AudioDescriptors> { // // @Override // public AudioDescriptors map(final JSONObject source) { // final AudioDescriptors audioDescriptors = new AudioDescriptors(); // // final JSONObject fixedLengthDescriptors = extractFieldValue(source, "fixed-length", JSONObject.class); // final JSONArray fixedLengthOneDimensionalDescriptors = // extractFieldValue(fixedLengthDescriptors, "one-dimensional", JSONArray.class); // audioDescriptors.setFixedLengthOneDimensional(new TreeSet<>(parseArray(fixedLengthOneDimensionalDescriptors))); // // final JSONArray fixedLengthMultiDimensionalDescriptors = // extractFieldValue(fixedLengthDescriptors, "multi-dimensional", JSONArray.class); // audioDescriptors.setFixedLengthMultiDimensional( // new TreeSet<>(parseArray(fixedLengthMultiDimensionalDescriptors))); // // final JSONArray variableLengthDescriptors = extractFieldValue(source, "variable-length", JSONArray.class); // audioDescriptors.setVariableLength(new TreeSet<>(parseArray(variableLengthDescriptors))); // // return audioDescriptors; // } // // }
import java.util.Collections; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.response.AudioDescriptors; import com.sonoport.freesound.response.mapping.AudioDescriptorsMapper;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.other; /** * Query used to retrieve all available audio descriptors used in content searches. * * API documentation at: http://www.freesound.org/docs/api/resources_apiv2.html#available-audio-descriptors. */ public class AvailableAudioDescriptorsQuery extends JSONResponseQuery<AudioDescriptors> { /** Path to API endpoint. */ private static final String PATH = "/descriptors/"; /** * No-arg constructor. */ public AvailableAudioDescriptorsQuery() {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/response/AudioDescriptors.java // public class AudioDescriptors { // // /** Fixed length descriptors that take a single value (e.g. pitch). */ // private Set<String> fixedLengthOneDimensional; // // /** Fixed length descriptors that take a multiple values (e.g. mfcc). */ // private Set<String> fixedLengthMultiDimensional; // // /** Descriptors that have different values depending on the sound. */ // private Set<String> variableLength; // // /** // * @return the fixedLengthOneDimensional // */ // public Set<String> getFixedLengthOneDimensional() { // return fixedLengthOneDimensional; // } // // /** // * @param fixedLengthOneDimensional the fixedLengthOneDimensional to set // */ // public void setFixedLengthOneDimensional(final Set<String> fixedLengthOneDimensional) { // this.fixedLengthOneDimensional = fixedLengthOneDimensional; // } // // /** // * @return the fixedLengthMultiDimensional // */ // public Set<String> getFixedLengthMultiDimensional() { // return fixedLengthMultiDimensional; // } // // /** // * @param fixedLengthMultiDimensional the fixedLengthMultiDimensional to set // */ // public void setFixedLengthMultiDimensional( // final Set<String> fixedLengthMultiDimensional) { // this.fixedLengthMultiDimensional = fixedLengthMultiDimensional; // } // // /** // * @return the variableLength // */ // public Set<String> getVariableLength() { // return variableLength; // } // // /** // * @param variableLength the variableLength to set // */ // public void setVariableLength(final Set<String> variableLength) { // this.variableLength = variableLength; // } // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/AudioDescriptorsMapper.java // public class AudioDescriptorsMapper extends Mapper<JSONObject, AudioDescriptors> { // // @Override // public AudioDescriptors map(final JSONObject source) { // final AudioDescriptors audioDescriptors = new AudioDescriptors(); // // final JSONObject fixedLengthDescriptors = extractFieldValue(source, "fixed-length", JSONObject.class); // final JSONArray fixedLengthOneDimensionalDescriptors = // extractFieldValue(fixedLengthDescriptors, "one-dimensional", JSONArray.class); // audioDescriptors.setFixedLengthOneDimensional(new TreeSet<>(parseArray(fixedLengthOneDimensionalDescriptors))); // // final JSONArray fixedLengthMultiDimensionalDescriptors = // extractFieldValue(fixedLengthDescriptors, "multi-dimensional", JSONArray.class); // audioDescriptors.setFixedLengthMultiDimensional( // new TreeSet<>(parseArray(fixedLengthMultiDimensionalDescriptors))); // // final JSONArray variableLengthDescriptors = extractFieldValue(source, "variable-length", JSONArray.class); // audioDescriptors.setVariableLength(new TreeSet<>(parseArray(variableLengthDescriptors))); // // return audioDescriptors; // } // // } // Path: src/main/java/com/sonoport/freesound/query/other/AvailableAudioDescriptorsQuery.java import java.util.Collections; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.response.AudioDescriptors; import com.sonoport.freesound.response.mapping.AudioDescriptorsMapper; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.other; /** * Query used to retrieve all available audio descriptors used in content searches. * * API documentation at: http://www.freesound.org/docs/api/resources_apiv2.html#available-audio-descriptors. */ public class AvailableAudioDescriptorsQuery extends JSONResponseQuery<AudioDescriptors> { /** Path to API endpoint. */ private static final String PATH = "/descriptors/"; /** * No-arg constructor. */ public AvailableAudioDescriptorsQuery() {
super(HTTPRequestMethod.GET, PATH, new AudioDescriptorsMapper());
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/sound/PendingUploadsQuery.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/PendingUploads.java // public class PendingUploads { // // /** List of names of sounds that do not yet have descriptions associated with them. */ // private List<String> pendingDescription; // // /** Collection of uploaded sounds that have not yet been processed by the system. */ // private List<Sound> pendingProcessing; // // /** Collection of uploaded sounds that have not yet passed through the moderation process. */ // private List<Sound> pendingModeration; // // /** // * @return the pendingDescription // */ // public List<String> getPendingDescription() { // return pendingDescription; // } // // /** // * @param pendingDescription the pendingDescription to set // */ // public void setPendingDescription(final List<String> pendingDescription) { // this.pendingDescription = pendingDescription; // } // // /** // * @return the pendingProcessing // */ // public List<Sound> getPendingProcessing() { // return pendingProcessing; // } // // /** // * @param pendingProcessing the pendingProcessing to set // */ // public void setPendingProcessing(final List<Sound> pendingProcessing) { // this.pendingProcessing = pendingProcessing; // } // // /** // * @return the pendingModeration // */ // public List<Sound> getPendingModeration() { // return pendingModeration; // } // // /** // * @param pendingModeration the pendingModeration to set // */ // public void setPendingModeration(final List<Sound> pendingModeration) { // this.pendingModeration = pendingModeration; // } // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/PendingUploadsMapper.java // public class PendingUploadsMapper extends Mapper<JSONObject, PendingUploads> { // // /** Instance of {@link SoundMapper} used to transform details of sounds within the response. */ // private final SoundMapper soundMapper = new SoundMapper(); // // @Override // public PendingUploads map(final JSONObject source) { // final PendingUploads pendingUploads = new PendingUploads(); // // pendingUploads.setPendingDescription( // parseArray(extractFieldValue(source, "pending_description", JSONArray.class))); // // pendingUploads.setPendingModeration( // parseArray(extractFieldValue(source, "pending_moderation", JSONArray.class), soundMapper)); // // pendingUploads.setPendingProcessing( // parseArray(extractFieldValue(source, "pending_processing", JSONArray.class), soundMapper)); // // return pendingUploads; // } // // }
import java.util.Collections; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.PendingUploads; import com.sonoport.freesound.response.mapping.PendingUploadsMapper;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query class used to retrieve details of sounds that have been uploaded by the current user, but that require * additional steps to be performed before they are made publicly available. * * Full details of API endpoint: http://www.freesound.org/docs/api/resources_apiv2.html#pending-uploads-oauth2-required */ public class PendingUploadsQuery extends JSONResponseQuery<PendingUploads> implements OAuthQuery { /** Path to API endpoint. */ private static final String PATH = "/sounds/pending_uploads/"; /** OAuth2 token to present as credentials. */ private final String ouathToken; /** * @param oauthToken OAuth2 token to present as credentials */ public PendingUploadsQuery(final String oauthToken) {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/PendingUploads.java // public class PendingUploads { // // /** List of names of sounds that do not yet have descriptions associated with them. */ // private List<String> pendingDescription; // // /** Collection of uploaded sounds that have not yet been processed by the system. */ // private List<Sound> pendingProcessing; // // /** Collection of uploaded sounds that have not yet passed through the moderation process. */ // private List<Sound> pendingModeration; // // /** // * @return the pendingDescription // */ // public List<String> getPendingDescription() { // return pendingDescription; // } // // /** // * @param pendingDescription the pendingDescription to set // */ // public void setPendingDescription(final List<String> pendingDescription) { // this.pendingDescription = pendingDescription; // } // // /** // * @return the pendingProcessing // */ // public List<Sound> getPendingProcessing() { // return pendingProcessing; // } // // /** // * @param pendingProcessing the pendingProcessing to set // */ // public void setPendingProcessing(final List<Sound> pendingProcessing) { // this.pendingProcessing = pendingProcessing; // } // // /** // * @return the pendingModeration // */ // public List<Sound> getPendingModeration() { // return pendingModeration; // } // // /** // * @param pendingModeration the pendingModeration to set // */ // public void setPendingModeration(final List<Sound> pendingModeration) { // this.pendingModeration = pendingModeration; // } // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/PendingUploadsMapper.java // public class PendingUploadsMapper extends Mapper<JSONObject, PendingUploads> { // // /** Instance of {@link SoundMapper} used to transform details of sounds within the response. */ // private final SoundMapper soundMapper = new SoundMapper(); // // @Override // public PendingUploads map(final JSONObject source) { // final PendingUploads pendingUploads = new PendingUploads(); // // pendingUploads.setPendingDescription( // parseArray(extractFieldValue(source, "pending_description", JSONArray.class))); // // pendingUploads.setPendingModeration( // parseArray(extractFieldValue(source, "pending_moderation", JSONArray.class), soundMapper)); // // pendingUploads.setPendingProcessing( // parseArray(extractFieldValue(source, "pending_processing", JSONArray.class), soundMapper)); // // return pendingUploads; // } // // } // Path: src/main/java/com/sonoport/freesound/query/sound/PendingUploadsQuery.java import java.util.Collections; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.PendingUploads; import com.sonoport.freesound.response.mapping.PendingUploadsMapper; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query class used to retrieve details of sounds that have been uploaded by the current user, but that require * additional steps to be performed before they are made publicly available. * * Full details of API endpoint: http://www.freesound.org/docs/api/resources_apiv2.html#pending-uploads-oauth2-required */ public class PendingUploadsQuery extends JSONResponseQuery<PendingUploads> implements OAuthQuery { /** Path to API endpoint. */ private static final String PATH = "/sounds/pending_uploads/"; /** OAuth2 token to present as credentials. */ private final String ouathToken; /** * @param oauthToken OAuth2 token to present as credentials */ public PendingUploadsQuery(final String oauthToken) {
super(HTTPRequestMethod.GET, PATH, new PendingUploadsMapper());
Sonoport/freesound-java
src/main/java/com/sonoport/freesound/query/sound/PendingUploadsQuery.java
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/PendingUploads.java // public class PendingUploads { // // /** List of names of sounds that do not yet have descriptions associated with them. */ // private List<String> pendingDescription; // // /** Collection of uploaded sounds that have not yet been processed by the system. */ // private List<Sound> pendingProcessing; // // /** Collection of uploaded sounds that have not yet passed through the moderation process. */ // private List<Sound> pendingModeration; // // /** // * @return the pendingDescription // */ // public List<String> getPendingDescription() { // return pendingDescription; // } // // /** // * @param pendingDescription the pendingDescription to set // */ // public void setPendingDescription(final List<String> pendingDescription) { // this.pendingDescription = pendingDescription; // } // // /** // * @return the pendingProcessing // */ // public List<Sound> getPendingProcessing() { // return pendingProcessing; // } // // /** // * @param pendingProcessing the pendingProcessing to set // */ // public void setPendingProcessing(final List<Sound> pendingProcessing) { // this.pendingProcessing = pendingProcessing; // } // // /** // * @return the pendingModeration // */ // public List<Sound> getPendingModeration() { // return pendingModeration; // } // // /** // * @param pendingModeration the pendingModeration to set // */ // public void setPendingModeration(final List<Sound> pendingModeration) { // this.pendingModeration = pendingModeration; // } // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/PendingUploadsMapper.java // public class PendingUploadsMapper extends Mapper<JSONObject, PendingUploads> { // // /** Instance of {@link SoundMapper} used to transform details of sounds within the response. */ // private final SoundMapper soundMapper = new SoundMapper(); // // @Override // public PendingUploads map(final JSONObject source) { // final PendingUploads pendingUploads = new PendingUploads(); // // pendingUploads.setPendingDescription( // parseArray(extractFieldValue(source, "pending_description", JSONArray.class))); // // pendingUploads.setPendingModeration( // parseArray(extractFieldValue(source, "pending_moderation", JSONArray.class), soundMapper)); // // pendingUploads.setPendingProcessing( // parseArray(extractFieldValue(source, "pending_processing", JSONArray.class), soundMapper)); // // return pendingUploads; // } // // }
import java.util.Collections; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.PendingUploads; import com.sonoport.freesound.response.mapping.PendingUploadsMapper;
/* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query class used to retrieve details of sounds that have been uploaded by the current user, but that require * additional steps to be performed before they are made publicly available. * * Full details of API endpoint: http://www.freesound.org/docs/api/resources_apiv2.html#pending-uploads-oauth2-required */ public class PendingUploadsQuery extends JSONResponseQuery<PendingUploads> implements OAuthQuery { /** Path to API endpoint. */ private static final String PATH = "/sounds/pending_uploads/"; /** OAuth2 token to present as credentials. */ private final String ouathToken; /** * @param oauthToken OAuth2 token to present as credentials */ public PendingUploadsQuery(final String oauthToken) {
// Path: src/main/java/com/sonoport/freesound/query/HTTPRequestMethod.java // public enum HTTPRequestMethod { // // /** HTTP GET. */ // GET, // // /** HTTP POST. */ // POST, // // /** HTTP PUT. */ // PUT, // // /** HTTP DELETE. */ // DELETE, // // /** HTTP PATCH. */ // PATCH, // // /** HTTP HEAD. */ // HEAD, // // /** HTTP OPTIONS. */ // OPTIONS; // } // // Path: src/main/java/com/sonoport/freesound/query/JSONResponseQuery.java // public abstract class JSONResponseQuery<R extends Object> extends Query<JSONObject, R> { // // /** // * @param httpRequestMethod HTTP method to use for query // * @param path Endpoint to submit the query to // * @param resultsMapper {@link Mapper} to convert results // */ // protected JSONResponseQuery( // final HTTPRequestMethod httpRequestMethod, final String path, final Mapper<JSONObject, R> resultsMapper) { // super(httpRequestMethod, path, resultsMapper); // } // // @Override // protected String extractErrorMessage(final JSONObject freesoundResponse) { // return freesoundResponse.getString("detail"); // } // // } // // Path: src/main/java/com/sonoport/freesound/query/OAuthQuery.java // public interface OAuthQuery { // // /** // * @return The oauthToken to be presented with the request // */ // String getOauthToken(); // // } // // Path: src/main/java/com/sonoport/freesound/response/PendingUploads.java // public class PendingUploads { // // /** List of names of sounds that do not yet have descriptions associated with them. */ // private List<String> pendingDescription; // // /** Collection of uploaded sounds that have not yet been processed by the system. */ // private List<Sound> pendingProcessing; // // /** Collection of uploaded sounds that have not yet passed through the moderation process. */ // private List<Sound> pendingModeration; // // /** // * @return the pendingDescription // */ // public List<String> getPendingDescription() { // return pendingDescription; // } // // /** // * @param pendingDescription the pendingDescription to set // */ // public void setPendingDescription(final List<String> pendingDescription) { // this.pendingDescription = pendingDescription; // } // // /** // * @return the pendingProcessing // */ // public List<Sound> getPendingProcessing() { // return pendingProcessing; // } // // /** // * @param pendingProcessing the pendingProcessing to set // */ // public void setPendingProcessing(final List<Sound> pendingProcessing) { // this.pendingProcessing = pendingProcessing; // } // // /** // * @return the pendingModeration // */ // public List<Sound> getPendingModeration() { // return pendingModeration; // } // // /** // * @param pendingModeration the pendingModeration to set // */ // public void setPendingModeration(final List<Sound> pendingModeration) { // this.pendingModeration = pendingModeration; // } // } // // Path: src/main/java/com/sonoport/freesound/response/mapping/PendingUploadsMapper.java // public class PendingUploadsMapper extends Mapper<JSONObject, PendingUploads> { // // /** Instance of {@link SoundMapper} used to transform details of sounds within the response. */ // private final SoundMapper soundMapper = new SoundMapper(); // // @Override // public PendingUploads map(final JSONObject source) { // final PendingUploads pendingUploads = new PendingUploads(); // // pendingUploads.setPendingDescription( // parseArray(extractFieldValue(source, "pending_description", JSONArray.class))); // // pendingUploads.setPendingModeration( // parseArray(extractFieldValue(source, "pending_moderation", JSONArray.class), soundMapper)); // // pendingUploads.setPendingProcessing( // parseArray(extractFieldValue(source, "pending_processing", JSONArray.class), soundMapper)); // // return pendingUploads; // } // // } // Path: src/main/java/com/sonoport/freesound/query/sound/PendingUploadsQuery.java import java.util.Collections; import java.util.Map; import com.sonoport.freesound.query.HTTPRequestMethod; import com.sonoport.freesound.query.JSONResponseQuery; import com.sonoport.freesound.query.OAuthQuery; import com.sonoport.freesound.response.PendingUploads; import com.sonoport.freesound.response.mapping.PendingUploadsMapper; /* * Copyright 2014 Sonoport (Asia) Pte 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.sonoport.freesound.query.sound; /** * Query class used to retrieve details of sounds that have been uploaded by the current user, but that require * additional steps to be performed before they are made publicly available. * * Full details of API endpoint: http://www.freesound.org/docs/api/resources_apiv2.html#pending-uploads-oauth2-required */ public class PendingUploadsQuery extends JSONResponseQuery<PendingUploads> implements OAuthQuery { /** Path to API endpoint. */ private static final String PATH = "/sounds/pending_uploads/"; /** OAuth2 token to present as credentials. */ private final String ouathToken; /** * @param oauthToken OAuth2 token to present as credentials */ public PendingUploadsQuery(final String oauthToken) {
super(HTTPRequestMethod.GET, PATH, new PendingUploadsMapper());
hprange/woinject
src/test/java/com/woinject/AbstractInjectableTestCase.java
// Path: src/test/java/com/woinject/stubs/StubApplication.java // public class StubApplication extends InjectableApplication { // private static class StubModule extends AbstractModule { // private boolean moduleWasLoaded = false; // // @Override // protected void configure() { // moduleWasLoaded = true; // // bind(String.class).annotatedWith(Names.named("field")).toInstance("fieldInjected"); // bind(String.class).annotatedWith(Names.named("method")).toInstance("methodInjected"); // } // } // // public static void setApplication(WOApplication application) { // try { // Method method = WOApplication.class.getDeclaredMethod("_setApplication", WOApplication.class); // // method.setAccessible(true); // // method.invoke(null, application); // } catch (Exception exception) { // throw new RuntimeException(exception); // } // } // // @Inject // @Named("field") // private String injectableField; // // private String injectableMethod; // // private boolean nullInjector = false; // // private StubModule stubModule; // // @Override // protected Class<StubSession> _sessionClass() { // return StubSession.class; // } // // public String getInjectableField() { // return injectableField; // } // // public String getInjectableMethod() { // return injectableMethod; // } // // @Inject // public void initInjectableMethod(@Named("method") String value) { // injectableMethod = value; // } // // @Override // public Injector injector() { // if (nullInjector) { // return null; // } // // return super.injector(); // } // // @Override // protected Module[] modules() { // stubModule = new StubModule(); // // return new Module[] { stubModule }; // } // // public void setReturnNullInjector(boolean nullInjector) { // this.nullInjector = nullInjector; // } // // public boolean stubModuleWasLoaded() { // return stubModule.moduleWasLoaded; // } // }
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import com.webobjects.foundation.NSBundle; import com.woinject.stubs.StubApplication;
/** * Copyright (C) 2010 hprange <[email protected]> * * 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.woinject; /** * @author <a href="mailto:[email protected]">Henrique Prange</a> */ public abstract class AbstractInjectableTestCase { /** * We have to cheat here in order to make the Application initialization * work. */ @BeforeClass public static void initMainBundle() throws Exception { NSBundle mockBundle = mock(NSBundle.class); when(mockBundle.name()).thenReturn("woinject"); when(mockBundle.bundlePathURL()).thenReturn(TestInjectableApplication.class.getClass().getResource("/")); NSBundle._setMainBundle(mockBundle); }
// Path: src/test/java/com/woinject/stubs/StubApplication.java // public class StubApplication extends InjectableApplication { // private static class StubModule extends AbstractModule { // private boolean moduleWasLoaded = false; // // @Override // protected void configure() { // moduleWasLoaded = true; // // bind(String.class).annotatedWith(Names.named("field")).toInstance("fieldInjected"); // bind(String.class).annotatedWith(Names.named("method")).toInstance("methodInjected"); // } // } // // public static void setApplication(WOApplication application) { // try { // Method method = WOApplication.class.getDeclaredMethod("_setApplication", WOApplication.class); // // method.setAccessible(true); // // method.invoke(null, application); // } catch (Exception exception) { // throw new RuntimeException(exception); // } // } // // @Inject // @Named("field") // private String injectableField; // // private String injectableMethod; // // private boolean nullInjector = false; // // private StubModule stubModule; // // @Override // protected Class<StubSession> _sessionClass() { // return StubSession.class; // } // // public String getInjectableField() { // return injectableField; // } // // public String getInjectableMethod() { // return injectableMethod; // } // // @Inject // public void initInjectableMethod(@Named("method") String value) { // injectableMethod = value; // } // // @Override // public Injector injector() { // if (nullInjector) { // return null; // } // // return super.injector(); // } // // @Override // protected Module[] modules() { // stubModule = new StubModule(); // // return new Module[] { stubModule }; // } // // public void setReturnNullInjector(boolean nullInjector) { // this.nullInjector = nullInjector; // } // // public boolean stubModuleWasLoaded() { // return stubModule.moduleWasLoaded; // } // } // Path: src/test/java/com/woinject/AbstractInjectableTestCase.java import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import com.webobjects.foundation.NSBundle; import com.woinject.stubs.StubApplication; /** * Copyright (C) 2010 hprange <[email protected]> * * 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.woinject; /** * @author <a href="mailto:[email protected]">Henrique Prange</a> */ public abstract class AbstractInjectableTestCase { /** * We have to cheat here in order to make the Application initialization * work. */ @BeforeClass public static void initMainBundle() throws Exception { NSBundle mockBundle = mock(NSBundle.class); when(mockBundle.name()).thenReturn("woinject"); when(mockBundle.bundlePathURL()).thenReturn(TestInjectableApplication.class.getClass().getResource("/")); NSBundle._setMainBundle(mockBundle); }
protected StubApplication application;
hprange/woinject
src/test/java/com/woinject/TestWOInjectModule.java
// Path: src/test/java/com/woinject/stubs/StubSession.java // public class StubSession extends ERXSession { // @Inject // @Named("test") // private String injectedText; // // @Override // public String toString() { // return injectedText; // } // }
import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.lang.annotation.Annotation; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.ProvisionException; import com.google.inject.Scope; import com.webobjects.appserver.WOContext; import com.webobjects.appserver.WOSession; import com.woinject.stubs.StubSession; import er.extensions.appserver.ERXSession; import er.extensions.appserver.ERXWOContext;
/** * Copyright (C) 2010 hprange <[email protected]> * * 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.woinject; /** * @author <a href="mailto:[email protected]">Henrique Prange</a> */ @RunWith(MockitoJUnitRunner.class) public class TestWOInjectModule { private Injector injector; @Mock private WOContext mockContext; @Mock
// Path: src/test/java/com/woinject/stubs/StubSession.java // public class StubSession extends ERXSession { // @Inject // @Named("test") // private String injectedText; // // @Override // public String toString() { // return injectedText; // } // } // Path: src/test/java/com/woinject/TestWOInjectModule.java import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.lang.annotation.Annotation; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.ProvisionException; import com.google.inject.Scope; import com.webobjects.appserver.WOContext; import com.webobjects.appserver.WOSession; import com.woinject.stubs.StubSession; import er.extensions.appserver.ERXSession; import er.extensions.appserver.ERXWOContext; /** * Copyright (C) 2010 hprange <[email protected]> * * 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.woinject; /** * @author <a href="mailto:[email protected]">Henrique Prange</a> */ @RunWith(MockitoJUnitRunner.class) public class TestWOInjectModule { private Injector injector; @Mock private WOContext mockContext; @Mock
private StubSession mockSession;