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
serkan-ozal/mysafe
src/main/java/tr/com/serkanozal/mysafe/impl/storage/DefaultAllocatedMemoryStorage.java
// Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryIterator.java // public interface AllocatedMemoryIterator { // // /** // * Called for each allocated memory. // * // * @param address address of the allocated memory // * @param size size of the allocated memory // */ // void onAllocatedMemory(long address, long size); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryStorage.java // public interface AllocatedMemoryStorage { // // /** // * Represents any invalid value. // */ // long INVALID = -1; // // /** // * Checks if the given address is allocated or not. // * // * @param address the address to be checked if it is allocated or not // * @return <code>true</code> if if the given address is allocated, // * otherwise <code>false</code> // */ // boolean contains(long address); // // /** // * Checks if the specified memory region starting from given address // * as given size is in allocated memory area or not. // * // * @param address the start address of the specified memory region // * @param size the size of the specified memory region // * @return <code>true</code> if if the given specified memory region // * is in allocated memory area, otherwise <code>false</code> // */ // boolean contains(long address, long size); // // /** // * Gets the allocation size of the given address. // * // * @param address the address whose allocation size will be retrieved // * @return allocation size of the given address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long get(long address); // // /** // * Stores given address with its allocation size. // * // * @param address the address // * @param size the allocation size // */ // void put(long address, long size); // // /** // * Removes the given address. // * // * @param address the address to be removed // * @return allocation size of the removed address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long remove(long address); // // /** // * Iterates on the allocated memory addresses. // * // * @param iterator the {@link AllocatedMemoryIterator} instance to be notified // * for each allocated memory while iterating // */ // void iterate(AllocatedMemoryIterator iterator); // // /** // * Returns <tt>true</tt> if storage is empty, otherwise returns <tt>false</tt>. // * // * @return <tt>true</tt> if storage is empty, <tt>false</tt> otherwise // */ // boolean isEmpty(); // // }
import java.util.Map; import org.cliffc.high_scale_lib.NonBlockingHashMapLong; import tr.com.serkanozal.mysafe.AllocatedMemoryIterator; import tr.com.serkanozal.mysafe.AllocatedMemoryStorage;
@Override public boolean contains(long address, long size) { for (Map.Entry<Long, Long> entry : allocatedMemories.entrySet()) { long startAddress = entry.getKey(); long endAddress = startAddress + entry.getValue(); if (address >= startAddress && (address + size) <= endAddress) { return true; } } return false; } @Override public long get(long address) { Long size = allocatedMemories.get(address); return size != null ? size : INVALID; } @Override public void put(long address, long size) { allocatedMemories.put(address, (Long) size); } @Override public long remove(long address) { Long size = allocatedMemories.remove(address); return size != null ? size : INVALID; } @Override
// Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryIterator.java // public interface AllocatedMemoryIterator { // // /** // * Called for each allocated memory. // * // * @param address address of the allocated memory // * @param size size of the allocated memory // */ // void onAllocatedMemory(long address, long size); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryStorage.java // public interface AllocatedMemoryStorage { // // /** // * Represents any invalid value. // */ // long INVALID = -1; // // /** // * Checks if the given address is allocated or not. // * // * @param address the address to be checked if it is allocated or not // * @return <code>true</code> if if the given address is allocated, // * otherwise <code>false</code> // */ // boolean contains(long address); // // /** // * Checks if the specified memory region starting from given address // * as given size is in allocated memory area or not. // * // * @param address the start address of the specified memory region // * @param size the size of the specified memory region // * @return <code>true</code> if if the given specified memory region // * is in allocated memory area, otherwise <code>false</code> // */ // boolean contains(long address, long size); // // /** // * Gets the allocation size of the given address. // * // * @param address the address whose allocation size will be retrieved // * @return allocation size of the given address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long get(long address); // // /** // * Stores given address with its allocation size. // * // * @param address the address // * @param size the allocation size // */ // void put(long address, long size); // // /** // * Removes the given address. // * // * @param address the address to be removed // * @return allocation size of the removed address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long remove(long address); // // /** // * Iterates on the allocated memory addresses. // * // * @param iterator the {@link AllocatedMemoryIterator} instance to be notified // * for each allocated memory while iterating // */ // void iterate(AllocatedMemoryIterator iterator); // // /** // * Returns <tt>true</tt> if storage is empty, otherwise returns <tt>false</tt>. // * // * @return <tt>true</tt> if storage is empty, <tt>false</tt> otherwise // */ // boolean isEmpty(); // // } // Path: src/main/java/tr/com/serkanozal/mysafe/impl/storage/DefaultAllocatedMemoryStorage.java import java.util.Map; import org.cliffc.high_scale_lib.NonBlockingHashMapLong; import tr.com.serkanozal.mysafe.AllocatedMemoryIterator; import tr.com.serkanozal.mysafe.AllocatedMemoryStorage; @Override public boolean contains(long address, long size) { for (Map.Entry<Long, Long> entry : allocatedMemories.entrySet()) { long startAddress = entry.getKey(); long endAddress = startAddress + entry.getValue(); if (address >= startAddress && (address + size) <= endAddress) { return true; } } return false; } @Override public long get(long address) { Long size = allocatedMemories.get(address); return size != null ? size : INVALID; } @Override public void put(long address, long size) { allocatedMemories.put(address, (Long) size); } @Override public long remove(long address) { Long size = allocatedMemories.remove(address); return size != null ? size : INVALID; } @Override
public void iterate(AllocatedMemoryIterator iterator) {
serkan-ozal/mysafe
src/main/java/tr/com/serkanozal/mysafe/impl/AllocationPathDiagramGenerator.java
// Path: src/main/java/tr/com/serkanozal/mysafe/impl/allocpath/AllocationPath.java // public class AllocationPath { // // private static final int MAX_ALLOCATION_PATH_DEPTH_LIMIT = 4; // private static final int DEFAULT_MAX_ALLOCATION_PATH_DEPTH = MAX_ALLOCATION_PATH_DEPTH_LIMIT; // public static final int MAX_ALLOCATION_PATH_DEPTH = // Math.min(MAX_ALLOCATION_PATH_DEPTH_LIMIT, // Integer.getInteger("mysafe.maxAllocationPathDepth", DEFAULT_MAX_ALLOCATION_PATH_DEPTH)); // // public final long key; // public final String[] callPoints; // // public AllocationPath(long key, String[] callPoints) { // this.key = key; // this.callPoints = callPoints; // } // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/impl/allocpath/AllocationPathAllocatedMemory.java // public class AllocationPathAllocatedMemory { // // public final AllocationPath allocationPath; // public final long allocatedMemory; // // public AllocationPathAllocatedMemory(AllocationPath allocationPath, long allocatedMemory) { // this.allocationPath = allocationPath; // this.allocatedMemory = allocatedMemory; // } // // }
import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.util.List; import javax.imageio.ImageIO; import tr.com.serkanozal.mysafe.impl.allocpath.AllocationPath; import tr.com.serkanozal.mysafe.impl.allocpath.AllocationPathAllocatedMemory;
/* * Copyright (c) 2017, Serkan OZAL, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tr.com.serkanozal.mysafe.impl; class AllocationPathDiagramGenerator { static final String DEFAULT_DIAGRAM_NANE = "mysafe-allocation-path.png"; private static final Color ALLOCATION_PATH_FRAME_BACKGROUND_COLOR = new Color(255, 228, 200); private static final Color ALLOCATION_PATH_UNIT_BACKGROUND_COLOR = new Color(228, 255, 255); private static final int ALLOCATION_PATH_FONT_SIZE = 14; private static final int ALLOCATION_PATH_H_GAP = 8; private static final int ALLOCATION_PATH_V_GAP = 8; private static final int ALLOCATION_PATH_UNIT_WIDTH = 800; private static final int ALLOCATION_PATH_UNIT_H_GAP = 50; private static final int ALLOCATION_PATH_FRAME_WIDTH = ALLOCATION_PATH_UNIT_WIDTH + (2 * ALLOCATION_PATH_UNIT_H_GAP); private static final int ALLOCATION_PATH_UNIT_HEIGHT = ALLOCATION_PATH_FONT_SIZE + (2 * ALLOCATION_PATH_V_GAP); private static final int ALLOCATION_PATH_UNIT_V_GAP = 50; private static final int ALLOCATION_PATH_FRAME_HEIGTH =
// Path: src/main/java/tr/com/serkanozal/mysafe/impl/allocpath/AllocationPath.java // public class AllocationPath { // // private static final int MAX_ALLOCATION_PATH_DEPTH_LIMIT = 4; // private static final int DEFAULT_MAX_ALLOCATION_PATH_DEPTH = MAX_ALLOCATION_PATH_DEPTH_LIMIT; // public static final int MAX_ALLOCATION_PATH_DEPTH = // Math.min(MAX_ALLOCATION_PATH_DEPTH_LIMIT, // Integer.getInteger("mysafe.maxAllocationPathDepth", DEFAULT_MAX_ALLOCATION_PATH_DEPTH)); // // public final long key; // public final String[] callPoints; // // public AllocationPath(long key, String[] callPoints) { // this.key = key; // this.callPoints = callPoints; // } // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/impl/allocpath/AllocationPathAllocatedMemory.java // public class AllocationPathAllocatedMemory { // // public final AllocationPath allocationPath; // public final long allocatedMemory; // // public AllocationPathAllocatedMemory(AllocationPath allocationPath, long allocatedMemory) { // this.allocationPath = allocationPath; // this.allocatedMemory = allocatedMemory; // } // // } // Path: src/main/java/tr/com/serkanozal/mysafe/impl/AllocationPathDiagramGenerator.java import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.util.List; import javax.imageio.ImageIO; import tr.com.serkanozal.mysafe.impl.allocpath.AllocationPath; import tr.com.serkanozal.mysafe.impl.allocpath.AllocationPathAllocatedMemory; /* * Copyright (c) 2017, Serkan OZAL, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tr.com.serkanozal.mysafe.impl; class AllocationPathDiagramGenerator { static final String DEFAULT_DIAGRAM_NANE = "mysafe-allocation-path.png"; private static final Color ALLOCATION_PATH_FRAME_BACKGROUND_COLOR = new Color(255, 228, 200); private static final Color ALLOCATION_PATH_UNIT_BACKGROUND_COLOR = new Color(228, 255, 255); private static final int ALLOCATION_PATH_FONT_SIZE = 14; private static final int ALLOCATION_PATH_H_GAP = 8; private static final int ALLOCATION_PATH_V_GAP = 8; private static final int ALLOCATION_PATH_UNIT_WIDTH = 800; private static final int ALLOCATION_PATH_UNIT_H_GAP = 50; private static final int ALLOCATION_PATH_FRAME_WIDTH = ALLOCATION_PATH_UNIT_WIDTH + (2 * ALLOCATION_PATH_UNIT_H_GAP); private static final int ALLOCATION_PATH_UNIT_HEIGHT = ALLOCATION_PATH_FONT_SIZE + (2 * ALLOCATION_PATH_V_GAP); private static final int ALLOCATION_PATH_UNIT_V_GAP = 50; private static final int ALLOCATION_PATH_FRAME_HEIGTH =
((AllocationPath.MAX_ALLOCATION_PATH_DEPTH + 1) * ALLOCATION_PATH_UNIT_HEIGHT)
serkan-ozal/mysafe
src/main/java/tr/com/serkanozal/mysafe/impl/AllocationPathDiagramGenerator.java
// Path: src/main/java/tr/com/serkanozal/mysafe/impl/allocpath/AllocationPath.java // public class AllocationPath { // // private static final int MAX_ALLOCATION_PATH_DEPTH_LIMIT = 4; // private static final int DEFAULT_MAX_ALLOCATION_PATH_DEPTH = MAX_ALLOCATION_PATH_DEPTH_LIMIT; // public static final int MAX_ALLOCATION_PATH_DEPTH = // Math.min(MAX_ALLOCATION_PATH_DEPTH_LIMIT, // Integer.getInteger("mysafe.maxAllocationPathDepth", DEFAULT_MAX_ALLOCATION_PATH_DEPTH)); // // public final long key; // public final String[] callPoints; // // public AllocationPath(long key, String[] callPoints) { // this.key = key; // this.callPoints = callPoints; // } // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/impl/allocpath/AllocationPathAllocatedMemory.java // public class AllocationPathAllocatedMemory { // // public final AllocationPath allocationPath; // public final long allocatedMemory; // // public AllocationPathAllocatedMemory(AllocationPath allocationPath, long allocatedMemory) { // this.allocationPath = allocationPath; // this.allocatedMemory = allocatedMemory; // } // // }
import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.util.List; import javax.imageio.ImageIO; import tr.com.serkanozal.mysafe.impl.allocpath.AllocationPath; import tr.com.serkanozal.mysafe.impl.allocpath.AllocationPathAllocatedMemory;
/* * Copyright (c) 2017, Serkan OZAL, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tr.com.serkanozal.mysafe.impl; class AllocationPathDiagramGenerator { static final String DEFAULT_DIAGRAM_NANE = "mysafe-allocation-path.png"; private static final Color ALLOCATION_PATH_FRAME_BACKGROUND_COLOR = new Color(255, 228, 200); private static final Color ALLOCATION_PATH_UNIT_BACKGROUND_COLOR = new Color(228, 255, 255); private static final int ALLOCATION_PATH_FONT_SIZE = 14; private static final int ALLOCATION_PATH_H_GAP = 8; private static final int ALLOCATION_PATH_V_GAP = 8; private static final int ALLOCATION_PATH_UNIT_WIDTH = 800; private static final int ALLOCATION_PATH_UNIT_H_GAP = 50; private static final int ALLOCATION_PATH_FRAME_WIDTH = ALLOCATION_PATH_UNIT_WIDTH + (2 * ALLOCATION_PATH_UNIT_H_GAP); private static final int ALLOCATION_PATH_UNIT_HEIGHT = ALLOCATION_PATH_FONT_SIZE + (2 * ALLOCATION_PATH_V_GAP); private static final int ALLOCATION_PATH_UNIT_V_GAP = 50; private static final int ALLOCATION_PATH_FRAME_HEIGTH = ((AllocationPath.MAX_ALLOCATION_PATH_DEPTH + 1) * ALLOCATION_PATH_UNIT_HEIGHT) + ((AllocationPath.MAX_ALLOCATION_PATH_DEPTH + 1 + 1) * ALLOCATION_PATH_UNIT_V_GAP); static void generateAllocationPathDiagram(String diagramName,
// Path: src/main/java/tr/com/serkanozal/mysafe/impl/allocpath/AllocationPath.java // public class AllocationPath { // // private static final int MAX_ALLOCATION_PATH_DEPTH_LIMIT = 4; // private static final int DEFAULT_MAX_ALLOCATION_PATH_DEPTH = MAX_ALLOCATION_PATH_DEPTH_LIMIT; // public static final int MAX_ALLOCATION_PATH_DEPTH = // Math.min(MAX_ALLOCATION_PATH_DEPTH_LIMIT, // Integer.getInteger("mysafe.maxAllocationPathDepth", DEFAULT_MAX_ALLOCATION_PATH_DEPTH)); // // public final long key; // public final String[] callPoints; // // public AllocationPath(long key, String[] callPoints) { // this.key = key; // this.callPoints = callPoints; // } // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/impl/allocpath/AllocationPathAllocatedMemory.java // public class AllocationPathAllocatedMemory { // // public final AllocationPath allocationPath; // public final long allocatedMemory; // // public AllocationPathAllocatedMemory(AllocationPath allocationPath, long allocatedMemory) { // this.allocationPath = allocationPath; // this.allocatedMemory = allocatedMemory; // } // // } // Path: src/main/java/tr/com/serkanozal/mysafe/impl/AllocationPathDiagramGenerator.java import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.util.List; import javax.imageio.ImageIO; import tr.com.serkanozal.mysafe.impl.allocpath.AllocationPath; import tr.com.serkanozal.mysafe.impl.allocpath.AllocationPathAllocatedMemory; /* * Copyright (c) 2017, Serkan OZAL, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tr.com.serkanozal.mysafe.impl; class AllocationPathDiagramGenerator { static final String DEFAULT_DIAGRAM_NANE = "mysafe-allocation-path.png"; private static final Color ALLOCATION_PATH_FRAME_BACKGROUND_COLOR = new Color(255, 228, 200); private static final Color ALLOCATION_PATH_UNIT_BACKGROUND_COLOR = new Color(228, 255, 255); private static final int ALLOCATION_PATH_FONT_SIZE = 14; private static final int ALLOCATION_PATH_H_GAP = 8; private static final int ALLOCATION_PATH_V_GAP = 8; private static final int ALLOCATION_PATH_UNIT_WIDTH = 800; private static final int ALLOCATION_PATH_UNIT_H_GAP = 50; private static final int ALLOCATION_PATH_FRAME_WIDTH = ALLOCATION_PATH_UNIT_WIDTH + (2 * ALLOCATION_PATH_UNIT_H_GAP); private static final int ALLOCATION_PATH_UNIT_HEIGHT = ALLOCATION_PATH_FONT_SIZE + (2 * ALLOCATION_PATH_V_GAP); private static final int ALLOCATION_PATH_UNIT_V_GAP = 50; private static final int ALLOCATION_PATH_FRAME_HEIGTH = ((AllocationPath.MAX_ALLOCATION_PATH_DEPTH + 1) * ALLOCATION_PATH_UNIT_HEIGHT) + ((AllocationPath.MAX_ALLOCATION_PATH_DEPTH + 1 + 1) * ALLOCATION_PATH_UNIT_V_GAP); static void generateAllocationPathDiagram(String diagramName,
List<AllocationPathAllocatedMemory> allocationPathAllocatedMemories) {
serkan-ozal/mysafe
src/main/java/tr/com/serkanozal/mysafe/impl/storage/NavigatableAllocatedMemoryStorage.java
// Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryIterator.java // public interface AllocatedMemoryIterator { // // /** // * Called for each allocated memory. // * // * @param address address of the allocated memory // * @param size size of the allocated memory // */ // void onAllocatedMemory(long address, long size); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryStorage.java // public interface AllocatedMemoryStorage { // // /** // * Represents any invalid value. // */ // long INVALID = -1; // // /** // * Checks if the given address is allocated or not. // * // * @param address the address to be checked if it is allocated or not // * @return <code>true</code> if if the given address is allocated, // * otherwise <code>false</code> // */ // boolean contains(long address); // // /** // * Checks if the specified memory region starting from given address // * as given size is in allocated memory area or not. // * // * @param address the start address of the specified memory region // * @param size the size of the specified memory region // * @return <code>true</code> if if the given specified memory region // * is in allocated memory area, otherwise <code>false</code> // */ // boolean contains(long address, long size); // // /** // * Gets the allocation size of the given address. // * // * @param address the address whose allocation size will be retrieved // * @return allocation size of the given address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long get(long address); // // /** // * Stores given address with its allocation size. // * // * @param address the address // * @param size the allocation size // */ // void put(long address, long size); // // /** // * Removes the given address. // * // * @param address the address to be removed // * @return allocation size of the removed address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long remove(long address); // // /** // * Iterates on the allocated memory addresses. // * // * @param iterator the {@link AllocatedMemoryIterator} instance to be notified // * for each allocated memory while iterating // */ // void iterate(AllocatedMemoryIterator iterator); // // /** // * Returns <tt>true</tt> if storage is empty, otherwise returns <tt>false</tt>. // * // * @return <tt>true</tt> if storage is empty, <tt>false</tt> otherwise // */ // boolean isEmpty(); // // }
import java.util.Map; import java.util.NavigableMap; import java.util.concurrent.ConcurrentSkipListMap; import tr.com.serkanozal.mysafe.AllocatedMemoryIterator; import tr.com.serkanozal.mysafe.AllocatedMemoryStorage;
@Override public boolean contains(long address, long size) { Map.Entry<Long, Long> entry = allocatedMemories.floorEntry(address); if (entry == null) { return false; } long startAddress = entry.getKey(); long endAddress = startAddress + entry.getValue(); return address >= startAddress && (address + size) <= endAddress; } @Override public long get(long address) { Long size = allocatedMemories.get(address); return size != null ? size : INVALID; } @Override public void put(long address, long size) { allocatedMemories.put(address, size); } @Override public long remove(long address) { Long size = allocatedMemories.remove(address); return size != null ? size : INVALID; } @Override
// Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryIterator.java // public interface AllocatedMemoryIterator { // // /** // * Called for each allocated memory. // * // * @param address address of the allocated memory // * @param size size of the allocated memory // */ // void onAllocatedMemory(long address, long size); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryStorage.java // public interface AllocatedMemoryStorage { // // /** // * Represents any invalid value. // */ // long INVALID = -1; // // /** // * Checks if the given address is allocated or not. // * // * @param address the address to be checked if it is allocated or not // * @return <code>true</code> if if the given address is allocated, // * otherwise <code>false</code> // */ // boolean contains(long address); // // /** // * Checks if the specified memory region starting from given address // * as given size is in allocated memory area or not. // * // * @param address the start address of the specified memory region // * @param size the size of the specified memory region // * @return <code>true</code> if if the given specified memory region // * is in allocated memory area, otherwise <code>false</code> // */ // boolean contains(long address, long size); // // /** // * Gets the allocation size of the given address. // * // * @param address the address whose allocation size will be retrieved // * @return allocation size of the given address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long get(long address); // // /** // * Stores given address with its allocation size. // * // * @param address the address // * @param size the allocation size // */ // void put(long address, long size); // // /** // * Removes the given address. // * // * @param address the address to be removed // * @return allocation size of the removed address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long remove(long address); // // /** // * Iterates on the allocated memory addresses. // * // * @param iterator the {@link AllocatedMemoryIterator} instance to be notified // * for each allocated memory while iterating // */ // void iterate(AllocatedMemoryIterator iterator); // // /** // * Returns <tt>true</tt> if storage is empty, otherwise returns <tt>false</tt>. // * // * @return <tt>true</tt> if storage is empty, <tt>false</tt> otherwise // */ // boolean isEmpty(); // // } // Path: src/main/java/tr/com/serkanozal/mysafe/impl/storage/NavigatableAllocatedMemoryStorage.java import java.util.Map; import java.util.NavigableMap; import java.util.concurrent.ConcurrentSkipListMap; import tr.com.serkanozal.mysafe.AllocatedMemoryIterator; import tr.com.serkanozal.mysafe.AllocatedMemoryStorage; @Override public boolean contains(long address, long size) { Map.Entry<Long, Long> entry = allocatedMemories.floorEntry(address); if (entry == null) { return false; } long startAddress = entry.getKey(); long endAddress = startAddress + entry.getValue(); return address >= startAddress && (address + size) <= endAddress; } @Override public long get(long address) { Long size = allocatedMemories.get(address); return size != null ? size : INVALID; } @Override public void put(long address, long size) { allocatedMemories.put(address, size); } @Override public long remove(long address) { Long size = allocatedMemories.remove(address); return size != null ? size : INVALID; } @Override
public void iterate(AllocatedMemoryIterator iterator) {
serkan-ozal/mysafe
src/main/java/tr/com/serkanozal/mysafe/impl/instrument/CustomMemoryManagementInstrumenter.java
// Path: src/main/java/tr/com/serkanozal/mysafe/config/AllocationPointConfig.java // public class AllocationPointConfig { // // public static final int DEFAULT_SIZE_PARAMETER_ORDER = 1; // // public final int sizeParameterOrder; // // public AllocationPointConfig() { // this.sizeParameterOrder = DEFAULT_SIZE_PARAMETER_ORDER; // } // // public AllocationPointConfig(int sizeParameterOrder) { // this.sizeParameterOrder = sizeParameterOrder; // } // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/config/FreePointConfig.java // public class FreePointConfig { // // public static final int DEFAULT_ADDRESS_PARAMETER_ORDER = 1; // // public final int addressParameterOrder; // // public FreePointConfig() { // this.addressParameterOrder = DEFAULT_ADDRESS_PARAMETER_ORDER; // } // // public FreePointConfig(int addressParameterOrder) { // this.addressParameterOrder = addressParameterOrder; // } // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/config/ReallocationPointConfig.java // public class ReallocationPointConfig { // // public static final int DEFAULT_OLD_ADDRESS_PARAMETER_ORDER = 1; // public static final int DEFAULT_NEW_SIZE_PARAMETER_ORDER = 2; // // public final int oldAddressParameterOrder; // public final int newSizeParameterOrder; // // public ReallocationPointConfig() { // this.oldAddressParameterOrder = DEFAULT_OLD_ADDRESS_PARAMETER_ORDER; // this.newSizeParameterOrder = DEFAULT_NEW_SIZE_PARAMETER_ORDER; // } // // public ReallocationPointConfig(int oldAddressParameterOrder) { // this.oldAddressParameterOrder = oldAddressParameterOrder; // this.newSizeParameterOrder = DEFAULT_NEW_SIZE_PARAMETER_ORDER; // } // // public ReallocationPointConfig(int oldAddressParameterOrder, int newSizeParameterOrder) { // this.oldAddressParameterOrder = oldAddressParameterOrder; // this.newSizeParameterOrder = newSizeParameterOrder; // } // // }
import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import static tr.com.serkanozal.mysafe.AllocatedMemoryStorage.INVALID; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Properties; import tr.com.serkanozal.mysafe.config.AllocationPoint; import tr.com.serkanozal.mysafe.config.AllocationPointConfig; import tr.com.serkanozal.mysafe.config.FreePoint; import tr.com.serkanozal.mysafe.config.FreePointConfig; import tr.com.serkanozal.mysafe.config.ReallocationPoint; import tr.com.serkanozal.mysafe.config.ReallocationPointConfig;
/* * Copyright (c) 2017, Serkan OZAL, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tr.com.serkanozal.mysafe.impl.instrument; class CustomMemoryManagementInstrumenter implements MySafeInstrumenter { private final boolean USE_CUSTOM_MEMORY_MANAGEMENT = Boolean.getBoolean("mysafe.useCustomMemoryManagement"); private final String CUSTOM_MEMORY_MANAGEMENT_PACKAGE_PREFIX = System.getProperty("mysafe.customMemoryManagementPackagePrefix"); private final ClassPool CP = new MySafeClassPool();
// Path: src/main/java/tr/com/serkanozal/mysafe/config/AllocationPointConfig.java // public class AllocationPointConfig { // // public static final int DEFAULT_SIZE_PARAMETER_ORDER = 1; // // public final int sizeParameterOrder; // // public AllocationPointConfig() { // this.sizeParameterOrder = DEFAULT_SIZE_PARAMETER_ORDER; // } // // public AllocationPointConfig(int sizeParameterOrder) { // this.sizeParameterOrder = sizeParameterOrder; // } // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/config/FreePointConfig.java // public class FreePointConfig { // // public static final int DEFAULT_ADDRESS_PARAMETER_ORDER = 1; // // public final int addressParameterOrder; // // public FreePointConfig() { // this.addressParameterOrder = DEFAULT_ADDRESS_PARAMETER_ORDER; // } // // public FreePointConfig(int addressParameterOrder) { // this.addressParameterOrder = addressParameterOrder; // } // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/config/ReallocationPointConfig.java // public class ReallocationPointConfig { // // public static final int DEFAULT_OLD_ADDRESS_PARAMETER_ORDER = 1; // public static final int DEFAULT_NEW_SIZE_PARAMETER_ORDER = 2; // // public final int oldAddressParameterOrder; // public final int newSizeParameterOrder; // // public ReallocationPointConfig() { // this.oldAddressParameterOrder = DEFAULT_OLD_ADDRESS_PARAMETER_ORDER; // this.newSizeParameterOrder = DEFAULT_NEW_SIZE_PARAMETER_ORDER; // } // // public ReallocationPointConfig(int oldAddressParameterOrder) { // this.oldAddressParameterOrder = oldAddressParameterOrder; // this.newSizeParameterOrder = DEFAULT_NEW_SIZE_PARAMETER_ORDER; // } // // public ReallocationPointConfig(int oldAddressParameterOrder, int newSizeParameterOrder) { // this.oldAddressParameterOrder = oldAddressParameterOrder; // this.newSizeParameterOrder = newSizeParameterOrder; // } // // } // Path: src/main/java/tr/com/serkanozal/mysafe/impl/instrument/CustomMemoryManagementInstrumenter.java import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import static tr.com.serkanozal.mysafe.AllocatedMemoryStorage.INVALID; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Properties; import tr.com.serkanozal.mysafe.config.AllocationPoint; import tr.com.serkanozal.mysafe.config.AllocationPointConfig; import tr.com.serkanozal.mysafe.config.FreePoint; import tr.com.serkanozal.mysafe.config.FreePointConfig; import tr.com.serkanozal.mysafe.config.ReallocationPoint; import tr.com.serkanozal.mysafe.config.ReallocationPointConfig; /* * Copyright (c) 2017, Serkan OZAL, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tr.com.serkanozal.mysafe.impl.instrument; class CustomMemoryManagementInstrumenter implements MySafeInstrumenter { private final boolean USE_CUSTOM_MEMORY_MANAGEMENT = Boolean.getBoolean("mysafe.useCustomMemoryManagement"); private final String CUSTOM_MEMORY_MANAGEMENT_PACKAGE_PREFIX = System.getProperty("mysafe.customMemoryManagementPackagePrefix"); private final ClassPool CP = new MySafeClassPool();
private Map<String, AllocationPointConfig> configuredAllocationPoints;
serkan-ozal/mysafe
src/main/java/tr/com/serkanozal/mysafe/impl/instrument/CustomMemoryManagementInstrumenter.java
// Path: src/main/java/tr/com/serkanozal/mysafe/config/AllocationPointConfig.java // public class AllocationPointConfig { // // public static final int DEFAULT_SIZE_PARAMETER_ORDER = 1; // // public final int sizeParameterOrder; // // public AllocationPointConfig() { // this.sizeParameterOrder = DEFAULT_SIZE_PARAMETER_ORDER; // } // // public AllocationPointConfig(int sizeParameterOrder) { // this.sizeParameterOrder = sizeParameterOrder; // } // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/config/FreePointConfig.java // public class FreePointConfig { // // public static final int DEFAULT_ADDRESS_PARAMETER_ORDER = 1; // // public final int addressParameterOrder; // // public FreePointConfig() { // this.addressParameterOrder = DEFAULT_ADDRESS_PARAMETER_ORDER; // } // // public FreePointConfig(int addressParameterOrder) { // this.addressParameterOrder = addressParameterOrder; // } // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/config/ReallocationPointConfig.java // public class ReallocationPointConfig { // // public static final int DEFAULT_OLD_ADDRESS_PARAMETER_ORDER = 1; // public static final int DEFAULT_NEW_SIZE_PARAMETER_ORDER = 2; // // public final int oldAddressParameterOrder; // public final int newSizeParameterOrder; // // public ReallocationPointConfig() { // this.oldAddressParameterOrder = DEFAULT_OLD_ADDRESS_PARAMETER_ORDER; // this.newSizeParameterOrder = DEFAULT_NEW_SIZE_PARAMETER_ORDER; // } // // public ReallocationPointConfig(int oldAddressParameterOrder) { // this.oldAddressParameterOrder = oldAddressParameterOrder; // this.newSizeParameterOrder = DEFAULT_NEW_SIZE_PARAMETER_ORDER; // } // // public ReallocationPointConfig(int oldAddressParameterOrder, int newSizeParameterOrder) { // this.oldAddressParameterOrder = oldAddressParameterOrder; // this.newSizeParameterOrder = newSizeParameterOrder; // } // // }
import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import static tr.com.serkanozal.mysafe.AllocatedMemoryStorage.INVALID; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Properties; import tr.com.serkanozal.mysafe.config.AllocationPoint; import tr.com.serkanozal.mysafe.config.AllocationPointConfig; import tr.com.serkanozal.mysafe.config.FreePoint; import tr.com.serkanozal.mysafe.config.FreePointConfig; import tr.com.serkanozal.mysafe.config.ReallocationPoint; import tr.com.serkanozal.mysafe.config.ReallocationPointConfig;
/* * Copyright (c) 2017, Serkan OZAL, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tr.com.serkanozal.mysafe.impl.instrument; class CustomMemoryManagementInstrumenter implements MySafeInstrumenter { private final boolean USE_CUSTOM_MEMORY_MANAGEMENT = Boolean.getBoolean("mysafe.useCustomMemoryManagement"); private final String CUSTOM_MEMORY_MANAGEMENT_PACKAGE_PREFIX = System.getProperty("mysafe.customMemoryManagementPackagePrefix"); private final ClassPool CP = new MySafeClassPool(); private Map<String, AllocationPointConfig> configuredAllocationPoints;
// Path: src/main/java/tr/com/serkanozal/mysafe/config/AllocationPointConfig.java // public class AllocationPointConfig { // // public static final int DEFAULT_SIZE_PARAMETER_ORDER = 1; // // public final int sizeParameterOrder; // // public AllocationPointConfig() { // this.sizeParameterOrder = DEFAULT_SIZE_PARAMETER_ORDER; // } // // public AllocationPointConfig(int sizeParameterOrder) { // this.sizeParameterOrder = sizeParameterOrder; // } // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/config/FreePointConfig.java // public class FreePointConfig { // // public static final int DEFAULT_ADDRESS_PARAMETER_ORDER = 1; // // public final int addressParameterOrder; // // public FreePointConfig() { // this.addressParameterOrder = DEFAULT_ADDRESS_PARAMETER_ORDER; // } // // public FreePointConfig(int addressParameterOrder) { // this.addressParameterOrder = addressParameterOrder; // } // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/config/ReallocationPointConfig.java // public class ReallocationPointConfig { // // public static final int DEFAULT_OLD_ADDRESS_PARAMETER_ORDER = 1; // public static final int DEFAULT_NEW_SIZE_PARAMETER_ORDER = 2; // // public final int oldAddressParameterOrder; // public final int newSizeParameterOrder; // // public ReallocationPointConfig() { // this.oldAddressParameterOrder = DEFAULT_OLD_ADDRESS_PARAMETER_ORDER; // this.newSizeParameterOrder = DEFAULT_NEW_SIZE_PARAMETER_ORDER; // } // // public ReallocationPointConfig(int oldAddressParameterOrder) { // this.oldAddressParameterOrder = oldAddressParameterOrder; // this.newSizeParameterOrder = DEFAULT_NEW_SIZE_PARAMETER_ORDER; // } // // public ReallocationPointConfig(int oldAddressParameterOrder, int newSizeParameterOrder) { // this.oldAddressParameterOrder = oldAddressParameterOrder; // this.newSizeParameterOrder = newSizeParameterOrder; // } // // } // Path: src/main/java/tr/com/serkanozal/mysafe/impl/instrument/CustomMemoryManagementInstrumenter.java import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import static tr.com.serkanozal.mysafe.AllocatedMemoryStorage.INVALID; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Properties; import tr.com.serkanozal.mysafe.config.AllocationPoint; import tr.com.serkanozal.mysafe.config.AllocationPointConfig; import tr.com.serkanozal.mysafe.config.FreePoint; import tr.com.serkanozal.mysafe.config.FreePointConfig; import tr.com.serkanozal.mysafe.config.ReallocationPoint; import tr.com.serkanozal.mysafe.config.ReallocationPointConfig; /* * Copyright (c) 2017, Serkan OZAL, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tr.com.serkanozal.mysafe.impl.instrument; class CustomMemoryManagementInstrumenter implements MySafeInstrumenter { private final boolean USE_CUSTOM_MEMORY_MANAGEMENT = Boolean.getBoolean("mysafe.useCustomMemoryManagement"); private final String CUSTOM_MEMORY_MANAGEMENT_PACKAGE_PREFIX = System.getProperty("mysafe.customMemoryManagementPackagePrefix"); private final ClassPool CP = new MySafeClassPool(); private Map<String, AllocationPointConfig> configuredAllocationPoints;
private Map<String, FreePointConfig> configuredFreePoints;
serkan-ozal/mysafe
src/main/java/tr/com/serkanozal/mysafe/impl/instrument/CustomMemoryManagementInstrumenter.java
// Path: src/main/java/tr/com/serkanozal/mysafe/config/AllocationPointConfig.java // public class AllocationPointConfig { // // public static final int DEFAULT_SIZE_PARAMETER_ORDER = 1; // // public final int sizeParameterOrder; // // public AllocationPointConfig() { // this.sizeParameterOrder = DEFAULT_SIZE_PARAMETER_ORDER; // } // // public AllocationPointConfig(int sizeParameterOrder) { // this.sizeParameterOrder = sizeParameterOrder; // } // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/config/FreePointConfig.java // public class FreePointConfig { // // public static final int DEFAULT_ADDRESS_PARAMETER_ORDER = 1; // // public final int addressParameterOrder; // // public FreePointConfig() { // this.addressParameterOrder = DEFAULT_ADDRESS_PARAMETER_ORDER; // } // // public FreePointConfig(int addressParameterOrder) { // this.addressParameterOrder = addressParameterOrder; // } // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/config/ReallocationPointConfig.java // public class ReallocationPointConfig { // // public static final int DEFAULT_OLD_ADDRESS_PARAMETER_ORDER = 1; // public static final int DEFAULT_NEW_SIZE_PARAMETER_ORDER = 2; // // public final int oldAddressParameterOrder; // public final int newSizeParameterOrder; // // public ReallocationPointConfig() { // this.oldAddressParameterOrder = DEFAULT_OLD_ADDRESS_PARAMETER_ORDER; // this.newSizeParameterOrder = DEFAULT_NEW_SIZE_PARAMETER_ORDER; // } // // public ReallocationPointConfig(int oldAddressParameterOrder) { // this.oldAddressParameterOrder = oldAddressParameterOrder; // this.newSizeParameterOrder = DEFAULT_NEW_SIZE_PARAMETER_ORDER; // } // // public ReallocationPointConfig(int oldAddressParameterOrder, int newSizeParameterOrder) { // this.oldAddressParameterOrder = oldAddressParameterOrder; // this.newSizeParameterOrder = newSizeParameterOrder; // } // // }
import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import static tr.com.serkanozal.mysafe.AllocatedMemoryStorage.INVALID; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Properties; import tr.com.serkanozal.mysafe.config.AllocationPoint; import tr.com.serkanozal.mysafe.config.AllocationPointConfig; import tr.com.serkanozal.mysafe.config.FreePoint; import tr.com.serkanozal.mysafe.config.FreePointConfig; import tr.com.serkanozal.mysafe.config.ReallocationPoint; import tr.com.serkanozal.mysafe.config.ReallocationPointConfig;
/* * Copyright (c) 2017, Serkan OZAL, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tr.com.serkanozal.mysafe.impl.instrument; class CustomMemoryManagementInstrumenter implements MySafeInstrumenter { private final boolean USE_CUSTOM_MEMORY_MANAGEMENT = Boolean.getBoolean("mysafe.useCustomMemoryManagement"); private final String CUSTOM_MEMORY_MANAGEMENT_PACKAGE_PREFIX = System.getProperty("mysafe.customMemoryManagementPackagePrefix"); private final ClassPool CP = new MySafeClassPool(); private Map<String, AllocationPointConfig> configuredAllocationPoints; private Map<String, FreePointConfig> configuredFreePoints;
// Path: src/main/java/tr/com/serkanozal/mysafe/config/AllocationPointConfig.java // public class AllocationPointConfig { // // public static final int DEFAULT_SIZE_PARAMETER_ORDER = 1; // // public final int sizeParameterOrder; // // public AllocationPointConfig() { // this.sizeParameterOrder = DEFAULT_SIZE_PARAMETER_ORDER; // } // // public AllocationPointConfig(int sizeParameterOrder) { // this.sizeParameterOrder = sizeParameterOrder; // } // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/config/FreePointConfig.java // public class FreePointConfig { // // public static final int DEFAULT_ADDRESS_PARAMETER_ORDER = 1; // // public final int addressParameterOrder; // // public FreePointConfig() { // this.addressParameterOrder = DEFAULT_ADDRESS_PARAMETER_ORDER; // } // // public FreePointConfig(int addressParameterOrder) { // this.addressParameterOrder = addressParameterOrder; // } // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/config/ReallocationPointConfig.java // public class ReallocationPointConfig { // // public static final int DEFAULT_OLD_ADDRESS_PARAMETER_ORDER = 1; // public static final int DEFAULT_NEW_SIZE_PARAMETER_ORDER = 2; // // public final int oldAddressParameterOrder; // public final int newSizeParameterOrder; // // public ReallocationPointConfig() { // this.oldAddressParameterOrder = DEFAULT_OLD_ADDRESS_PARAMETER_ORDER; // this.newSizeParameterOrder = DEFAULT_NEW_SIZE_PARAMETER_ORDER; // } // // public ReallocationPointConfig(int oldAddressParameterOrder) { // this.oldAddressParameterOrder = oldAddressParameterOrder; // this.newSizeParameterOrder = DEFAULT_NEW_SIZE_PARAMETER_ORDER; // } // // public ReallocationPointConfig(int oldAddressParameterOrder, int newSizeParameterOrder) { // this.oldAddressParameterOrder = oldAddressParameterOrder; // this.newSizeParameterOrder = newSizeParameterOrder; // } // // } // Path: src/main/java/tr/com/serkanozal/mysafe/impl/instrument/CustomMemoryManagementInstrumenter.java import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import static tr.com.serkanozal.mysafe.AllocatedMemoryStorage.INVALID; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Properties; import tr.com.serkanozal.mysafe.config.AllocationPoint; import tr.com.serkanozal.mysafe.config.AllocationPointConfig; import tr.com.serkanozal.mysafe.config.FreePoint; import tr.com.serkanozal.mysafe.config.FreePointConfig; import tr.com.serkanozal.mysafe.config.ReallocationPoint; import tr.com.serkanozal.mysafe.config.ReallocationPointConfig; /* * Copyright (c) 2017, Serkan OZAL, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tr.com.serkanozal.mysafe.impl.instrument; class CustomMemoryManagementInstrumenter implements MySafeInstrumenter { private final boolean USE_CUSTOM_MEMORY_MANAGEMENT = Boolean.getBoolean("mysafe.useCustomMemoryManagement"); private final String CUSTOM_MEMORY_MANAGEMENT_PACKAGE_PREFIX = System.getProperty("mysafe.customMemoryManagementPackagePrefix"); private final ClassPool CP = new MySafeClassPool(); private Map<String, AllocationPointConfig> configuredAllocationPoints; private Map<String, FreePointConfig> configuredFreePoints;
private Map<String, ReallocationPointConfig> configuredReallocationPoints;
serkan-ozal/mysafe
src/main/java/tr/com/serkanozal/mysafe/impl/storage/ThreadLocalNavigatableAllocatedMemoryStorage.java
// Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryIterator.java // public interface AllocatedMemoryIterator { // // /** // * Called for each allocated memory. // * // * @param address address of the allocated memory // * @param size size of the allocated memory // */ // void onAllocatedMemory(long address, long size); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryStorage.java // public interface AllocatedMemoryStorage { // // /** // * Represents any invalid value. // */ // long INVALID = -1; // // /** // * Checks if the given address is allocated or not. // * // * @param address the address to be checked if it is allocated or not // * @return <code>true</code> if if the given address is allocated, // * otherwise <code>false</code> // */ // boolean contains(long address); // // /** // * Checks if the specified memory region starting from given address // * as given size is in allocated memory area or not. // * // * @param address the start address of the specified memory region // * @param size the size of the specified memory region // * @return <code>true</code> if if the given specified memory region // * is in allocated memory area, otherwise <code>false</code> // */ // boolean contains(long address, long size); // // /** // * Gets the allocation size of the given address. // * // * @param address the address whose allocation size will be retrieved // * @return allocation size of the given address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long get(long address); // // /** // * Stores given address with its allocation size. // * // * @param address the address // * @param size the allocation size // */ // void put(long address, long size); // // /** // * Removes the given address. // * // * @param address the address to be removed // * @return allocation size of the removed address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long remove(long address); // // /** // * Iterates on the allocated memory addresses. // * // * @param iterator the {@link AllocatedMemoryIterator} instance to be notified // * for each allocated memory while iterating // */ // void iterate(AllocatedMemoryIterator iterator); // // /** // * Returns <tt>true</tt> if storage is empty, otherwise returns <tt>false</tt>. // * // * @return <tt>true</tt> if storage is empty, <tt>false</tt> otherwise // */ // boolean isEmpty(); // // }
import it.unimi.dsi.fastutil.longs.Long2LongAVLTreeMap; import it.unimi.dsi.fastutil.longs.Long2LongMap; import it.unimi.dsi.fastutil.longs.Long2LongSortedMap; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import sun.misc.Unsafe; import tr.com.serkanozal.mysafe.AllocatedMemoryIterator; import tr.com.serkanozal.mysafe.AllocatedMemoryStorage;
/* * Copyright (c) 2017, Serkan OZAL, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tr.com.serkanozal.mysafe.impl.storage; public class ThreadLocalNavigatableAllocatedMemoryStorage extends AbstractThreadLocalAllocatedMemoryStorage { private static final boolean USE_INDEXED_MEMORY_ACCESS_CHECK = Boolean.getBoolean("mysafe.useIndexedMemoryAccessCheck"); private final IndexedMemoryAccessChecker indexedMemoryAccessChecker; public ThreadLocalNavigatableAllocatedMemoryStorage(Unsafe unsafe, ScheduledExecutorService scheduler) { super(unsafe, scheduler); if (USE_INDEXED_MEMORY_ACCESS_CHECK) { indexedMemoryAccessChecker = new IndexedMemoryAccessChecker(unsafe); } else { indexedMemoryAccessChecker = null; } } @Override
// Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryIterator.java // public interface AllocatedMemoryIterator { // // /** // * Called for each allocated memory. // * // * @param address address of the allocated memory // * @param size size of the allocated memory // */ // void onAllocatedMemory(long address, long size); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryStorage.java // public interface AllocatedMemoryStorage { // // /** // * Represents any invalid value. // */ // long INVALID = -1; // // /** // * Checks if the given address is allocated or not. // * // * @param address the address to be checked if it is allocated or not // * @return <code>true</code> if if the given address is allocated, // * otherwise <code>false</code> // */ // boolean contains(long address); // // /** // * Checks if the specified memory region starting from given address // * as given size is in allocated memory area or not. // * // * @param address the start address of the specified memory region // * @param size the size of the specified memory region // * @return <code>true</code> if if the given specified memory region // * is in allocated memory area, otherwise <code>false</code> // */ // boolean contains(long address, long size); // // /** // * Gets the allocation size of the given address. // * // * @param address the address whose allocation size will be retrieved // * @return allocation size of the given address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long get(long address); // // /** // * Stores given address with its allocation size. // * // * @param address the address // * @param size the allocation size // */ // void put(long address, long size); // // /** // * Removes the given address. // * // * @param address the address to be removed // * @return allocation size of the removed address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long remove(long address); // // /** // * Iterates on the allocated memory addresses. // * // * @param iterator the {@link AllocatedMemoryIterator} instance to be notified // * for each allocated memory while iterating // */ // void iterate(AllocatedMemoryIterator iterator); // // /** // * Returns <tt>true</tt> if storage is empty, otherwise returns <tt>false</tt>. // * // * @return <tt>true</tt> if storage is empty, <tt>false</tt> otherwise // */ // boolean isEmpty(); // // } // Path: src/main/java/tr/com/serkanozal/mysafe/impl/storage/ThreadLocalNavigatableAllocatedMemoryStorage.java import it.unimi.dsi.fastutil.longs.Long2LongAVLTreeMap; import it.unimi.dsi.fastutil.longs.Long2LongMap; import it.unimi.dsi.fastutil.longs.Long2LongSortedMap; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import sun.misc.Unsafe; import tr.com.serkanozal.mysafe.AllocatedMemoryIterator; import tr.com.serkanozal.mysafe.AllocatedMemoryStorage; /* * Copyright (c) 2017, Serkan OZAL, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tr.com.serkanozal.mysafe.impl.storage; public class ThreadLocalNavigatableAllocatedMemoryStorage extends AbstractThreadLocalAllocatedMemoryStorage { private static final boolean USE_INDEXED_MEMORY_ACCESS_CHECK = Boolean.getBoolean("mysafe.useIndexedMemoryAccessCheck"); private final IndexedMemoryAccessChecker indexedMemoryAccessChecker; public ThreadLocalNavigatableAllocatedMemoryStorage(Unsafe unsafe, ScheduledExecutorService scheduler) { super(unsafe, scheduler); if (USE_INDEXED_MEMORY_ACCESS_CHECK) { indexedMemoryAccessChecker = new IndexedMemoryAccessChecker(unsafe); } else { indexedMemoryAccessChecker = null; } } @Override
protected AllocatedMemoryStorage createInternalThreadLocalAllocatedMemoryStorage(Unsafe unsafe) {
serkan-ozal/mysafe
src/main/java/tr/com/serkanozal/mysafe/impl/storage/ThreadLocalNavigatableAllocatedMemoryStorage.java
// Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryIterator.java // public interface AllocatedMemoryIterator { // // /** // * Called for each allocated memory. // * // * @param address address of the allocated memory // * @param size size of the allocated memory // */ // void onAllocatedMemory(long address, long size); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryStorage.java // public interface AllocatedMemoryStorage { // // /** // * Represents any invalid value. // */ // long INVALID = -1; // // /** // * Checks if the given address is allocated or not. // * // * @param address the address to be checked if it is allocated or not // * @return <code>true</code> if if the given address is allocated, // * otherwise <code>false</code> // */ // boolean contains(long address); // // /** // * Checks if the specified memory region starting from given address // * as given size is in allocated memory area or not. // * // * @param address the start address of the specified memory region // * @param size the size of the specified memory region // * @return <code>true</code> if if the given specified memory region // * is in allocated memory area, otherwise <code>false</code> // */ // boolean contains(long address, long size); // // /** // * Gets the allocation size of the given address. // * // * @param address the address whose allocation size will be retrieved // * @return allocation size of the given address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long get(long address); // // /** // * Stores given address with its allocation size. // * // * @param address the address // * @param size the allocation size // */ // void put(long address, long size); // // /** // * Removes the given address. // * // * @param address the address to be removed // * @return allocation size of the removed address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long remove(long address); // // /** // * Iterates on the allocated memory addresses. // * // * @param iterator the {@link AllocatedMemoryIterator} instance to be notified // * for each allocated memory while iterating // */ // void iterate(AllocatedMemoryIterator iterator); // // /** // * Returns <tt>true</tt> if storage is empty, otherwise returns <tt>false</tt>. // * // * @return <tt>true</tt> if storage is empty, <tt>false</tt> otherwise // */ // boolean isEmpty(); // // }
import it.unimi.dsi.fastutil.longs.Long2LongAVLTreeMap; import it.unimi.dsi.fastutil.longs.Long2LongMap; import it.unimi.dsi.fastutil.longs.Long2LongSortedMap; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import sun.misc.Unsafe; import tr.com.serkanozal.mysafe.AllocatedMemoryIterator; import tr.com.serkanozal.mysafe.AllocatedMemoryStorage;
} @Override public void put(long address, long size) { acquire(); try { allocatedMemories.put(address, size); if (indexedMemoryAccessChecker != null) { indexedMemoryAccessChecker.markAllocated(address, size); } } finally { free(); } } @Override public long remove(long address) { acquire(); try { long size = allocatedMemories.remove(address); if (indexedMemoryAccessChecker != null && size != 0) { indexedMemoryAccessChecker.markFree(address, size); } return size != 0 ? size : INVALID; } finally { free(); } } @Override
// Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryIterator.java // public interface AllocatedMemoryIterator { // // /** // * Called for each allocated memory. // * // * @param address address of the allocated memory // * @param size size of the allocated memory // */ // void onAllocatedMemory(long address, long size); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryStorage.java // public interface AllocatedMemoryStorage { // // /** // * Represents any invalid value. // */ // long INVALID = -1; // // /** // * Checks if the given address is allocated or not. // * // * @param address the address to be checked if it is allocated or not // * @return <code>true</code> if if the given address is allocated, // * otherwise <code>false</code> // */ // boolean contains(long address); // // /** // * Checks if the specified memory region starting from given address // * as given size is in allocated memory area or not. // * // * @param address the start address of the specified memory region // * @param size the size of the specified memory region // * @return <code>true</code> if if the given specified memory region // * is in allocated memory area, otherwise <code>false</code> // */ // boolean contains(long address, long size); // // /** // * Gets the allocation size of the given address. // * // * @param address the address whose allocation size will be retrieved // * @return allocation size of the given address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long get(long address); // // /** // * Stores given address with its allocation size. // * // * @param address the address // * @param size the allocation size // */ // void put(long address, long size); // // /** // * Removes the given address. // * // * @param address the address to be removed // * @return allocation size of the removed address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long remove(long address); // // /** // * Iterates on the allocated memory addresses. // * // * @param iterator the {@link AllocatedMemoryIterator} instance to be notified // * for each allocated memory while iterating // */ // void iterate(AllocatedMemoryIterator iterator); // // /** // * Returns <tt>true</tt> if storage is empty, otherwise returns <tt>false</tt>. // * // * @return <tt>true</tt> if storage is empty, <tt>false</tt> otherwise // */ // boolean isEmpty(); // // } // Path: src/main/java/tr/com/serkanozal/mysafe/impl/storage/ThreadLocalNavigatableAllocatedMemoryStorage.java import it.unimi.dsi.fastutil.longs.Long2LongAVLTreeMap; import it.unimi.dsi.fastutil.longs.Long2LongMap; import it.unimi.dsi.fastutil.longs.Long2LongSortedMap; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import sun.misc.Unsafe; import tr.com.serkanozal.mysafe.AllocatedMemoryIterator; import tr.com.serkanozal.mysafe.AllocatedMemoryStorage; } @Override public void put(long address, long size) { acquire(); try { allocatedMemories.put(address, size); if (indexedMemoryAccessChecker != null) { indexedMemoryAccessChecker.markAllocated(address, size); } } finally { free(); } } @Override public long remove(long address) { acquire(); try { long size = allocatedMemories.remove(address); if (indexedMemoryAccessChecker != null && size != 0) { indexedMemoryAccessChecker.markFree(address, size); } return size != 0 ? size : INVALID; } finally { free(); } } @Override
public void iterate(final AllocatedMemoryIterator iterator) {
serkan-ozal/mysafe
src/main/java/tr/com/serkanozal/mysafe/impl/storage/ThreadLocalAwareAllocatedMemoryStorage.java
// Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryIterator.java // public interface AllocatedMemoryIterator { // // /** // * Called for each allocated memory. // * // * @param address address of the allocated memory // * @param size size of the allocated memory // */ // void onAllocatedMemory(long address, long size); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryStorage.java // public interface AllocatedMemoryStorage { // // /** // * Represents any invalid value. // */ // long INVALID = -1; // // /** // * Checks if the given address is allocated or not. // * // * @param address the address to be checked if it is allocated or not // * @return <code>true</code> if if the given address is allocated, // * otherwise <code>false</code> // */ // boolean contains(long address); // // /** // * Checks if the specified memory region starting from given address // * as given size is in allocated memory area or not. // * // * @param address the start address of the specified memory region // * @param size the size of the specified memory region // * @return <code>true</code> if if the given specified memory region // * is in allocated memory area, otherwise <code>false</code> // */ // boolean contains(long address, long size); // // /** // * Gets the allocation size of the given address. // * // * @param address the address whose allocation size will be retrieved // * @return allocation size of the given address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long get(long address); // // /** // * Stores given address with its allocation size. // * // * @param address the address // * @param size the allocation size // */ // void put(long address, long size); // // /** // * Removes the given address. // * // * @param address the address to be removed // * @return allocation size of the removed address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long remove(long address); // // /** // * Iterates on the allocated memory addresses. // * // * @param iterator the {@link AllocatedMemoryIterator} instance to be notified // * for each allocated memory while iterating // */ // void iterate(AllocatedMemoryIterator iterator); // // /** // * Returns <tt>true</tt> if storage is empty, otherwise returns <tt>false</tt>. // * // * @return <tt>true</tt> if storage is empty, <tt>false</tt> otherwise // */ // boolean isEmpty(); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/ThreadLocalMemoryUsageDecider.java // public interface ThreadLocalMemoryUsageDecider { // // /** // * Returns <tt>true</tt> if current thread uses (allocate/free/read/write) // * memory as thread-local, otherwise returns <tt>false</tt>. // * // * @param currentThread the current thread uses (allocate/free/read/write) memory // * @return <tt>true</tt> if current thread uses (allocate/free/read/write) // * memory as thread-local, otherwise <tt>false</tt> // */ // boolean isThreadLocal(Thread currentThread); // // }
import tr.com.serkanozal.mysafe.AllocatedMemoryIterator; import tr.com.serkanozal.mysafe.AllocatedMemoryStorage; import tr.com.serkanozal.mysafe.ThreadLocalMemoryUsageDecider;
/* * Copyright (c) 2017, Serkan OZAL, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tr.com.serkanozal.mysafe.impl.storage; public class ThreadLocalAwareAllocatedMemoryStorage implements AllocatedMemoryStorage { private final AllocatedMemoryStorage globalAllocatedMemoryStorage; private final AllocatedMemoryStorage threadLocalAllocatedMemoryStorage;
// Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryIterator.java // public interface AllocatedMemoryIterator { // // /** // * Called for each allocated memory. // * // * @param address address of the allocated memory // * @param size size of the allocated memory // */ // void onAllocatedMemory(long address, long size); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryStorage.java // public interface AllocatedMemoryStorage { // // /** // * Represents any invalid value. // */ // long INVALID = -1; // // /** // * Checks if the given address is allocated or not. // * // * @param address the address to be checked if it is allocated or not // * @return <code>true</code> if if the given address is allocated, // * otherwise <code>false</code> // */ // boolean contains(long address); // // /** // * Checks if the specified memory region starting from given address // * as given size is in allocated memory area or not. // * // * @param address the start address of the specified memory region // * @param size the size of the specified memory region // * @return <code>true</code> if if the given specified memory region // * is in allocated memory area, otherwise <code>false</code> // */ // boolean contains(long address, long size); // // /** // * Gets the allocation size of the given address. // * // * @param address the address whose allocation size will be retrieved // * @return allocation size of the given address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long get(long address); // // /** // * Stores given address with its allocation size. // * // * @param address the address // * @param size the allocation size // */ // void put(long address, long size); // // /** // * Removes the given address. // * // * @param address the address to be removed // * @return allocation size of the removed address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long remove(long address); // // /** // * Iterates on the allocated memory addresses. // * // * @param iterator the {@link AllocatedMemoryIterator} instance to be notified // * for each allocated memory while iterating // */ // void iterate(AllocatedMemoryIterator iterator); // // /** // * Returns <tt>true</tt> if storage is empty, otherwise returns <tt>false</tt>. // * // * @return <tt>true</tt> if storage is empty, <tt>false</tt> otherwise // */ // boolean isEmpty(); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/ThreadLocalMemoryUsageDecider.java // public interface ThreadLocalMemoryUsageDecider { // // /** // * Returns <tt>true</tt> if current thread uses (allocate/free/read/write) // * memory as thread-local, otherwise returns <tt>false</tt>. // * // * @param currentThread the current thread uses (allocate/free/read/write) memory // * @return <tt>true</tt> if current thread uses (allocate/free/read/write) // * memory as thread-local, otherwise <tt>false</tt> // */ // boolean isThreadLocal(Thread currentThread); // // } // Path: src/main/java/tr/com/serkanozal/mysafe/impl/storage/ThreadLocalAwareAllocatedMemoryStorage.java import tr.com.serkanozal.mysafe.AllocatedMemoryIterator; import tr.com.serkanozal.mysafe.AllocatedMemoryStorage; import tr.com.serkanozal.mysafe.ThreadLocalMemoryUsageDecider; /* * Copyright (c) 2017, Serkan OZAL, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tr.com.serkanozal.mysafe.impl.storage; public class ThreadLocalAwareAllocatedMemoryStorage implements AllocatedMemoryStorage { private final AllocatedMemoryStorage globalAllocatedMemoryStorage; private final AllocatedMemoryStorage threadLocalAllocatedMemoryStorage;
private final ThreadLocalMemoryUsageDecider threadLocalMemoryUsageDecider;
serkan-ozal/mysafe
src/main/java/tr/com/serkanozal/mysafe/impl/storage/ThreadLocalAwareAllocatedMemoryStorage.java
// Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryIterator.java // public interface AllocatedMemoryIterator { // // /** // * Called for each allocated memory. // * // * @param address address of the allocated memory // * @param size size of the allocated memory // */ // void onAllocatedMemory(long address, long size); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryStorage.java // public interface AllocatedMemoryStorage { // // /** // * Represents any invalid value. // */ // long INVALID = -1; // // /** // * Checks if the given address is allocated or not. // * // * @param address the address to be checked if it is allocated or not // * @return <code>true</code> if if the given address is allocated, // * otherwise <code>false</code> // */ // boolean contains(long address); // // /** // * Checks if the specified memory region starting from given address // * as given size is in allocated memory area or not. // * // * @param address the start address of the specified memory region // * @param size the size of the specified memory region // * @return <code>true</code> if if the given specified memory region // * is in allocated memory area, otherwise <code>false</code> // */ // boolean contains(long address, long size); // // /** // * Gets the allocation size of the given address. // * // * @param address the address whose allocation size will be retrieved // * @return allocation size of the given address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long get(long address); // // /** // * Stores given address with its allocation size. // * // * @param address the address // * @param size the allocation size // */ // void put(long address, long size); // // /** // * Removes the given address. // * // * @param address the address to be removed // * @return allocation size of the removed address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long remove(long address); // // /** // * Iterates on the allocated memory addresses. // * // * @param iterator the {@link AllocatedMemoryIterator} instance to be notified // * for each allocated memory while iterating // */ // void iterate(AllocatedMemoryIterator iterator); // // /** // * Returns <tt>true</tt> if storage is empty, otherwise returns <tt>false</tt>. // * // * @return <tt>true</tt> if storage is empty, <tt>false</tt> otherwise // */ // boolean isEmpty(); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/ThreadLocalMemoryUsageDecider.java // public interface ThreadLocalMemoryUsageDecider { // // /** // * Returns <tt>true</tt> if current thread uses (allocate/free/read/write) // * memory as thread-local, otherwise returns <tt>false</tt>. // * // * @param currentThread the current thread uses (allocate/free/read/write) memory // * @return <tt>true</tt> if current thread uses (allocate/free/read/write) // * memory as thread-local, otherwise <tt>false</tt> // */ // boolean isThreadLocal(Thread currentThread); // // }
import tr.com.serkanozal.mysafe.AllocatedMemoryIterator; import tr.com.serkanozal.mysafe.AllocatedMemoryStorage; import tr.com.serkanozal.mysafe.ThreadLocalMemoryUsageDecider;
return globalAllocatedMemoryStorage; } } @Override public boolean contains(long address) { return allocatedMemoryStorage().contains(address); } @Override public boolean contains(long address, long size) { return allocatedMemoryStorage().contains(address, size); } @Override public long get(long address) { return allocatedMemoryStorage().get(address); } @Override public void put(long address, long size) { allocatedMemoryStorage().put(address, size); } @Override public long remove(long address) { return allocatedMemoryStorage().remove(address); } @Override
// Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryIterator.java // public interface AllocatedMemoryIterator { // // /** // * Called for each allocated memory. // * // * @param address address of the allocated memory // * @param size size of the allocated memory // */ // void onAllocatedMemory(long address, long size); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryStorage.java // public interface AllocatedMemoryStorage { // // /** // * Represents any invalid value. // */ // long INVALID = -1; // // /** // * Checks if the given address is allocated or not. // * // * @param address the address to be checked if it is allocated or not // * @return <code>true</code> if if the given address is allocated, // * otherwise <code>false</code> // */ // boolean contains(long address); // // /** // * Checks if the specified memory region starting from given address // * as given size is in allocated memory area or not. // * // * @param address the start address of the specified memory region // * @param size the size of the specified memory region // * @return <code>true</code> if if the given specified memory region // * is in allocated memory area, otherwise <code>false</code> // */ // boolean contains(long address, long size); // // /** // * Gets the allocation size of the given address. // * // * @param address the address whose allocation size will be retrieved // * @return allocation size of the given address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long get(long address); // // /** // * Stores given address with its allocation size. // * // * @param address the address // * @param size the allocation size // */ // void put(long address, long size); // // /** // * Removes the given address. // * // * @param address the address to be removed // * @return allocation size of the removed address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long remove(long address); // // /** // * Iterates on the allocated memory addresses. // * // * @param iterator the {@link AllocatedMemoryIterator} instance to be notified // * for each allocated memory while iterating // */ // void iterate(AllocatedMemoryIterator iterator); // // /** // * Returns <tt>true</tt> if storage is empty, otherwise returns <tt>false</tt>. // * // * @return <tt>true</tt> if storage is empty, <tt>false</tt> otherwise // */ // boolean isEmpty(); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/ThreadLocalMemoryUsageDecider.java // public interface ThreadLocalMemoryUsageDecider { // // /** // * Returns <tt>true</tt> if current thread uses (allocate/free/read/write) // * memory as thread-local, otherwise returns <tt>false</tt>. // * // * @param currentThread the current thread uses (allocate/free/read/write) memory // * @return <tt>true</tt> if current thread uses (allocate/free/read/write) // * memory as thread-local, otherwise <tt>false</tt> // */ // boolean isThreadLocal(Thread currentThread); // // } // Path: src/main/java/tr/com/serkanozal/mysafe/impl/storage/ThreadLocalAwareAllocatedMemoryStorage.java import tr.com.serkanozal.mysafe.AllocatedMemoryIterator; import tr.com.serkanozal.mysafe.AllocatedMemoryStorage; import tr.com.serkanozal.mysafe.ThreadLocalMemoryUsageDecider; return globalAllocatedMemoryStorage; } } @Override public boolean contains(long address) { return allocatedMemoryStorage().contains(address); } @Override public boolean contains(long address, long size) { return allocatedMemoryStorage().contains(address, size); } @Override public long get(long address) { return allocatedMemoryStorage().get(address); } @Override public void put(long address, long size) { allocatedMemoryStorage().put(address, size); } @Override public long remove(long address) { return allocatedMemoryStorage().remove(address); } @Override
public void iterate(AllocatedMemoryIterator iterator) {
serkan-ozal/mysafe
src/main/java/tr/com/serkanozal/mysafe/impl/storage/AbstractThreadLocalAllocatedMemoryStorage.java
// Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryIterator.java // public interface AllocatedMemoryIterator { // // /** // * Called for each allocated memory. // * // * @param address address of the allocated memory // * @param size size of the allocated memory // */ // void onAllocatedMemory(long address, long size); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryStorage.java // public interface AllocatedMemoryStorage { // // /** // * Represents any invalid value. // */ // long INVALID = -1; // // /** // * Checks if the given address is allocated or not. // * // * @param address the address to be checked if it is allocated or not // * @return <code>true</code> if if the given address is allocated, // * otherwise <code>false</code> // */ // boolean contains(long address); // // /** // * Checks if the specified memory region starting from given address // * as given size is in allocated memory area or not. // * // * @param address the start address of the specified memory region // * @param size the size of the specified memory region // * @return <code>true</code> if if the given specified memory region // * is in allocated memory area, otherwise <code>false</code> // */ // boolean contains(long address, long size); // // /** // * Gets the allocation size of the given address. // * // * @param address the address whose allocation size will be retrieved // * @return allocation size of the given address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long get(long address); // // /** // * Stores given address with its allocation size. // * // * @param address the address // * @param size the allocation size // */ // void put(long address, long size); // // /** // * Removes the given address. // * // * @param address the address to be removed // * @return allocation size of the removed address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long remove(long address); // // /** // * Iterates on the allocated memory addresses. // * // * @param iterator the {@link AllocatedMemoryIterator} instance to be notified // * for each allocated memory while iterating // */ // void iterate(AllocatedMemoryIterator iterator); // // /** // * Returns <tt>true</tt> if storage is empty, otherwise returns <tt>false</tt>. // * // * @return <tt>true</tt> if storage is empty, <tt>false</tt> otherwise // */ // boolean isEmpty(); // // }
import java.lang.ref.SoftReference; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import sun.misc.Unsafe; import tr.com.serkanozal.mysafe.AllocatedMemoryIterator; import tr.com.serkanozal.mysafe.AllocatedMemoryStorage;
} abstract protected AllocatedMemoryStorage createInternalThreadLocalAllocatedMemoryStorage(Unsafe unsafe); @Override public boolean contains(long address) { return threadLocalAllocatedMemoryStorages.get().contains(address); } @Override public boolean contains(long address, long size) { return threadLocalAllocatedMemoryStorages.get().contains(address, size); } @Override public long get(long address) { return threadLocalAllocatedMemoryStorages.get().get(address); } @Override public void put(long address, long size) { threadLocalAllocatedMemoryStorages.get().put(address, size); } @Override public long remove(long address) { return threadLocalAllocatedMemoryStorages.get().remove(address); } @Override
// Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryIterator.java // public interface AllocatedMemoryIterator { // // /** // * Called for each allocated memory. // * // * @param address address of the allocated memory // * @param size size of the allocated memory // */ // void onAllocatedMemory(long address, long size); // // } // // Path: src/main/java/tr/com/serkanozal/mysafe/AllocatedMemoryStorage.java // public interface AllocatedMemoryStorage { // // /** // * Represents any invalid value. // */ // long INVALID = -1; // // /** // * Checks if the given address is allocated or not. // * // * @param address the address to be checked if it is allocated or not // * @return <code>true</code> if if the given address is allocated, // * otherwise <code>false</code> // */ // boolean contains(long address); // // /** // * Checks if the specified memory region starting from given address // * as given size is in allocated memory area or not. // * // * @param address the start address of the specified memory region // * @param size the size of the specified memory region // * @return <code>true</code> if if the given specified memory region // * is in allocated memory area, otherwise <code>false</code> // */ // boolean contains(long address, long size); // // /** // * Gets the allocation size of the given address. // * // * @param address the address whose allocation size will be retrieved // * @return allocation size of the given address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long get(long address); // // /** // * Stores given address with its allocation size. // * // * @param address the address // * @param size the allocation size // */ // void put(long address, long size); // // /** // * Removes the given address. // * // * @param address the address to be removed // * @return allocation size of the removed address if it is exist (allocated), // * otherwise {@link AllocatedMemoryStorage#INVALID} // */ // long remove(long address); // // /** // * Iterates on the allocated memory addresses. // * // * @param iterator the {@link AllocatedMemoryIterator} instance to be notified // * for each allocated memory while iterating // */ // void iterate(AllocatedMemoryIterator iterator); // // /** // * Returns <tt>true</tt> if storage is empty, otherwise returns <tt>false</tt>. // * // * @return <tt>true</tt> if storage is empty, <tt>false</tt> otherwise // */ // boolean isEmpty(); // // } // Path: src/main/java/tr/com/serkanozal/mysafe/impl/storage/AbstractThreadLocalAllocatedMemoryStorage.java import java.lang.ref.SoftReference; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import sun.misc.Unsafe; import tr.com.serkanozal.mysafe.AllocatedMemoryIterator; import tr.com.serkanozal.mysafe.AllocatedMemoryStorage; } abstract protected AllocatedMemoryStorage createInternalThreadLocalAllocatedMemoryStorage(Unsafe unsafe); @Override public boolean contains(long address) { return threadLocalAllocatedMemoryStorages.get().contains(address); } @Override public boolean contains(long address, long size) { return threadLocalAllocatedMemoryStorages.get().contains(address, size); } @Override public long get(long address) { return threadLocalAllocatedMemoryStorages.get().get(address); } @Override public void put(long address, long size) { threadLocalAllocatedMemoryStorages.get().put(address, size); } @Override public long remove(long address) { return threadLocalAllocatedMemoryStorages.get().remove(address); } @Override
public void iterate(AllocatedMemoryIterator iterator) {
serkan-ozal/mysafe
src/main/java/tr/com/serkanozal/mysafe/impl/allocpath/storage/ThreadLocalAwareAllocationPathStorage.java
// Path: src/main/java/tr/com/serkanozal/mysafe/ThreadLocalMemoryUsageDecider.java // public interface ThreadLocalMemoryUsageDecider { // // /** // * Returns <tt>true</tt> if current thread uses (allocate/free/read/write) // * memory as thread-local, otherwise returns <tt>false</tt>. // * // * @param currentThread the current thread uses (allocate/free/read/write) memory // * @return <tt>true</tt> if current thread uses (allocate/free/read/write) // * memory as thread-local, otherwise <tt>false</tt> // */ // boolean isThreadLocal(Thread currentThread); // // }
import java.util.concurrent.ScheduledExecutorService; import sun.misc.Unsafe; import tr.com.serkanozal.mysafe.ThreadLocalMemoryUsageDecider;
/* * Copyright (c) 2017, Serkan OZAL, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tr.com.serkanozal.mysafe.impl.allocpath.storage; public class ThreadLocalAwareAllocationPathStorage implements AllocationPathStorage { private final AllocationPathStorage globalAllocationPathStorage; private final AllocationPathStorage threadLocalAllocationPathStorage;
// Path: src/main/java/tr/com/serkanozal/mysafe/ThreadLocalMemoryUsageDecider.java // public interface ThreadLocalMemoryUsageDecider { // // /** // * Returns <tt>true</tt> if current thread uses (allocate/free/read/write) // * memory as thread-local, otherwise returns <tt>false</tt>. // * // * @param currentThread the current thread uses (allocate/free/read/write) memory // * @return <tt>true</tt> if current thread uses (allocate/free/read/write) // * memory as thread-local, otherwise <tt>false</tt> // */ // boolean isThreadLocal(Thread currentThread); // // } // Path: src/main/java/tr/com/serkanozal/mysafe/impl/allocpath/storage/ThreadLocalAwareAllocationPathStorage.java import java.util.concurrent.ScheduledExecutorService; import sun.misc.Unsafe; import tr.com.serkanozal.mysafe.ThreadLocalMemoryUsageDecider; /* * Copyright (c) 2017, Serkan OZAL, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tr.com.serkanozal.mysafe.impl.allocpath.storage; public class ThreadLocalAwareAllocationPathStorage implements AllocationPathStorage { private final AllocationPathStorage globalAllocationPathStorage; private final AllocationPathStorage threadLocalAllocationPathStorage;
private final ThreadLocalMemoryUsageDecider threadLocalMemoryUsageDecider;
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/framework/UGDBEventProcessor.java
// Path: app/src/main/java/ultimategdbot/database/GuildConfig.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGuildConfig.class) // @JsonDeserialize(as = ImmutableGuildConfig.class) // public interface GuildConfig { // // @Criteria.Id // @JsonProperty("_id") // long guildId(); // // Optional<String> prefix(); // // Optional<String> locale(); // } // // Path: app/src/main/java/ultimategdbot/service/DatabaseService.java // @RdiService // public final class DatabaseService { // // private final Backend backend; // // @RdiFactory // public DatabaseService(ConfigContainer configContainer) { // final var config = configContainer.get(MongoDBConfig.class); // final var mapper = new ObjectMapper() // .registerModule(new BsonModule()) // .registerModule(new Jdk8Module()) // .registerModule(new IdAnnotationModule()) // .addHandler(new UnknownPropertyHandler(true)); // @SuppressWarnings("UnstableApiUsage") // final var registry = JacksonCodecs.registryFromMapper(mapper); // final var client = MongoClients.create(config.connectionString()); // final var db = client.getDatabase(config.databaseName()).withCodecRegistry(registry); // this.backend = new MongoBackend(MongoSetup.of(db)); // } // // public GuildConfigDao guildConfigDao() { // return new GuildConfigDao(backend); // } // // public BlacklistDao blacklistDao() { // return new BlacklistDao(backend); // } // // public BotAdminDao botAdminDao() { // return new BotAdminDao(backend); // } // // public GdLinkedUserDao gdLinkedUserDao() { // return new GdLinkedUserDao(backend); // } // // public GdLeaderboardDao gdLeaderboardDao() { // return new GdLeaderboardDao(backend); // } // // public GdLeaderboardBanDao gdLeaderboardBanDao() { // return new GdLeaderboardBanDao(backend); // } // // public GdModDao gdModDao() { // return new GdModDao(backend); // } // // public GdAwardedLevelDao gdAwardedLevelDao() { // return new GdAwardedLevelDao(backend); // } // }
import botrino.interaction.InteractionEventProcessor; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.common.util.Snowflake; import discord4j.core.event.domain.interaction.InteractionCreateEvent; import reactor.core.publisher.Mono; import reactor.function.TupleUtils; import reactor.util.annotation.Nullable; import ultimategdbot.database.GuildConfig; import ultimategdbot.database.ImmutableGuildConfig; import ultimategdbot.service.DatabaseService; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors;
package ultimategdbot.framework; @RdiService public class UGDBEventProcessor implements InteractionEventProcessor {
// Path: app/src/main/java/ultimategdbot/database/GuildConfig.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGuildConfig.class) // @JsonDeserialize(as = ImmutableGuildConfig.class) // public interface GuildConfig { // // @Criteria.Id // @JsonProperty("_id") // long guildId(); // // Optional<String> prefix(); // // Optional<String> locale(); // } // // Path: app/src/main/java/ultimategdbot/service/DatabaseService.java // @RdiService // public final class DatabaseService { // // private final Backend backend; // // @RdiFactory // public DatabaseService(ConfigContainer configContainer) { // final var config = configContainer.get(MongoDBConfig.class); // final var mapper = new ObjectMapper() // .registerModule(new BsonModule()) // .registerModule(new Jdk8Module()) // .registerModule(new IdAnnotationModule()) // .addHandler(new UnknownPropertyHandler(true)); // @SuppressWarnings("UnstableApiUsage") // final var registry = JacksonCodecs.registryFromMapper(mapper); // final var client = MongoClients.create(config.connectionString()); // final var db = client.getDatabase(config.databaseName()).withCodecRegistry(registry); // this.backend = new MongoBackend(MongoSetup.of(db)); // } // // public GuildConfigDao guildConfigDao() { // return new GuildConfigDao(backend); // } // // public BlacklistDao blacklistDao() { // return new BlacklistDao(backend); // } // // public BotAdminDao botAdminDao() { // return new BotAdminDao(backend); // } // // public GdLinkedUserDao gdLinkedUserDao() { // return new GdLinkedUserDao(backend); // } // // public GdLeaderboardDao gdLeaderboardDao() { // return new GdLeaderboardDao(backend); // } // // public GdLeaderboardBanDao gdLeaderboardBanDao() { // return new GdLeaderboardBanDao(backend); // } // // public GdModDao gdModDao() { // return new GdModDao(backend); // } // // public GdAwardedLevelDao gdAwardedLevelDao() { // return new GdAwardedLevelDao(backend); // } // } // Path: app/src/main/java/ultimategdbot/framework/UGDBEventProcessor.java import botrino.interaction.InteractionEventProcessor; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.common.util.Snowflake; import discord4j.core.event.domain.interaction.InteractionCreateEvent; import reactor.core.publisher.Mono; import reactor.function.TupleUtils; import reactor.util.annotation.Nullable; import ultimategdbot.database.GuildConfig; import ultimategdbot.database.ImmutableGuildConfig; import ultimategdbot.service.DatabaseService; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; package ultimategdbot.framework; @RdiService public class UGDBEventProcessor implements InteractionEventProcessor {
private final DatabaseService db;
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/framework/UGDBEventProcessor.java
// Path: app/src/main/java/ultimategdbot/database/GuildConfig.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGuildConfig.class) // @JsonDeserialize(as = ImmutableGuildConfig.class) // public interface GuildConfig { // // @Criteria.Id // @JsonProperty("_id") // long guildId(); // // Optional<String> prefix(); // // Optional<String> locale(); // } // // Path: app/src/main/java/ultimategdbot/service/DatabaseService.java // @RdiService // public final class DatabaseService { // // private final Backend backend; // // @RdiFactory // public DatabaseService(ConfigContainer configContainer) { // final var config = configContainer.get(MongoDBConfig.class); // final var mapper = new ObjectMapper() // .registerModule(new BsonModule()) // .registerModule(new Jdk8Module()) // .registerModule(new IdAnnotationModule()) // .addHandler(new UnknownPropertyHandler(true)); // @SuppressWarnings("UnstableApiUsage") // final var registry = JacksonCodecs.registryFromMapper(mapper); // final var client = MongoClients.create(config.connectionString()); // final var db = client.getDatabase(config.databaseName()).withCodecRegistry(registry); // this.backend = new MongoBackend(MongoSetup.of(db)); // } // // public GuildConfigDao guildConfigDao() { // return new GuildConfigDao(backend); // } // // public BlacklistDao blacklistDao() { // return new BlacklistDao(backend); // } // // public BotAdminDao botAdminDao() { // return new BotAdminDao(backend); // } // // public GdLinkedUserDao gdLinkedUserDao() { // return new GdLinkedUserDao(backend); // } // // public GdLeaderboardDao gdLeaderboardDao() { // return new GdLeaderboardDao(backend); // } // // public GdLeaderboardBanDao gdLeaderboardBanDao() { // return new GdLeaderboardBanDao(backend); // } // // public GdModDao gdModDao() { // return new GdModDao(backend); // } // // public GdAwardedLevelDao gdAwardedLevelDao() { // return new GdAwardedLevelDao(backend); // } // }
import botrino.interaction.InteractionEventProcessor; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.common.util.Snowflake; import discord4j.core.event.domain.interaction.InteractionCreateEvent; import reactor.core.publisher.Mono; import reactor.function.TupleUtils; import reactor.util.annotation.Nullable; import ultimategdbot.database.GuildConfig; import ultimategdbot.database.ImmutableGuildConfig; import ultimategdbot.service.DatabaseService; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors;
package ultimategdbot.framework; @RdiService public class UGDBEventProcessor implements InteractionEventProcessor { private final DatabaseService db;
// Path: app/src/main/java/ultimategdbot/database/GuildConfig.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGuildConfig.class) // @JsonDeserialize(as = ImmutableGuildConfig.class) // public interface GuildConfig { // // @Criteria.Id // @JsonProperty("_id") // long guildId(); // // Optional<String> prefix(); // // Optional<String> locale(); // } // // Path: app/src/main/java/ultimategdbot/service/DatabaseService.java // @RdiService // public final class DatabaseService { // // private final Backend backend; // // @RdiFactory // public DatabaseService(ConfigContainer configContainer) { // final var config = configContainer.get(MongoDBConfig.class); // final var mapper = new ObjectMapper() // .registerModule(new BsonModule()) // .registerModule(new Jdk8Module()) // .registerModule(new IdAnnotationModule()) // .addHandler(new UnknownPropertyHandler(true)); // @SuppressWarnings("UnstableApiUsage") // final var registry = JacksonCodecs.registryFromMapper(mapper); // final var client = MongoClients.create(config.connectionString()); // final var db = client.getDatabase(config.databaseName()).withCodecRegistry(registry); // this.backend = new MongoBackend(MongoSetup.of(db)); // } // // public GuildConfigDao guildConfigDao() { // return new GuildConfigDao(backend); // } // // public BlacklistDao blacklistDao() { // return new BlacklistDao(backend); // } // // public BotAdminDao botAdminDao() { // return new BotAdminDao(backend); // } // // public GdLinkedUserDao gdLinkedUserDao() { // return new GdLinkedUserDao(backend); // } // // public GdLeaderboardDao gdLeaderboardDao() { // return new GdLeaderboardDao(backend); // } // // public GdLeaderboardBanDao gdLeaderboardBanDao() { // return new GdLeaderboardBanDao(backend); // } // // public GdModDao gdModDao() { // return new GdModDao(backend); // } // // public GdAwardedLevelDao gdAwardedLevelDao() { // return new GdAwardedLevelDao(backend); // } // } // Path: app/src/main/java/ultimategdbot/framework/UGDBEventProcessor.java import botrino.interaction.InteractionEventProcessor; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.common.util.Snowflake; import discord4j.core.event.domain.interaction.InteractionCreateEvent; import reactor.core.publisher.Mono; import reactor.function.TupleUtils; import reactor.util.annotation.Nullable; import ultimategdbot.database.GuildConfig; import ultimategdbot.database.ImmutableGuildConfig; import ultimategdbot.service.DatabaseService; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; package ultimategdbot.framework; @RdiService public class UGDBEventProcessor implements InteractionEventProcessor { private final DatabaseService db;
private final Map<Long, GuildConfig> guildConfigCache;
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/framework/UltimateGDBotExtension.java
// Path: app/src/main/java/ultimategdbot/service/CommandPermissionUpdater.java // @RdiService // public final class CommandPermissionUpdater { // // private final long applicationId; // private final List<UltimateGDBotConfig.CommandPermission> permissions; // private final ApplicationService appService; // private final Long guildId; // private final Mono<Void> onCommandsDeployed; // // @RdiFactory // public CommandPermissionUpdater(ConfigContainer configContainer, ApplicationInfo applicationInfo, // GatewayDiscordClient gateway, InteractionService interactionService) { // this.applicationId = applicationInfo.getId().asLong(); // this.permissions = configContainer.get(UltimateGDBotConfig.class).commandPermissions(); // this.appService = gateway.rest().getApplicationService(); // this.guildId = configContainer.get(InteractionConfig.class).applicationCommandsGuildId().orElse(null); // this.onCommandsDeployed = interactionService.onCommandsDeployed(); // } // // public Mono<Void> run() { // return onCommandsDeployed // .thenMany(guildId == null ? // appService.getGlobalApplicationCommands(applicationId) : // appService.getGuildApplicationCommands(applicationId, guildId)) // .collectMap(ApplicationCommandData::name, ApplicationCommandData::id) // .flatMapMany(commandIdsByName -> Flux.fromStream(permissions.stream() // .collect(groupingBy(UltimateGDBotConfig.CommandPermission::guildId)) // .entrySet() // .stream() // .map(entry -> updatePermissions(commandIdsByName, entry.getKey(), entry.getValue())))) // .flatMap(Function.identity()) // .then(); // } // // private Mono<Void> updatePermissions(Map<String, String> commandIdsByName, long guildId, // List<UltimateGDBotConfig.CommandPermission> permissions) { // final var payload = permissions.stream() // .collect(groupingBy(UltimateGDBotConfig.CommandPermission::name)) // .entrySet() // .stream() // .map(byCommandName -> (PartialGuildApplicationCommandPermissionsData) // PartialGuildApplicationCommandPermissionsData.builder() // .id(commandIdsByName.computeIfAbsent(byCommandName.getKey(), k -> { // throw new IllegalStateException( // "Command name '" + byCommandName.getKey() + "' not found"); // })) // .addAllPermissions(byCommandName.getValue().stream() // .map(perm -> ApplicationCommandPermissionsData.builder() // .id(perm.roleId()) // .type(1) // .permission(true) // .build()) // .collect(toUnmodifiableList())) // .build()) // .collect(toUnmodifiableList()); // return appService.bulkModifyApplicationCommandPermissions(applicationId, guildId, payload).then(); // } // } // // Path: app/src/main/java/ultimategdbot/service/ExternalServices.java // public final class ExternalServices { // // private static final Logger LOGGER = Loggers.getLogger(ExternalServices.class); // // private ExternalServices() { // throw new AssertionError(); // } // // public static Mono<ApplicationInfo> applicationInfo(GatewayDiscordClient gateway) { // return gateway.getApplicationInfo(); // } // // public static Mono<GDClient> gdClient(ConfigContainer configContainer) { // var config = configContainer.get(UltimateGDBotConfig.class).gd().client(); // return GDClient.create() // .withRouter(GDRouter.builder() // .setBaseUrl(config.host()) // .setRequestTimeout(config.requestTimeoutSeconds() > 0 // ? Duration.ofSeconds(config.requestTimeoutSeconds()) : null) // .setRequestLimiter(config.requestLimiter() // .map(l -> RequestLimiter.of(l.limit(), Duration.ofSeconds(l.intervalSeconds()))) // .orElseGet(RequestLimiter::none)) // .build()) // .withCache(GDCache.caffeine(c -> c.expireAfterAccess(Duration.ofSeconds(config.cacheTtlSeconds())))) // .login(config.username(), config.password()) // .doOnNext(client -> LOGGER.debug("Successfully logged into GD account " + config.username())); // } // // public static Mono<SpriteFactory> spriteFactory() { // return Mono.fromCallable(SpriteFactory::create) // .subscribeOn(Schedulers.boundedElastic()) // .onErrorMap(e -> new RuntimeException("An error occurred when loading the GD icons sprite factory", e)); // } // }
import botrino.api.config.ConfigContainer; import botrino.api.extension.BotrinoExtension; import com.github.alex1304.rdi.config.ServiceDescriptor; import discord4j.core.GatewayDiscordClient; import discord4j.core.object.entity.ApplicationInfo; import jdash.client.GDClient; import jdash.graphics.SpriteFactory; import reactor.core.publisher.Mono; import ultimategdbot.service.CommandPermissionUpdater; import ultimategdbot.service.ExternalServices; import java.util.Objects; import java.util.Set; import static com.github.alex1304.rdi.ServiceReference.ofType; import static com.github.alex1304.rdi.config.FactoryMethod.externalStaticFactory; import static com.github.alex1304.rdi.config.Injectable.ref;
package ultimategdbot.framework; public final class UltimateGDBotExtension implements BotrinoExtension { private CommandPermissionUpdater commandPermissionUpdater; @Override public void onClassDiscovered(Class<?> clazz) { } @Override public void onServiceCreated(Object serviceInstance) { if (serviceInstance instanceof CommandPermissionUpdater) { this.commandPermissionUpdater = (CommandPermissionUpdater) serviceInstance; } } @Override public Set<ServiceDescriptor> provideExtraServices() { return Set.of( ServiceDescriptor.builder(ofType(ApplicationInfo.class))
// Path: app/src/main/java/ultimategdbot/service/CommandPermissionUpdater.java // @RdiService // public final class CommandPermissionUpdater { // // private final long applicationId; // private final List<UltimateGDBotConfig.CommandPermission> permissions; // private final ApplicationService appService; // private final Long guildId; // private final Mono<Void> onCommandsDeployed; // // @RdiFactory // public CommandPermissionUpdater(ConfigContainer configContainer, ApplicationInfo applicationInfo, // GatewayDiscordClient gateway, InteractionService interactionService) { // this.applicationId = applicationInfo.getId().asLong(); // this.permissions = configContainer.get(UltimateGDBotConfig.class).commandPermissions(); // this.appService = gateway.rest().getApplicationService(); // this.guildId = configContainer.get(InteractionConfig.class).applicationCommandsGuildId().orElse(null); // this.onCommandsDeployed = interactionService.onCommandsDeployed(); // } // // public Mono<Void> run() { // return onCommandsDeployed // .thenMany(guildId == null ? // appService.getGlobalApplicationCommands(applicationId) : // appService.getGuildApplicationCommands(applicationId, guildId)) // .collectMap(ApplicationCommandData::name, ApplicationCommandData::id) // .flatMapMany(commandIdsByName -> Flux.fromStream(permissions.stream() // .collect(groupingBy(UltimateGDBotConfig.CommandPermission::guildId)) // .entrySet() // .stream() // .map(entry -> updatePermissions(commandIdsByName, entry.getKey(), entry.getValue())))) // .flatMap(Function.identity()) // .then(); // } // // private Mono<Void> updatePermissions(Map<String, String> commandIdsByName, long guildId, // List<UltimateGDBotConfig.CommandPermission> permissions) { // final var payload = permissions.stream() // .collect(groupingBy(UltimateGDBotConfig.CommandPermission::name)) // .entrySet() // .stream() // .map(byCommandName -> (PartialGuildApplicationCommandPermissionsData) // PartialGuildApplicationCommandPermissionsData.builder() // .id(commandIdsByName.computeIfAbsent(byCommandName.getKey(), k -> { // throw new IllegalStateException( // "Command name '" + byCommandName.getKey() + "' not found"); // })) // .addAllPermissions(byCommandName.getValue().stream() // .map(perm -> ApplicationCommandPermissionsData.builder() // .id(perm.roleId()) // .type(1) // .permission(true) // .build()) // .collect(toUnmodifiableList())) // .build()) // .collect(toUnmodifiableList()); // return appService.bulkModifyApplicationCommandPermissions(applicationId, guildId, payload).then(); // } // } // // Path: app/src/main/java/ultimategdbot/service/ExternalServices.java // public final class ExternalServices { // // private static final Logger LOGGER = Loggers.getLogger(ExternalServices.class); // // private ExternalServices() { // throw new AssertionError(); // } // // public static Mono<ApplicationInfo> applicationInfo(GatewayDiscordClient gateway) { // return gateway.getApplicationInfo(); // } // // public static Mono<GDClient> gdClient(ConfigContainer configContainer) { // var config = configContainer.get(UltimateGDBotConfig.class).gd().client(); // return GDClient.create() // .withRouter(GDRouter.builder() // .setBaseUrl(config.host()) // .setRequestTimeout(config.requestTimeoutSeconds() > 0 // ? Duration.ofSeconds(config.requestTimeoutSeconds()) : null) // .setRequestLimiter(config.requestLimiter() // .map(l -> RequestLimiter.of(l.limit(), Duration.ofSeconds(l.intervalSeconds()))) // .orElseGet(RequestLimiter::none)) // .build()) // .withCache(GDCache.caffeine(c -> c.expireAfterAccess(Duration.ofSeconds(config.cacheTtlSeconds())))) // .login(config.username(), config.password()) // .doOnNext(client -> LOGGER.debug("Successfully logged into GD account " + config.username())); // } // // public static Mono<SpriteFactory> spriteFactory() { // return Mono.fromCallable(SpriteFactory::create) // .subscribeOn(Schedulers.boundedElastic()) // .onErrorMap(e -> new RuntimeException("An error occurred when loading the GD icons sprite factory", e)); // } // } // Path: app/src/main/java/ultimategdbot/framework/UltimateGDBotExtension.java import botrino.api.config.ConfigContainer; import botrino.api.extension.BotrinoExtension; import com.github.alex1304.rdi.config.ServiceDescriptor; import discord4j.core.GatewayDiscordClient; import discord4j.core.object.entity.ApplicationInfo; import jdash.client.GDClient; import jdash.graphics.SpriteFactory; import reactor.core.publisher.Mono; import ultimategdbot.service.CommandPermissionUpdater; import ultimategdbot.service.ExternalServices; import java.util.Objects; import java.util.Set; import static com.github.alex1304.rdi.ServiceReference.ofType; import static com.github.alex1304.rdi.config.FactoryMethod.externalStaticFactory; import static com.github.alex1304.rdi.config.Injectable.ref; package ultimategdbot.framework; public final class UltimateGDBotExtension implements BotrinoExtension { private CommandPermissionUpdater commandPermissionUpdater; @Override public void onClassDiscovered(Class<?> clazz) { } @Override public void onServiceCreated(Object serviceInstance) { if (serviceInstance instanceof CommandPermissionUpdater) { this.commandPermissionUpdater = (CommandPermissionUpdater) serviceInstance; } } @Override public Set<ServiceDescriptor> provideExtraServices() { return Set.of( ServiceDescriptor.builder(ofType(ApplicationInfo.class))
.setFactoryMethod(externalStaticFactory(ExternalServices.class, "applicationInfo",
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/service/CommandPermissionUpdater.java
// Path: app/src/main/java/ultimategdbot/config/UltimateGDBotConfig.java // @ConfigEntry("ultimategdbot") // @Value.Immutable // @JsonDeserialize(as = ImmutableUltimateGDBotConfig.class) // public interface UltimateGDBotConfig { // // @JsonProperty("pagination_max_entries") // int paginationMaxEntries(); // // @JsonProperty("emoji_guild_ids") // Set<Long> emojiGuildIds(); // // @JsonProperty("command_cooldown") // Optional<Limiter> commandCooldown(); // // @JsonProperty("legacy_command_redirect_prefix") // Optional<String> legacyCommandRedirectPrefix(); // // @Value.Default // @JsonProperty("command_permissions") // default List<CommandPermission> commandPermissions() { // return List.of(); // } // // @Value.Default // @JsonProperty("bot_announcements_channel_ids") // default Set<Long> botAnnouncementsChannelIds() { // return Set.of(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableCommandPermission.class) // interface CommandPermission { // // String name(); // // @JsonProperty("guild_id") // long guildId(); // // @JsonProperty("role_id") // long roleId(); // } // // GD gd(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableGD.class) // interface GD { // // Client client(); // // Events events(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableClient.class) // interface Client { // // String username(); // // String password(); // // String host(); // // @JsonProperty("cache_ttl_seconds") // int cacheTtlSeconds(); // // @JsonProperty("request_timeout_seconds") // int requestTimeoutSeconds(); // // @JsonProperty("request_limiter") // Optional<Limiter> requestLimiter(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableEvents.class) // interface Events { // // @JsonProperty("event_loop_interval_seconds") // int eventLoopIntervalSeconds(); // // boolean crosspost(); // // @JsonProperty("rates_channel_ids") // Set<Long> ratesChannelIds(); // // @JsonProperty("demons_channel_ids") // Set<Long> demonsChannelIds(); // // @JsonProperty("timely_channel_id") // Optional<Long> timelyChannelId(); // // @JsonProperty("mods_channel_id") // Optional<Long> modsChannelId(); // // @JsonProperty("public_random_messages") // RandomMessages publicRandomMessages(); // // @JsonProperty("dm_random_messages") // RandomMessages dmRandomMessages(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableRandomMessages.class) // interface RandomMessages { // // List<String> rates(); // // List<String> unrates(); // // List<String> daily(); // // List<String> weekly(); // // List<String> mod(); // // @JsonProperty("elder_mod") // List<String> elderMod(); // // List<String> unmod(); // // @JsonProperty("elder_unmod") // List<String> elderUnmod(); // } // } // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableLimiter.class) // interface Limiter { // // @Value.Default // default int limit() { // return 10; // } // // @Value.Default // @JsonProperty("interval_seconds") // default int intervalSeconds() { // return 60; // } // } // }
import botrino.api.config.ConfigContainer; import botrino.interaction.InteractionService; import botrino.interaction.config.InteractionConfig; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.GatewayDiscordClient; import discord4j.core.object.entity.ApplicationInfo; import discord4j.discordjson.json.ApplicationCommandData; import discord4j.discordjson.json.ApplicationCommandPermissionsData; import discord4j.discordjson.json.PartialGuildApplicationCommandPermissionsData; import discord4j.rest.service.ApplicationService; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import ultimategdbot.config.UltimateGDBotConfig; import java.util.List; import java.util.Map; import java.util.function.Function; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toUnmodifiableList;
package ultimategdbot.service; @RdiService public final class CommandPermissionUpdater { private final long applicationId;
// Path: app/src/main/java/ultimategdbot/config/UltimateGDBotConfig.java // @ConfigEntry("ultimategdbot") // @Value.Immutable // @JsonDeserialize(as = ImmutableUltimateGDBotConfig.class) // public interface UltimateGDBotConfig { // // @JsonProperty("pagination_max_entries") // int paginationMaxEntries(); // // @JsonProperty("emoji_guild_ids") // Set<Long> emojiGuildIds(); // // @JsonProperty("command_cooldown") // Optional<Limiter> commandCooldown(); // // @JsonProperty("legacy_command_redirect_prefix") // Optional<String> legacyCommandRedirectPrefix(); // // @Value.Default // @JsonProperty("command_permissions") // default List<CommandPermission> commandPermissions() { // return List.of(); // } // // @Value.Default // @JsonProperty("bot_announcements_channel_ids") // default Set<Long> botAnnouncementsChannelIds() { // return Set.of(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableCommandPermission.class) // interface CommandPermission { // // String name(); // // @JsonProperty("guild_id") // long guildId(); // // @JsonProperty("role_id") // long roleId(); // } // // GD gd(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableGD.class) // interface GD { // // Client client(); // // Events events(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableClient.class) // interface Client { // // String username(); // // String password(); // // String host(); // // @JsonProperty("cache_ttl_seconds") // int cacheTtlSeconds(); // // @JsonProperty("request_timeout_seconds") // int requestTimeoutSeconds(); // // @JsonProperty("request_limiter") // Optional<Limiter> requestLimiter(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableEvents.class) // interface Events { // // @JsonProperty("event_loop_interval_seconds") // int eventLoopIntervalSeconds(); // // boolean crosspost(); // // @JsonProperty("rates_channel_ids") // Set<Long> ratesChannelIds(); // // @JsonProperty("demons_channel_ids") // Set<Long> demonsChannelIds(); // // @JsonProperty("timely_channel_id") // Optional<Long> timelyChannelId(); // // @JsonProperty("mods_channel_id") // Optional<Long> modsChannelId(); // // @JsonProperty("public_random_messages") // RandomMessages publicRandomMessages(); // // @JsonProperty("dm_random_messages") // RandomMessages dmRandomMessages(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableRandomMessages.class) // interface RandomMessages { // // List<String> rates(); // // List<String> unrates(); // // List<String> daily(); // // List<String> weekly(); // // List<String> mod(); // // @JsonProperty("elder_mod") // List<String> elderMod(); // // List<String> unmod(); // // @JsonProperty("elder_unmod") // List<String> elderUnmod(); // } // } // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableLimiter.class) // interface Limiter { // // @Value.Default // default int limit() { // return 10; // } // // @Value.Default // @JsonProperty("interval_seconds") // default int intervalSeconds() { // return 60; // } // } // } // Path: app/src/main/java/ultimategdbot/service/CommandPermissionUpdater.java import botrino.api.config.ConfigContainer; import botrino.interaction.InteractionService; import botrino.interaction.config.InteractionConfig; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.GatewayDiscordClient; import discord4j.core.object.entity.ApplicationInfo; import discord4j.discordjson.json.ApplicationCommandData; import discord4j.discordjson.json.ApplicationCommandPermissionsData; import discord4j.discordjson.json.PartialGuildApplicationCommandPermissionsData; import discord4j.rest.service.ApplicationService; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import ultimategdbot.config.UltimateGDBotConfig; import java.util.List; import java.util.Map; import java.util.function.Function; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toUnmodifiableList; package ultimategdbot.service; @RdiService public final class CommandPermissionUpdater { private final long applicationId;
private final List<UltimateGDBotConfig.CommandPermission> permissions;
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/service/EmojiService.java
// Path: app/src/main/java/ultimategdbot/config/UltimateGDBotConfig.java // @ConfigEntry("ultimategdbot") // @Value.Immutable // @JsonDeserialize(as = ImmutableUltimateGDBotConfig.class) // public interface UltimateGDBotConfig { // // @JsonProperty("pagination_max_entries") // int paginationMaxEntries(); // // @JsonProperty("emoji_guild_ids") // Set<Long> emojiGuildIds(); // // @JsonProperty("command_cooldown") // Optional<Limiter> commandCooldown(); // // @JsonProperty("legacy_command_redirect_prefix") // Optional<String> legacyCommandRedirectPrefix(); // // @Value.Default // @JsonProperty("command_permissions") // default List<CommandPermission> commandPermissions() { // return List.of(); // } // // @Value.Default // @JsonProperty("bot_announcements_channel_ids") // default Set<Long> botAnnouncementsChannelIds() { // return Set.of(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableCommandPermission.class) // interface CommandPermission { // // String name(); // // @JsonProperty("guild_id") // long guildId(); // // @JsonProperty("role_id") // long roleId(); // } // // GD gd(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableGD.class) // interface GD { // // Client client(); // // Events events(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableClient.class) // interface Client { // // String username(); // // String password(); // // String host(); // // @JsonProperty("cache_ttl_seconds") // int cacheTtlSeconds(); // // @JsonProperty("request_timeout_seconds") // int requestTimeoutSeconds(); // // @JsonProperty("request_limiter") // Optional<Limiter> requestLimiter(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableEvents.class) // interface Events { // // @JsonProperty("event_loop_interval_seconds") // int eventLoopIntervalSeconds(); // // boolean crosspost(); // // @JsonProperty("rates_channel_ids") // Set<Long> ratesChannelIds(); // // @JsonProperty("demons_channel_ids") // Set<Long> demonsChannelIds(); // // @JsonProperty("timely_channel_id") // Optional<Long> timelyChannelId(); // // @JsonProperty("mods_channel_id") // Optional<Long> modsChannelId(); // // @JsonProperty("public_random_messages") // RandomMessages publicRandomMessages(); // // @JsonProperty("dm_random_messages") // RandomMessages dmRandomMessages(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableRandomMessages.class) // interface RandomMessages { // // List<String> rates(); // // List<String> unrates(); // // List<String> daily(); // // List<String> weekly(); // // List<String> mod(); // // @JsonProperty("elder_mod") // List<String> elderMod(); // // List<String> unmod(); // // @JsonProperty("elder_unmod") // List<String> elderUnmod(); // } // } // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableLimiter.class) // interface Limiter { // // @Value.Default // default int limit() { // return 10; // } // // @Value.Default // @JsonProperty("interval_seconds") // default int intervalSeconds() { // return 60; // } // } // }
import botrino.api.config.ConfigContainer; import botrino.api.util.EmojiManager; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.common.util.Snowflake; import discord4j.core.GatewayDiscordClient; import reactor.core.publisher.Mono; import ultimategdbot.config.UltimateGDBotConfig; import java.util.NoSuchElementException; import java.util.stream.Collectors;
package ultimategdbot.service; @RdiService public final class EmojiService { private final EmojiManager emojiManager; private EmojiService(EmojiManager emojiManager) { this.emojiManager = emojiManager; } @RdiFactory public static Mono<EmojiService> create(ConfigContainer configContainer, GatewayDiscordClient gateway) { var emojiManager = EmojiManager.create(
// Path: app/src/main/java/ultimategdbot/config/UltimateGDBotConfig.java // @ConfigEntry("ultimategdbot") // @Value.Immutable // @JsonDeserialize(as = ImmutableUltimateGDBotConfig.class) // public interface UltimateGDBotConfig { // // @JsonProperty("pagination_max_entries") // int paginationMaxEntries(); // // @JsonProperty("emoji_guild_ids") // Set<Long> emojiGuildIds(); // // @JsonProperty("command_cooldown") // Optional<Limiter> commandCooldown(); // // @JsonProperty("legacy_command_redirect_prefix") // Optional<String> legacyCommandRedirectPrefix(); // // @Value.Default // @JsonProperty("command_permissions") // default List<CommandPermission> commandPermissions() { // return List.of(); // } // // @Value.Default // @JsonProperty("bot_announcements_channel_ids") // default Set<Long> botAnnouncementsChannelIds() { // return Set.of(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableCommandPermission.class) // interface CommandPermission { // // String name(); // // @JsonProperty("guild_id") // long guildId(); // // @JsonProperty("role_id") // long roleId(); // } // // GD gd(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableGD.class) // interface GD { // // Client client(); // // Events events(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableClient.class) // interface Client { // // String username(); // // String password(); // // String host(); // // @JsonProperty("cache_ttl_seconds") // int cacheTtlSeconds(); // // @JsonProperty("request_timeout_seconds") // int requestTimeoutSeconds(); // // @JsonProperty("request_limiter") // Optional<Limiter> requestLimiter(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableEvents.class) // interface Events { // // @JsonProperty("event_loop_interval_seconds") // int eventLoopIntervalSeconds(); // // boolean crosspost(); // // @JsonProperty("rates_channel_ids") // Set<Long> ratesChannelIds(); // // @JsonProperty("demons_channel_ids") // Set<Long> demonsChannelIds(); // // @JsonProperty("timely_channel_id") // Optional<Long> timelyChannelId(); // // @JsonProperty("mods_channel_id") // Optional<Long> modsChannelId(); // // @JsonProperty("public_random_messages") // RandomMessages publicRandomMessages(); // // @JsonProperty("dm_random_messages") // RandomMessages dmRandomMessages(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableRandomMessages.class) // interface RandomMessages { // // List<String> rates(); // // List<String> unrates(); // // List<String> daily(); // // List<String> weekly(); // // List<String> mod(); // // @JsonProperty("elder_mod") // List<String> elderMod(); // // List<String> unmod(); // // @JsonProperty("elder_unmod") // List<String> elderUnmod(); // } // } // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableLimiter.class) // interface Limiter { // // @Value.Default // default int limit() { // return 10; // } // // @Value.Default // @JsonProperty("interval_seconds") // default int intervalSeconds() { // return 60; // } // } // } // Path: app/src/main/java/ultimategdbot/service/EmojiService.java import botrino.api.config.ConfigContainer; import botrino.api.util.EmojiManager; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.common.util.Snowflake; import discord4j.core.GatewayDiscordClient; import reactor.core.publisher.Mono; import ultimategdbot.config.UltimateGDBotConfig; import java.util.NoSuchElementException; import java.util.stream.Collectors; package ultimategdbot.service; @RdiService public final class EmojiService { private final EmojiManager emojiManager; private EmojiService(EmojiManager emojiManager) { this.emojiManager = emojiManager; } @RdiFactory public static Mono<EmojiService> create(ConfigContainer configContainer, GatewayDiscordClient gateway) { var emojiManager = EmojiManager.create(
configContainer.get(UltimateGDBotConfig.class).emojiGuildIds()
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/service/PrivilegeFactory.java
// Path: app/src/main/java/ultimategdbot/database/GdMod.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGdMod.class) // @JsonDeserialize(as = ImmutableGdMod.class) // public interface GdMod { // // @Criteria.Id // @JsonProperty("_id") // long accountId(); // // String name(); // // int elder(); // // default boolean isElder() { // return elder() > 0; // } // } // // Path: app/src/main/java/ultimategdbot/exception/BotAdminPrivilegeException.java // public final class BotAdminPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/BotOwnerPrivilegeException.java // public final class BotOwnerPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/ElderModPrivilegeException.java // public final class ElderModPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/GuildAdminPrivilegeException.java // public final class GuildAdminPrivilegeException extends PrivilegeException { // }
import botrino.interaction.privilege.Privilege; import botrino.interaction.privilege.Privileges; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.object.entity.ApplicationInfo; import discord4j.rest.util.Permission; import reactor.core.publisher.Mono; import ultimategdbot.database.GdMod; import ultimategdbot.exception.BotAdminPrivilegeException; import ultimategdbot.exception.BotOwnerPrivilegeException; import ultimategdbot.exception.ElderModPrivilegeException; import ultimategdbot.exception.GuildAdminPrivilegeException;
package ultimategdbot.service; @RdiService public final class PrivilegeFactory { private final long ownerId; private final DatabaseService db; @RdiFactory public PrivilegeFactory(ApplicationInfo applicationInfo, DatabaseService db) { this.ownerId = applicationInfo.getOwnerId().asLong(); this.db = db; } public Privilege botOwner() { return ctx -> ctx.event().getInteraction().getUser().getId().asLong() == ownerId ? Mono.empty()
// Path: app/src/main/java/ultimategdbot/database/GdMod.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGdMod.class) // @JsonDeserialize(as = ImmutableGdMod.class) // public interface GdMod { // // @Criteria.Id // @JsonProperty("_id") // long accountId(); // // String name(); // // int elder(); // // default boolean isElder() { // return elder() > 0; // } // } // // Path: app/src/main/java/ultimategdbot/exception/BotAdminPrivilegeException.java // public final class BotAdminPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/BotOwnerPrivilegeException.java // public final class BotOwnerPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/ElderModPrivilegeException.java // public final class ElderModPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/GuildAdminPrivilegeException.java // public final class GuildAdminPrivilegeException extends PrivilegeException { // } // Path: app/src/main/java/ultimategdbot/service/PrivilegeFactory.java import botrino.interaction.privilege.Privilege; import botrino.interaction.privilege.Privileges; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.object.entity.ApplicationInfo; import discord4j.rest.util.Permission; import reactor.core.publisher.Mono; import ultimategdbot.database.GdMod; import ultimategdbot.exception.BotAdminPrivilegeException; import ultimategdbot.exception.BotOwnerPrivilegeException; import ultimategdbot.exception.ElderModPrivilegeException; import ultimategdbot.exception.GuildAdminPrivilegeException; package ultimategdbot.service; @RdiService public final class PrivilegeFactory { private final long ownerId; private final DatabaseService db; @RdiFactory public PrivilegeFactory(ApplicationInfo applicationInfo, DatabaseService db) { this.ownerId = applicationInfo.getOwnerId().asLong(); this.db = db; } public Privilege botOwner() { return ctx -> ctx.event().getInteraction().getUser().getId().asLong() == ownerId ? Mono.empty()
: Mono.error(new BotOwnerPrivilegeException());
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/service/PrivilegeFactory.java
// Path: app/src/main/java/ultimategdbot/database/GdMod.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGdMod.class) // @JsonDeserialize(as = ImmutableGdMod.class) // public interface GdMod { // // @Criteria.Id // @JsonProperty("_id") // long accountId(); // // String name(); // // int elder(); // // default boolean isElder() { // return elder() > 0; // } // } // // Path: app/src/main/java/ultimategdbot/exception/BotAdminPrivilegeException.java // public final class BotAdminPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/BotOwnerPrivilegeException.java // public final class BotOwnerPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/ElderModPrivilegeException.java // public final class ElderModPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/GuildAdminPrivilegeException.java // public final class GuildAdminPrivilegeException extends PrivilegeException { // }
import botrino.interaction.privilege.Privilege; import botrino.interaction.privilege.Privileges; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.object.entity.ApplicationInfo; import discord4j.rest.util.Permission; import reactor.core.publisher.Mono; import ultimategdbot.database.GdMod; import ultimategdbot.exception.BotAdminPrivilegeException; import ultimategdbot.exception.BotOwnerPrivilegeException; import ultimategdbot.exception.ElderModPrivilegeException; import ultimategdbot.exception.GuildAdminPrivilegeException;
package ultimategdbot.service; @RdiService public final class PrivilegeFactory { private final long ownerId; private final DatabaseService db; @RdiFactory public PrivilegeFactory(ApplicationInfo applicationInfo, DatabaseService db) { this.ownerId = applicationInfo.getOwnerId().asLong(); this.db = db; } public Privilege botOwner() { return ctx -> ctx.event().getInteraction().getUser().getId().asLong() == ownerId ? Mono.empty() : Mono.error(new BotOwnerPrivilegeException()); } public Privilege botAdmin() { return botOwner().or(ctx -> db.botAdminDao() .exists(ctx.event().getInteraction().getUser().getId().asLong()) .filter(Boolean::booleanValue)
// Path: app/src/main/java/ultimategdbot/database/GdMod.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGdMod.class) // @JsonDeserialize(as = ImmutableGdMod.class) // public interface GdMod { // // @Criteria.Id // @JsonProperty("_id") // long accountId(); // // String name(); // // int elder(); // // default boolean isElder() { // return elder() > 0; // } // } // // Path: app/src/main/java/ultimategdbot/exception/BotAdminPrivilegeException.java // public final class BotAdminPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/BotOwnerPrivilegeException.java // public final class BotOwnerPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/ElderModPrivilegeException.java // public final class ElderModPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/GuildAdminPrivilegeException.java // public final class GuildAdminPrivilegeException extends PrivilegeException { // } // Path: app/src/main/java/ultimategdbot/service/PrivilegeFactory.java import botrino.interaction.privilege.Privilege; import botrino.interaction.privilege.Privileges; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.object.entity.ApplicationInfo; import discord4j.rest.util.Permission; import reactor.core.publisher.Mono; import ultimategdbot.database.GdMod; import ultimategdbot.exception.BotAdminPrivilegeException; import ultimategdbot.exception.BotOwnerPrivilegeException; import ultimategdbot.exception.ElderModPrivilegeException; import ultimategdbot.exception.GuildAdminPrivilegeException; package ultimategdbot.service; @RdiService public final class PrivilegeFactory { private final long ownerId; private final DatabaseService db; @RdiFactory public PrivilegeFactory(ApplicationInfo applicationInfo, DatabaseService db) { this.ownerId = applicationInfo.getOwnerId().asLong(); this.db = db; } public Privilege botOwner() { return ctx -> ctx.event().getInteraction().getUser().getId().asLong() == ownerId ? Mono.empty() : Mono.error(new BotOwnerPrivilegeException()); } public Privilege botAdmin() { return botOwner().or(ctx -> db.botAdminDao() .exists(ctx.event().getInteraction().getUser().getId().asLong()) .filter(Boolean::booleanValue)
.switchIfEmpty(Mono.error(BotAdminPrivilegeException::new))
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/service/PrivilegeFactory.java
// Path: app/src/main/java/ultimategdbot/database/GdMod.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGdMod.class) // @JsonDeserialize(as = ImmutableGdMod.class) // public interface GdMod { // // @Criteria.Id // @JsonProperty("_id") // long accountId(); // // String name(); // // int elder(); // // default boolean isElder() { // return elder() > 0; // } // } // // Path: app/src/main/java/ultimategdbot/exception/BotAdminPrivilegeException.java // public final class BotAdminPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/BotOwnerPrivilegeException.java // public final class BotOwnerPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/ElderModPrivilegeException.java // public final class ElderModPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/GuildAdminPrivilegeException.java // public final class GuildAdminPrivilegeException extends PrivilegeException { // }
import botrino.interaction.privilege.Privilege; import botrino.interaction.privilege.Privileges; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.object.entity.ApplicationInfo; import discord4j.rest.util.Permission; import reactor.core.publisher.Mono; import ultimategdbot.database.GdMod; import ultimategdbot.exception.BotAdminPrivilegeException; import ultimategdbot.exception.BotOwnerPrivilegeException; import ultimategdbot.exception.ElderModPrivilegeException; import ultimategdbot.exception.GuildAdminPrivilegeException;
package ultimategdbot.service; @RdiService public final class PrivilegeFactory { private final long ownerId; private final DatabaseService db; @RdiFactory public PrivilegeFactory(ApplicationInfo applicationInfo, DatabaseService db) { this.ownerId = applicationInfo.getOwnerId().asLong(); this.db = db; } public Privilege botOwner() { return ctx -> ctx.event().getInteraction().getUser().getId().asLong() == ownerId ? Mono.empty() : Mono.error(new BotOwnerPrivilegeException()); } public Privilege botAdmin() { return botOwner().or(ctx -> db.botAdminDao() .exists(ctx.event().getInteraction().getUser().getId().asLong()) .filter(Boolean::booleanValue) .switchIfEmpty(Mono.error(BotAdminPrivilegeException::new)) .then(), (a, b) -> b); } public Privilege guildAdmin() {
// Path: app/src/main/java/ultimategdbot/database/GdMod.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGdMod.class) // @JsonDeserialize(as = ImmutableGdMod.class) // public interface GdMod { // // @Criteria.Id // @JsonProperty("_id") // long accountId(); // // String name(); // // int elder(); // // default boolean isElder() { // return elder() > 0; // } // } // // Path: app/src/main/java/ultimategdbot/exception/BotAdminPrivilegeException.java // public final class BotAdminPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/BotOwnerPrivilegeException.java // public final class BotOwnerPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/ElderModPrivilegeException.java // public final class ElderModPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/GuildAdminPrivilegeException.java // public final class GuildAdminPrivilegeException extends PrivilegeException { // } // Path: app/src/main/java/ultimategdbot/service/PrivilegeFactory.java import botrino.interaction.privilege.Privilege; import botrino.interaction.privilege.Privileges; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.object.entity.ApplicationInfo; import discord4j.rest.util.Permission; import reactor.core.publisher.Mono; import ultimategdbot.database.GdMod; import ultimategdbot.exception.BotAdminPrivilegeException; import ultimategdbot.exception.BotOwnerPrivilegeException; import ultimategdbot.exception.ElderModPrivilegeException; import ultimategdbot.exception.GuildAdminPrivilegeException; package ultimategdbot.service; @RdiService public final class PrivilegeFactory { private final long ownerId; private final DatabaseService db; @RdiFactory public PrivilegeFactory(ApplicationInfo applicationInfo, DatabaseService db) { this.ownerId = applicationInfo.getOwnerId().asLong(); this.db = db; } public Privilege botOwner() { return ctx -> ctx.event().getInteraction().getUser().getId().asLong() == ownerId ? Mono.empty() : Mono.error(new BotOwnerPrivilegeException()); } public Privilege botAdmin() { return botOwner().or(ctx -> db.botAdminDao() .exists(ctx.event().getInteraction().getUser().getId().asLong()) .filter(Boolean::booleanValue) .switchIfEmpty(Mono.error(BotAdminPrivilegeException::new)) .then(), (a, b) -> b); } public Privilege guildAdmin() {
return botAdmin().or(Privileges.checkPermissions(ctx -> new GuildAdminPrivilegeException(),
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/service/PrivilegeFactory.java
// Path: app/src/main/java/ultimategdbot/database/GdMod.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGdMod.class) // @JsonDeserialize(as = ImmutableGdMod.class) // public interface GdMod { // // @Criteria.Id // @JsonProperty("_id") // long accountId(); // // String name(); // // int elder(); // // default boolean isElder() { // return elder() > 0; // } // } // // Path: app/src/main/java/ultimategdbot/exception/BotAdminPrivilegeException.java // public final class BotAdminPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/BotOwnerPrivilegeException.java // public final class BotOwnerPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/ElderModPrivilegeException.java // public final class ElderModPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/GuildAdminPrivilegeException.java // public final class GuildAdminPrivilegeException extends PrivilegeException { // }
import botrino.interaction.privilege.Privilege; import botrino.interaction.privilege.Privileges; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.object.entity.ApplicationInfo; import discord4j.rest.util.Permission; import reactor.core.publisher.Mono; import ultimategdbot.database.GdMod; import ultimategdbot.exception.BotAdminPrivilegeException; import ultimategdbot.exception.BotOwnerPrivilegeException; import ultimategdbot.exception.ElderModPrivilegeException; import ultimategdbot.exception.GuildAdminPrivilegeException;
package ultimategdbot.service; @RdiService public final class PrivilegeFactory { private final long ownerId; private final DatabaseService db; @RdiFactory public PrivilegeFactory(ApplicationInfo applicationInfo, DatabaseService db) { this.ownerId = applicationInfo.getOwnerId().asLong(); this.db = db; } public Privilege botOwner() { return ctx -> ctx.event().getInteraction().getUser().getId().asLong() == ownerId ? Mono.empty() : Mono.error(new BotOwnerPrivilegeException()); } public Privilege botAdmin() { return botOwner().or(ctx -> db.botAdminDao() .exists(ctx.event().getInteraction().getUser().getId().asLong()) .filter(Boolean::booleanValue) .switchIfEmpty(Mono.error(BotAdminPrivilegeException::new)) .then(), (a, b) -> b); } public Privilege guildAdmin() { return botAdmin().or(Privileges.checkPermissions(ctx -> new GuildAdminPrivilegeException(), perms -> perms.contains(Permission.ADMINISTRATOR)), (a, b) -> b); } public Privilege elderMod() { return botOwner().or(ctx -> db.gdLinkedUserDao() .getActiveLink(ctx.event().getInteraction().getUser().getId().asLong())
// Path: app/src/main/java/ultimategdbot/database/GdMod.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGdMod.class) // @JsonDeserialize(as = ImmutableGdMod.class) // public interface GdMod { // // @Criteria.Id // @JsonProperty("_id") // long accountId(); // // String name(); // // int elder(); // // default boolean isElder() { // return elder() > 0; // } // } // // Path: app/src/main/java/ultimategdbot/exception/BotAdminPrivilegeException.java // public final class BotAdminPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/BotOwnerPrivilegeException.java // public final class BotOwnerPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/ElderModPrivilegeException.java // public final class ElderModPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/GuildAdminPrivilegeException.java // public final class GuildAdminPrivilegeException extends PrivilegeException { // } // Path: app/src/main/java/ultimategdbot/service/PrivilegeFactory.java import botrino.interaction.privilege.Privilege; import botrino.interaction.privilege.Privileges; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.object.entity.ApplicationInfo; import discord4j.rest.util.Permission; import reactor.core.publisher.Mono; import ultimategdbot.database.GdMod; import ultimategdbot.exception.BotAdminPrivilegeException; import ultimategdbot.exception.BotOwnerPrivilegeException; import ultimategdbot.exception.ElderModPrivilegeException; import ultimategdbot.exception.GuildAdminPrivilegeException; package ultimategdbot.service; @RdiService public final class PrivilegeFactory { private final long ownerId; private final DatabaseService db; @RdiFactory public PrivilegeFactory(ApplicationInfo applicationInfo, DatabaseService db) { this.ownerId = applicationInfo.getOwnerId().asLong(); this.db = db; } public Privilege botOwner() { return ctx -> ctx.event().getInteraction().getUser().getId().asLong() == ownerId ? Mono.empty() : Mono.error(new BotOwnerPrivilegeException()); } public Privilege botAdmin() { return botOwner().or(ctx -> db.botAdminDao() .exists(ctx.event().getInteraction().getUser().getId().asLong()) .filter(Boolean::booleanValue) .switchIfEmpty(Mono.error(BotAdminPrivilegeException::new)) .then(), (a, b) -> b); } public Privilege guildAdmin() { return botAdmin().or(Privileges.checkPermissions(ctx -> new GuildAdminPrivilegeException(), perms -> perms.contains(Permission.ADMINISTRATOR)), (a, b) -> b); } public Privilege elderMod() { return botOwner().or(ctx -> db.gdLinkedUserDao() .getActiveLink(ctx.event().getInteraction().getUser().getId().asLong())
.flatMap(linkedUser -> db.gdModDao().get(linkedUser.gdUserId()).map(GdMod::isElder))
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/service/PrivilegeFactory.java
// Path: app/src/main/java/ultimategdbot/database/GdMod.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGdMod.class) // @JsonDeserialize(as = ImmutableGdMod.class) // public interface GdMod { // // @Criteria.Id // @JsonProperty("_id") // long accountId(); // // String name(); // // int elder(); // // default boolean isElder() { // return elder() > 0; // } // } // // Path: app/src/main/java/ultimategdbot/exception/BotAdminPrivilegeException.java // public final class BotAdminPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/BotOwnerPrivilegeException.java // public final class BotOwnerPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/ElderModPrivilegeException.java // public final class ElderModPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/GuildAdminPrivilegeException.java // public final class GuildAdminPrivilegeException extends PrivilegeException { // }
import botrino.interaction.privilege.Privilege; import botrino.interaction.privilege.Privileges; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.object.entity.ApplicationInfo; import discord4j.rest.util.Permission; import reactor.core.publisher.Mono; import ultimategdbot.database.GdMod; import ultimategdbot.exception.BotAdminPrivilegeException; import ultimategdbot.exception.BotOwnerPrivilegeException; import ultimategdbot.exception.ElderModPrivilegeException; import ultimategdbot.exception.GuildAdminPrivilegeException;
@RdiFactory public PrivilegeFactory(ApplicationInfo applicationInfo, DatabaseService db) { this.ownerId = applicationInfo.getOwnerId().asLong(); this.db = db; } public Privilege botOwner() { return ctx -> ctx.event().getInteraction().getUser().getId().asLong() == ownerId ? Mono.empty() : Mono.error(new BotOwnerPrivilegeException()); } public Privilege botAdmin() { return botOwner().or(ctx -> db.botAdminDao() .exists(ctx.event().getInteraction().getUser().getId().asLong()) .filter(Boolean::booleanValue) .switchIfEmpty(Mono.error(BotAdminPrivilegeException::new)) .then(), (a, b) -> b); } public Privilege guildAdmin() { return botAdmin().or(Privileges.checkPermissions(ctx -> new GuildAdminPrivilegeException(), perms -> perms.contains(Permission.ADMINISTRATOR)), (a, b) -> b); } public Privilege elderMod() { return botOwner().or(ctx -> db.gdLinkedUserDao() .getActiveLink(ctx.event().getInteraction().getUser().getId().asLong()) .flatMap(linkedUser -> db.gdModDao().get(linkedUser.gdUserId()).map(GdMod::isElder)) .filter(Boolean::booleanValue)
// Path: app/src/main/java/ultimategdbot/database/GdMod.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGdMod.class) // @JsonDeserialize(as = ImmutableGdMod.class) // public interface GdMod { // // @Criteria.Id // @JsonProperty("_id") // long accountId(); // // String name(); // // int elder(); // // default boolean isElder() { // return elder() > 0; // } // } // // Path: app/src/main/java/ultimategdbot/exception/BotAdminPrivilegeException.java // public final class BotAdminPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/BotOwnerPrivilegeException.java // public final class BotOwnerPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/ElderModPrivilegeException.java // public final class ElderModPrivilegeException extends PrivilegeException { // } // // Path: app/src/main/java/ultimategdbot/exception/GuildAdminPrivilegeException.java // public final class GuildAdminPrivilegeException extends PrivilegeException { // } // Path: app/src/main/java/ultimategdbot/service/PrivilegeFactory.java import botrino.interaction.privilege.Privilege; import botrino.interaction.privilege.Privileges; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.object.entity.ApplicationInfo; import discord4j.rest.util.Permission; import reactor.core.publisher.Mono; import ultimategdbot.database.GdMod; import ultimategdbot.exception.BotAdminPrivilegeException; import ultimategdbot.exception.BotOwnerPrivilegeException; import ultimategdbot.exception.ElderModPrivilegeException; import ultimategdbot.exception.GuildAdminPrivilegeException; @RdiFactory public PrivilegeFactory(ApplicationInfo applicationInfo, DatabaseService db) { this.ownerId = applicationInfo.getOwnerId().asLong(); this.db = db; } public Privilege botOwner() { return ctx -> ctx.event().getInteraction().getUser().getId().asLong() == ownerId ? Mono.empty() : Mono.error(new BotOwnerPrivilegeException()); } public Privilege botAdmin() { return botOwner().or(ctx -> db.botAdminDao() .exists(ctx.event().getInteraction().getUser().getId().asLong()) .filter(Boolean::booleanValue) .switchIfEmpty(Mono.error(BotAdminPrivilegeException::new)) .then(), (a, b) -> b); } public Privilege guildAdmin() { return botAdmin().or(Privileges.checkPermissions(ctx -> new GuildAdminPrivilegeException(), perms -> perms.contains(Permission.ADMINISTRATOR)), (a, b) -> b); } public Privilege elderMod() { return botOwner().or(ctx -> db.gdLinkedUserDao() .getActiveLink(ctx.event().getInteraction().getUser().getId().asLong()) .flatMap(linkedUser -> db.gdModDao().get(linkedUser.gdUserId()).map(GdMod::isElder)) .filter(Boolean::booleanValue)
.switchIfEmpty(Mono.error(ElderModPrivilegeException::new))
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/framework/UGDBErrorHandler.java
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/service/EmojiService.java // @RdiService // public final class EmojiService { // // private final EmojiManager emojiManager; // // private EmojiService(EmojiManager emojiManager) { // this.emojiManager = emojiManager; // } // // @RdiFactory // public static Mono<EmojiService> create(ConfigContainer configContainer, GatewayDiscordClient gateway) { // var emojiManager = EmojiManager.create( // configContainer.get(UltimateGDBotConfig.class).emojiGuildIds() // .stream() // .map(Snowflake::of) // .collect(Collectors.toSet())); // return emojiManager.loadFromGateway(gateway) // .thenReturn(emojiManager) // .map(EmojiService::new); // } // // public String get(String name) { // try { // return emojiManager.get(name).asFormat(); // } catch (NoSuchElementException e) { // throw new NoSuchElementException("Emoji '" + name + "' not found. Make sure the emoji is uploaded in a " + // "server that the bot has access to, with the ID of that server listed in `config.json`. After " + // "adding the emoji, restart the bot."); // } // } // // public EmojiManager getEmojiManager() { // return emojiManager; // } // }
import botrino.api.util.DurationUtils; import botrino.api.util.MatcherFunction; import botrino.interaction.InteractionErrorHandler; import botrino.interaction.InteractionFailedException; import botrino.interaction.context.InteractionContext; import botrino.interaction.cooldown.CooldownException; import botrino.interaction.privilege.PrivilegeException; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.event.domain.interaction.ApplicationCommandInteractionEvent; import discord4j.core.event.domain.interaction.ChatInputInteractionEvent; import discord4j.core.event.domain.interaction.ComponentInteractionEvent; import discord4j.core.object.command.ApplicationCommandInteractionOption; import discord4j.core.object.command.ApplicationCommandInteractionOptionValue; import discord4j.core.object.command.ApplicationCommandOption; import discord4j.core.object.entity.ApplicationInfo; import discord4j.core.object.entity.User; import jdash.client.exception.GDClientException; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; import reactor.retry.RetryExhaustedException; import reactor.util.Logger; import reactor.util.Loggers; import ultimategdbot.Strings; import ultimategdbot.exception.*; import ultimategdbot.service.EmojiService; import java.util.List; import java.util.concurrent.TimeoutException; import static java.util.stream.Collectors.joining;
package ultimategdbot.framework; @RdiService public class UGDBErrorHandler implements InteractionErrorHandler { private static final Logger LOGGER = Loggers.getLogger(UGDBErrorHandler.class);
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/service/EmojiService.java // @RdiService // public final class EmojiService { // // private final EmojiManager emojiManager; // // private EmojiService(EmojiManager emojiManager) { // this.emojiManager = emojiManager; // } // // @RdiFactory // public static Mono<EmojiService> create(ConfigContainer configContainer, GatewayDiscordClient gateway) { // var emojiManager = EmojiManager.create( // configContainer.get(UltimateGDBotConfig.class).emojiGuildIds() // .stream() // .map(Snowflake::of) // .collect(Collectors.toSet())); // return emojiManager.loadFromGateway(gateway) // .thenReturn(emojiManager) // .map(EmojiService::new); // } // // public String get(String name) { // try { // return emojiManager.get(name).asFormat(); // } catch (NoSuchElementException e) { // throw new NoSuchElementException("Emoji '" + name + "' not found. Make sure the emoji is uploaded in a " + // "server that the bot has access to, with the ID of that server listed in `config.json`. After " + // "adding the emoji, restart the bot."); // } // } // // public EmojiManager getEmojiManager() { // return emojiManager; // } // } // Path: app/src/main/java/ultimategdbot/framework/UGDBErrorHandler.java import botrino.api.util.DurationUtils; import botrino.api.util.MatcherFunction; import botrino.interaction.InteractionErrorHandler; import botrino.interaction.InteractionFailedException; import botrino.interaction.context.InteractionContext; import botrino.interaction.cooldown.CooldownException; import botrino.interaction.privilege.PrivilegeException; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.event.domain.interaction.ApplicationCommandInteractionEvent; import discord4j.core.event.domain.interaction.ChatInputInteractionEvent; import discord4j.core.event.domain.interaction.ComponentInteractionEvent; import discord4j.core.object.command.ApplicationCommandInteractionOption; import discord4j.core.object.command.ApplicationCommandInteractionOptionValue; import discord4j.core.object.command.ApplicationCommandOption; import discord4j.core.object.entity.ApplicationInfo; import discord4j.core.object.entity.User; import jdash.client.exception.GDClientException; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; import reactor.retry.RetryExhaustedException; import reactor.util.Logger; import reactor.util.Loggers; import ultimategdbot.Strings; import ultimategdbot.exception.*; import ultimategdbot.service.EmojiService; import java.util.List; import java.util.concurrent.TimeoutException; import static java.util.stream.Collectors.joining; package ultimategdbot.framework; @RdiService public class UGDBErrorHandler implements InteractionErrorHandler { private static final Logger LOGGER = Loggers.getLogger(UGDBErrorHandler.class);
private final EmojiService emoji;
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/framework/UGDBErrorHandler.java
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/service/EmojiService.java // @RdiService // public final class EmojiService { // // private final EmojiManager emojiManager; // // private EmojiService(EmojiManager emojiManager) { // this.emojiManager = emojiManager; // } // // @RdiFactory // public static Mono<EmojiService> create(ConfigContainer configContainer, GatewayDiscordClient gateway) { // var emojiManager = EmojiManager.create( // configContainer.get(UltimateGDBotConfig.class).emojiGuildIds() // .stream() // .map(Snowflake::of) // .collect(Collectors.toSet())); // return emojiManager.loadFromGateway(gateway) // .thenReturn(emojiManager) // .map(EmojiService::new); // } // // public String get(String name) { // try { // return emojiManager.get(name).asFormat(); // } catch (NoSuchElementException e) { // throw new NoSuchElementException("Emoji '" + name + "' not found. Make sure the emoji is uploaded in a " + // "server that the bot has access to, with the ID of that server listed in `config.json`. After " + // "adding the emoji, restart the bot."); // } // } // // public EmojiManager getEmojiManager() { // return emojiManager; // } // }
import botrino.api.util.DurationUtils; import botrino.api.util.MatcherFunction; import botrino.interaction.InteractionErrorHandler; import botrino.interaction.InteractionFailedException; import botrino.interaction.context.InteractionContext; import botrino.interaction.cooldown.CooldownException; import botrino.interaction.privilege.PrivilegeException; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.event.domain.interaction.ApplicationCommandInteractionEvent; import discord4j.core.event.domain.interaction.ChatInputInteractionEvent; import discord4j.core.event.domain.interaction.ComponentInteractionEvent; import discord4j.core.object.command.ApplicationCommandInteractionOption; import discord4j.core.object.command.ApplicationCommandInteractionOptionValue; import discord4j.core.object.command.ApplicationCommandOption; import discord4j.core.object.entity.ApplicationInfo; import discord4j.core.object.entity.User; import jdash.client.exception.GDClientException; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; import reactor.retry.RetryExhaustedException; import reactor.util.Logger; import reactor.util.Loggers; import ultimategdbot.Strings; import ultimategdbot.exception.*; import ultimategdbot.service.EmojiService; import java.util.List; import java.util.concurrent.TimeoutException; import static java.util.stream.Collectors.joining;
} else { commandName = "unknown"; } return "Command: " + commandName + "\n" + "User: " + ctx.event().getInteraction().getUser().getTag() + "\n"; } private static String formatOptions(List<ApplicationCommandInteractionOption> options) { return options.stream() .map(o -> o.getType() == ApplicationCommandOption.Type.SUB_COMMAND || o.getType() == ApplicationCommandOption.Type.SUB_COMMAND_GROUP ? o.getName() + ' ' + formatOptions(o.getOptions()) : formatOptionValue(o)) .collect(joining(" ")); } private static String formatOptionValue(ApplicationCommandInteractionOption o) { return o.getName() + ":" + o.getValue() .map(ApplicationCommandInteractionOptionValue::getRaw) .orElse("<null>"); } @Override public Mono<Void> handleInteractionFailed(InteractionFailedException e, InteractionContext ctx) { return sendErrorMessage(ctx, e.getMessage()); } @Override public Mono<Void> handlePrivilege(PrivilegeException e, InteractionContext ctx) { return MatcherFunction.<Mono<Void>>create() .matchType(BotOwnerPrivilegeException.class, __ -> sendErrorMessage(ctx,
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/service/EmojiService.java // @RdiService // public final class EmojiService { // // private final EmojiManager emojiManager; // // private EmojiService(EmojiManager emojiManager) { // this.emojiManager = emojiManager; // } // // @RdiFactory // public static Mono<EmojiService> create(ConfigContainer configContainer, GatewayDiscordClient gateway) { // var emojiManager = EmojiManager.create( // configContainer.get(UltimateGDBotConfig.class).emojiGuildIds() // .stream() // .map(Snowflake::of) // .collect(Collectors.toSet())); // return emojiManager.loadFromGateway(gateway) // .thenReturn(emojiManager) // .map(EmojiService::new); // } // // public String get(String name) { // try { // return emojiManager.get(name).asFormat(); // } catch (NoSuchElementException e) { // throw new NoSuchElementException("Emoji '" + name + "' not found. Make sure the emoji is uploaded in a " + // "server that the bot has access to, with the ID of that server listed in `config.json`. After " + // "adding the emoji, restart the bot."); // } // } // // public EmojiManager getEmojiManager() { // return emojiManager; // } // } // Path: app/src/main/java/ultimategdbot/framework/UGDBErrorHandler.java import botrino.api.util.DurationUtils; import botrino.api.util.MatcherFunction; import botrino.interaction.InteractionErrorHandler; import botrino.interaction.InteractionFailedException; import botrino.interaction.context.InteractionContext; import botrino.interaction.cooldown.CooldownException; import botrino.interaction.privilege.PrivilegeException; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.event.domain.interaction.ApplicationCommandInteractionEvent; import discord4j.core.event.domain.interaction.ChatInputInteractionEvent; import discord4j.core.event.domain.interaction.ComponentInteractionEvent; import discord4j.core.object.command.ApplicationCommandInteractionOption; import discord4j.core.object.command.ApplicationCommandInteractionOptionValue; import discord4j.core.object.command.ApplicationCommandOption; import discord4j.core.object.entity.ApplicationInfo; import discord4j.core.object.entity.User; import jdash.client.exception.GDClientException; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; import reactor.retry.RetryExhaustedException; import reactor.util.Logger; import reactor.util.Loggers; import ultimategdbot.Strings; import ultimategdbot.exception.*; import ultimategdbot.service.EmojiService; import java.util.List; import java.util.concurrent.TimeoutException; import static java.util.stream.Collectors.joining; } else { commandName = "unknown"; } return "Command: " + commandName + "\n" + "User: " + ctx.event().getInteraction().getUser().getTag() + "\n"; } private static String formatOptions(List<ApplicationCommandInteractionOption> options) { return options.stream() .map(o -> o.getType() == ApplicationCommandOption.Type.SUB_COMMAND || o.getType() == ApplicationCommandOption.Type.SUB_COMMAND_GROUP ? o.getName() + ' ' + formatOptions(o.getOptions()) : formatOptionValue(o)) .collect(joining(" ")); } private static String formatOptionValue(ApplicationCommandInteractionOption o) { return o.getName() + ":" + o.getValue() .map(ApplicationCommandInteractionOptionValue::getRaw) .orElse("<null>"); } @Override public Mono<Void> handleInteractionFailed(InteractionFailedException e, InteractionContext ctx) { return sendErrorMessage(ctx, e.getMessage()); } @Override public Mono<Void> handlePrivilege(PrivilegeException e, InteractionContext ctx) { return MatcherFunction.<Mono<Void>>create() .matchType(BotOwnerPrivilegeException.class, __ -> sendErrorMessage(ctx,
ctx.translate(Strings.GENERAL, "error_privilege_bot_owner")))
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/event/CrosspostQueue.java
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // }
import botrino.api.i18n.Translator; import discord4j.core.object.entity.Message; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; import reactor.util.Logger; import reactor.util.Loggers; import ultimategdbot.Strings; import java.time.Duration;
package ultimategdbot.event; class CrosspostQueue { private static final Logger LOGGER = Loggers.getLogger(CrosspostQueue.class); private final Translator tr; CrosspostQueue(Translator tr) { this.tr = tr; } void submit(Message message, Object event) { var crosspostCompletion = Sinks.empty(); var warnDelayed = Mono.firstWithSignal(crosspostCompletion.asMono(), Mono .delay(Duration.ofSeconds(10)) .flatMap(__ -> message.getChannel()) .flatMap(channel -> channel.createMessage(":warning: " + tr
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // Path: app/src/main/java/ultimategdbot/event/CrosspostQueue.java import botrino.api.i18n.Translator; import discord4j.core.object.entity.Message; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; import reactor.util.Logger; import reactor.util.Loggers; import ultimategdbot.Strings; import java.time.Duration; package ultimategdbot.event; class CrosspostQueue { private static final Logger LOGGER = Loggers.getLogger(CrosspostQueue.class); private final Translator tr; CrosspostQueue(Translator tr) { this.tr = tr; } void submit(Message message, Object event) { var crosspostCompletion = Sinks.empty(); var warnDelayed = Mono.firstWithSignal(crosspostCompletion.asMono(), Mono .delay(Duration.ofSeconds(10)) .flatMap(__ -> message.getChannel()) .flatMap(channel -> channel.createMessage(":warning: " + tr
.translate(Strings.GD, "gdevents_crosspost_delayed"))));
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/util/GDLevels.java
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // }
import botrino.api.i18n.Translator; import jdash.common.entity.GDLevel; import jdash.common.entity.GDSong; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; import ultimategdbot.Strings; import java.util.Collections; import java.util.HashMap; import java.util.Map;
return vStr.substring(0, vStr.length() - 1) + "." + vStr.charAt(vStr.length() - 1); } public static String coinsToEmoji(String emoji, int n, boolean shorten) { final var output = new StringBuilder(); if (shorten) { if (n <= 0) { return ""; } output.append(emoji); output.append(" x"); output.append(n); } else { if (n <= 0) { return "-"; } for (int i = 1 ; i <= n && i <= 3 ; i++) { output.append(emoji); output.append(" "); } } return output.toString(); } public static String formatSong(Translator tr, GDSong song) { return "__" + song.title() + "__ by " + song.artist(); } public static String formatSongExtra(Translator tr, GDSong song, String emojiPlay, String emojiDownload) { return song.isCustom()
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // Path: app/src/main/java/ultimategdbot/util/GDLevels.java import botrino.api.i18n.Translator; import jdash.common.entity.GDLevel; import jdash.common.entity.GDSong; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; import ultimategdbot.Strings; import java.util.Collections; import java.util.HashMap; import java.util.Map; return vStr.substring(0, vStr.length() - 1) + "." + vStr.charAt(vStr.length() - 1); } public static String coinsToEmoji(String emoji, int n, boolean shorten) { final var output = new StringBuilder(); if (shorten) { if (n <= 0) { return ""; } output.append(emoji); output.append(" x"); output.append(n); } else { if (n <= 0) { return "-"; } for (int i = 1 ; i <= n && i <= 3 ; i++) { output.append(emoji); output.append(" "); } } return output.toString(); } public static String formatSong(Translator tr, GDSong song) { return "__" + song.title() + "__ by " + song.artist(); } public static String formatSongExtra(Translator tr, GDSong song, String emojiPlay, String emojiDownload) { return song.isCustom()
? tr.translate(Strings.GD, "label_song_id") + ' ' + song.id() + " - " +
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/util/Leaderboards.java
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/database/GdLeaderboard.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGdLeaderboard.class) // @JsonDeserialize(as = ImmutableGdLeaderboard.class) // public interface GdLeaderboard { // // @Criteria.Id // @JsonProperty("_id") // long accountId(); // // String name(); // // int stars(); // // int diamonds(); // // int userCoins(); // // int secretCoins(); // // int demons(); // // int creatorPoints(); // // Instant lastRefreshed(); // }
import botrino.api.i18n.Translator; import discord4j.core.object.entity.Guild; import discord4j.core.spec.EmbedCreateSpec; import reactor.util.annotation.Nullable; import ultimategdbot.Strings; import ultimategdbot.database.GdLeaderboard; import java.util.List; import java.util.Objects;
package ultimategdbot.util; public final class Leaderboards { public static final int ENTRIES_PER_PAGE = 20; private Leaderboards() { throw new AssertionError(); } public static EmbedCreateSpec embed(Translator tr, Guild guild, List<LeaderboardEntry> entryList, int page, @Nullable String highlighted, String emoji) { final var size = entryList.size(); final var maxPage = (size - 1) / ENTRIES_PER_PAGE; final var offset = page * ENTRIES_PER_PAGE; final var subList = entryList.subList(offset, Math.min(offset + ENTRIES_PER_PAGE, size)); var embed = EmbedCreateSpec.builder()
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/database/GdLeaderboard.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGdLeaderboard.class) // @JsonDeserialize(as = ImmutableGdLeaderboard.class) // public interface GdLeaderboard { // // @Criteria.Id // @JsonProperty("_id") // long accountId(); // // String name(); // // int stars(); // // int diamonds(); // // int userCoins(); // // int secretCoins(); // // int demons(); // // int creatorPoints(); // // Instant lastRefreshed(); // } // Path: app/src/main/java/ultimategdbot/util/Leaderboards.java import botrino.api.i18n.Translator; import discord4j.core.object.entity.Guild; import discord4j.core.spec.EmbedCreateSpec; import reactor.util.annotation.Nullable; import ultimategdbot.Strings; import ultimategdbot.database.GdLeaderboard; import java.util.List; import java.util.Objects; package ultimategdbot.util; public final class Leaderboards { public static final int ENTRIES_PER_PAGE = 20; private Leaderboards() { throw new AssertionError(); } public static EmbedCreateSpec embed(Translator tr, Guild guild, List<LeaderboardEntry> entryList, int page, @Nullable String highlighted, String emoji) { final var size = entryList.size(); final var maxPage = (size - 1) / ENTRIES_PER_PAGE; final var offset = page * ENTRIES_PER_PAGE; final var subList = entryList.subList(offset, Math.min(offset + ENTRIES_PER_PAGE, size)); var embed = EmbedCreateSpec.builder()
.title(tr.translate(Strings.GD, "lb_title", guild.getName()));
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/util/Leaderboards.java
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/database/GdLeaderboard.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGdLeaderboard.class) // @JsonDeserialize(as = ImmutableGdLeaderboard.class) // public interface GdLeaderboard { // // @Criteria.Id // @JsonProperty("_id") // long accountId(); // // String name(); // // int stars(); // // int diamonds(); // // int userCoins(); // // int secretCoins(); // // int demons(); // // int creatorPoints(); // // Instant lastRefreshed(); // }
import botrino.api.i18n.Translator; import discord4j.core.object.entity.Guild; import discord4j.core.spec.EmbedCreateSpec; import reactor.util.annotation.Nullable; import ultimategdbot.Strings; import ultimategdbot.database.GdLeaderboard; import java.util.List; import java.util.Objects;
var isHighlighted = entry.getStats().name().equalsIgnoreCase(highlighted); var rank = page * ENTRIES_PER_PAGE + i; if (isHighlighted) { sb.append("**"); } var row = String.format("%s | %s %s | %s (%s)", String.format("`#%" + rankWidth + "d`", rank).replaceAll(" ", " ‌‌"), emoji, GDFormatter.formatCode(entry.getValue(), statWidth), entry.getStats().name(), entry.getDiscordUser()); if (row.length() > maxRowLength) { row = row.substring(0, maxRowLength - 3) + "..."; } sb.append(row).append("\n"); if (isHighlighted) { sb.append("**"); } } embed.description("**" + tr.translate(Strings.GD, "lb_total_players", size, emoji) + "**\n\n" + sb); embed.addField("───────────", tr.translate(Strings.GD, "lb_account_notice"), false); if (maxPage > 0) { embed.addField(tr.translate(Strings.GENERAL, "page_x", page + 1, maxPage + 1), tr.translate(Strings.GENERAL, "page_instructions"), false); } return embed.build(); } public static class LeaderboardEntry implements Comparable<LeaderboardEntry> { private final int value;
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/database/GdLeaderboard.java // @Value.Immutable // @Criteria // @Criteria.Repository(facets = { ReactorReadable.class, ReactorWritable.class }) // @JsonSerialize(as = ImmutableGdLeaderboard.class) // @JsonDeserialize(as = ImmutableGdLeaderboard.class) // public interface GdLeaderboard { // // @Criteria.Id // @JsonProperty("_id") // long accountId(); // // String name(); // // int stars(); // // int diamonds(); // // int userCoins(); // // int secretCoins(); // // int demons(); // // int creatorPoints(); // // Instant lastRefreshed(); // } // Path: app/src/main/java/ultimategdbot/util/Leaderboards.java import botrino.api.i18n.Translator; import discord4j.core.object.entity.Guild; import discord4j.core.spec.EmbedCreateSpec; import reactor.util.annotation.Nullable; import ultimategdbot.Strings; import ultimategdbot.database.GdLeaderboard; import java.util.List; import java.util.Objects; var isHighlighted = entry.getStats().name().equalsIgnoreCase(highlighted); var rank = page * ENTRIES_PER_PAGE + i; if (isHighlighted) { sb.append("**"); } var row = String.format("%s | %s %s | %s (%s)", String.format("`#%" + rankWidth + "d`", rank).replaceAll(" ", " ‌‌"), emoji, GDFormatter.formatCode(entry.getValue(), statWidth), entry.getStats().name(), entry.getDiscordUser()); if (row.length() > maxRowLength) { row = row.substring(0, maxRowLength - 3) + "..."; } sb.append(row).append("\n"); if (isHighlighted) { sb.append("**"); } } embed.description("**" + tr.translate(Strings.GD, "lb_total_players", size, emoji) + "**\n\n" + sb); embed.addField("───────────", tr.translate(Strings.GD, "lb_account_notice"), false); if (maxPage > 0) { embed.addField(tr.translate(Strings.GENERAL, "page_x", page + 1, maxPage + 1), tr.translate(Strings.GENERAL, "page_instructions"), false); } return embed.build(); } public static class LeaderboardEntry implements Comparable<LeaderboardEntry> { private final int value;
private final GdLeaderboard stats;
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/util/GDFormatter.java
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // }
import botrino.api.i18n.Translator; import jdash.common.AccessPolicy; import ultimategdbot.Strings;
package ultimategdbot.util; public final class GDFormatter { private GDFormatter() { } public static String formatPolicy(Translator tr, AccessPolicy policy) { String str; switch (policy) { case NONE: str = "policy_none"; break; case FRIENDS_ONLY: str = "policy_friends_only"; break; case ALL: str = "policy_all"; break; default: throw new AssertionError(); }
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // Path: app/src/main/java/ultimategdbot/util/GDFormatter.java import botrino.api.i18n.Translator; import jdash.common.AccessPolicy; import ultimategdbot.Strings; package ultimategdbot.util; public final class GDFormatter { private GDFormatter() { } public static String formatPolicy(Translator tr, AccessPolicy policy) { String str; switch (policy) { case NONE: str = "policy_none"; break; case FRIENDS_ONLY: str = "policy_friends_only"; break; case ALL: str = "policy_all"; break; default: throw new AssertionError(); }
return tr.translate(Strings.GD, str);
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/command/PingCommand.java
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // }
import botrino.api.i18n.Translator; import botrino.api.util.DurationUtils; import botrino.interaction.annotation.Acknowledge; import botrino.interaction.annotation.ChatInputCommand; import botrino.interaction.context.ChatInputInteractionContext; import botrino.interaction.listener.ChatInputInteractionListener; import discord4j.core.event.domain.interaction.InteractionCreateEvent; import discord4j.gateway.GatewayClient; import org.reactivestreams.Publisher; import ultimategdbot.Strings; import java.time.Duration; import static reactor.function.TupleUtils.function;
package ultimategdbot.command; @Acknowledge(Acknowledge.Mode.NONE) @ChatInputCommand(name = "ping", description = "Ping the bot to check if it is alive and view latency information.") public final class PingCommand implements ChatInputInteractionListener { private static String computeLatency(Translator tr, InteractionCreateEvent event, long apiLatency) {
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // Path: app/src/main/java/ultimategdbot/command/PingCommand.java import botrino.api.i18n.Translator; import botrino.api.util.DurationUtils; import botrino.interaction.annotation.Acknowledge; import botrino.interaction.annotation.ChatInputCommand; import botrino.interaction.context.ChatInputInteractionContext; import botrino.interaction.listener.ChatInputInteractionListener; import discord4j.core.event.domain.interaction.InteractionCreateEvent; import discord4j.gateway.GatewayClient; import org.reactivestreams.Publisher; import ultimategdbot.Strings; import java.time.Duration; import static reactor.function.TupleUtils.function; package ultimategdbot.command; @Acknowledge(Acknowledge.Mode.NONE) @ChatInputCommand(name = "ping", description = "Ping the bot to check if it is alive and view latency information.") public final class PingCommand implements ChatInputInteractionListener { private static String computeLatency(Translator tr, InteractionCreateEvent event, long apiLatency) {
return tr.translate(Strings.GENERAL, "pong") + '\n' +
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/service/DatabaseService.java
// Path: app/src/main/java/ultimategdbot/config/MongoDBConfig.java // @ConfigEntry("mongodb") // @Value.Immutable // @JsonDeserialize(as = ImmutableMongoDBConfig.class) // public interface MongoDBConfig { // // @Value.Default // @JsonProperty("database_name") // default String databaseName() { // return "ultimategdbot"; // } // // @Value.Default // @JsonProperty("connection_string") // default String connectionString() { // return "mongodb://localhost:27017"; // } // }
import botrino.api.config.ConfigContainer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import com.mongodb.reactivestreams.client.MongoClients; import discord4j.common.jackson.UnknownPropertyHandler; import org.immutables.criteria.backend.Backend; import org.immutables.criteria.mongo.MongoBackend; import org.immutables.criteria.mongo.MongoSetup; import org.immutables.criteria.mongo.bson4jackson.BsonModule; import org.immutables.criteria.mongo.bson4jackson.IdAnnotationModule; import org.immutables.criteria.mongo.bson4jackson.JacksonCodecs; import ultimategdbot.config.MongoDBConfig; import ultimategdbot.database.*;
package ultimategdbot.service; @RdiService public final class DatabaseService { private final Backend backend; @RdiFactory public DatabaseService(ConfigContainer configContainer) {
// Path: app/src/main/java/ultimategdbot/config/MongoDBConfig.java // @ConfigEntry("mongodb") // @Value.Immutable // @JsonDeserialize(as = ImmutableMongoDBConfig.class) // public interface MongoDBConfig { // // @Value.Default // @JsonProperty("database_name") // default String databaseName() { // return "ultimategdbot"; // } // // @Value.Default // @JsonProperty("connection_string") // default String connectionString() { // return "mongodb://localhost:27017"; // } // } // Path: app/src/main/java/ultimategdbot/service/DatabaseService.java import botrino.api.config.ConfigContainer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import com.mongodb.reactivestreams.client.MongoClients; import discord4j.common.jackson.UnknownPropertyHandler; import org.immutables.criteria.backend.Backend; import org.immutables.criteria.mongo.MongoBackend; import org.immutables.criteria.mongo.MongoSetup; import org.immutables.criteria.mongo.bson4jackson.BsonModule; import org.immutables.criteria.mongo.bson4jackson.IdAnnotationModule; import org.immutables.criteria.mongo.bson4jackson.JacksonCodecs; import ultimategdbot.config.MongoDBConfig; import ultimategdbot.database.*; package ultimategdbot.service; @RdiService public final class DatabaseService { private final Backend backend; @RdiFactory public DatabaseService(ConfigContainer configContainer) {
final var config = configContainer.get(MongoDBConfig.class);
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/service/GDUserService.java
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/util/EmbedType.java // public enum EmbedType { // USER_PROMOTED(tr -> tr.translate(Strings.GD, "gdevents_title_promoted"), "https://i.imgur.com/zY61GDD.png"), // USER_DEMOTED(tr -> tr.translate(Strings.GD, "gdevents_title_demoted"), "https://i.imgur.com/X53HV7d.png"), // USER_PROFILE(tr -> tr.translate(Strings.GD, "user_profile"), "https://i.imgur.com/ppg4HqJ.png"), // LEVEL_SEARCH_RESULT(tr -> tr.translate(Strings.GD, "search_result"), "https://i.imgur.com/a9B6LyS.png"), // DAILY_LEVEL(tr -> tr.translate(Strings.GD, "daily"), "https://i.imgur.com/enpYuB8.png"), // WEEKLY_DEMON(tr -> tr.translate(Strings.GD, "weekly"), "https://i.imgur.com/kcsP5SN.png"), // RATE(tr -> tr.translate(Strings.GD, "gdevents_title_rate"), "https://i.imgur.com/asoMj1W.png"), // UNRATE(tr -> tr.translate(Strings.GD, "gdevents_title_unrate"), "https://i.imgur.com/fPECXUz.png"), // MOD(tr -> tr.translate(Strings.GD, "gdevents_title_promoted"), "https://i.imgur.com/zY61GDD.png"), // UNMOD(tr -> tr.translate(Strings.GD, "gdevents_title_demoted"), "https://i.imgur.com/X53HV7d.png"); // // private final Function<Translator, String> authorName; // private final String authorIconUrl; // // EmbedType(Function<Translator, String> authorName, String authorIconUrl) { // this.authorName = authorName; // this.authorIconUrl = authorIconUrl; // } // // public String getAuthorName(Translator tr) { // return authorName.apply(tr); // } // // public String getAuthorIconUrl() { // return authorIconUrl; // } // } // // Path: app/src/main/java/ultimategdbot/util/GDFormatter.java // public static String formatCode(Object val, int n) { // var sb = new StringBuilder("" + val); // for (var i = sb.length() ; i <= n ; i++) { // sb.insert(0, " ‌‌"); // } // sb.insert(0, '`').append('`'); // return sb.toString(); // } // // Path: app/src/main/java/ultimategdbot/util/GDFormatter.java // public static String formatPolicy(Translator tr, AccessPolicy policy) { // String str; // switch (policy) { // case NONE: // str = "policy_none"; // break; // case FRIENDS_ONLY: // str = "policy_friends_only"; // break; // case ALL: // str = "policy_all"; // break; // default: // throw new AssertionError(); // } // return tr.translate(Strings.GD, str); // }
import botrino.api.i18n.Translator; import botrino.interaction.InteractionFailedException; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.common.util.Snowflake; import discord4j.core.GatewayDiscordClient; import discord4j.core.object.entity.User; import discord4j.core.spec.EmbedCreateSpec; import discord4j.core.spec.MessageCreateFields.File; import discord4j.core.spec.MessageCreateSpec; import jdash.client.GDClient; import jdash.common.IconType; import jdash.common.Role; import jdash.common.entity.GDUserProfile; import jdash.graphics.GDUserIconSet; import jdash.graphics.SpriteFactory; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import reactor.util.annotation.Nullable; import ultimategdbot.Strings; import ultimategdbot.util.EmbedType; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Objects; import java.util.Random; import java.util.stream.Collectors; import static botrino.api.util.Markdown.italic; import static discord4j.core.retriever.EntityRetrievalStrategy.STORE_FALLBACK_REST; import static reactor.function.TupleUtils.function; import static ultimategdbot.util.GDFormatter.formatCode; import static ultimategdbot.util.GDFormatter.formatPolicy;
* Generates a random String made of alphanumeric characters. The length of the generated String is specified as an * argument. * <p> * The following characters are excluded to avoid confusion between l and 1, O and 0, etc: <code>l, I, 1, 0, * O</code> * * @param n the length of the generated String * @return the generated random String */ public static String generateAlphanumericToken(int n) { if (n < 1) { throw new IllegalArgumentException("n is negative"); } var rand = new Random(); var alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; var result = new char[n]; for (int i = 0; i < result.length; i++) { result[i] = alphabet.charAt(rand.nextInt(alphabet.length())); } return new String(result); } private static Mono<ByteArrayInputStream> imageStream(BufferedImage img) { return Mono.fromCallable(() -> { final var os = new ByteArrayOutputStream(100_000); ImageIO.write(img, "png", os); return new ByteArrayInputStream(os.toByteArray()); }).subscribeOn(Schedulers.boundedElastic()); }
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/util/EmbedType.java // public enum EmbedType { // USER_PROMOTED(tr -> tr.translate(Strings.GD, "gdevents_title_promoted"), "https://i.imgur.com/zY61GDD.png"), // USER_DEMOTED(tr -> tr.translate(Strings.GD, "gdevents_title_demoted"), "https://i.imgur.com/X53HV7d.png"), // USER_PROFILE(tr -> tr.translate(Strings.GD, "user_profile"), "https://i.imgur.com/ppg4HqJ.png"), // LEVEL_SEARCH_RESULT(tr -> tr.translate(Strings.GD, "search_result"), "https://i.imgur.com/a9B6LyS.png"), // DAILY_LEVEL(tr -> tr.translate(Strings.GD, "daily"), "https://i.imgur.com/enpYuB8.png"), // WEEKLY_DEMON(tr -> tr.translate(Strings.GD, "weekly"), "https://i.imgur.com/kcsP5SN.png"), // RATE(tr -> tr.translate(Strings.GD, "gdevents_title_rate"), "https://i.imgur.com/asoMj1W.png"), // UNRATE(tr -> tr.translate(Strings.GD, "gdevents_title_unrate"), "https://i.imgur.com/fPECXUz.png"), // MOD(tr -> tr.translate(Strings.GD, "gdevents_title_promoted"), "https://i.imgur.com/zY61GDD.png"), // UNMOD(tr -> tr.translate(Strings.GD, "gdevents_title_demoted"), "https://i.imgur.com/X53HV7d.png"); // // private final Function<Translator, String> authorName; // private final String authorIconUrl; // // EmbedType(Function<Translator, String> authorName, String authorIconUrl) { // this.authorName = authorName; // this.authorIconUrl = authorIconUrl; // } // // public String getAuthorName(Translator tr) { // return authorName.apply(tr); // } // // public String getAuthorIconUrl() { // return authorIconUrl; // } // } // // Path: app/src/main/java/ultimategdbot/util/GDFormatter.java // public static String formatCode(Object val, int n) { // var sb = new StringBuilder("" + val); // for (var i = sb.length() ; i <= n ; i++) { // sb.insert(0, " ‌‌"); // } // sb.insert(0, '`').append('`'); // return sb.toString(); // } // // Path: app/src/main/java/ultimategdbot/util/GDFormatter.java // public static String formatPolicy(Translator tr, AccessPolicy policy) { // String str; // switch (policy) { // case NONE: // str = "policy_none"; // break; // case FRIENDS_ONLY: // str = "policy_friends_only"; // break; // case ALL: // str = "policy_all"; // break; // default: // throw new AssertionError(); // } // return tr.translate(Strings.GD, str); // } // Path: app/src/main/java/ultimategdbot/service/GDUserService.java import botrino.api.i18n.Translator; import botrino.interaction.InteractionFailedException; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.common.util.Snowflake; import discord4j.core.GatewayDiscordClient; import discord4j.core.object.entity.User; import discord4j.core.spec.EmbedCreateSpec; import discord4j.core.spec.MessageCreateFields.File; import discord4j.core.spec.MessageCreateSpec; import jdash.client.GDClient; import jdash.common.IconType; import jdash.common.Role; import jdash.common.entity.GDUserProfile; import jdash.graphics.GDUserIconSet; import jdash.graphics.SpriteFactory; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import reactor.util.annotation.Nullable; import ultimategdbot.Strings; import ultimategdbot.util.EmbedType; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Objects; import java.util.Random; import java.util.stream.Collectors; import static botrino.api.util.Markdown.italic; import static discord4j.core.retriever.EntityRetrievalStrategy.STORE_FALLBACK_REST; import static reactor.function.TupleUtils.function; import static ultimategdbot.util.GDFormatter.formatCode; import static ultimategdbot.util.GDFormatter.formatPolicy; * Generates a random String made of alphanumeric characters. The length of the generated String is specified as an * argument. * <p> * The following characters are excluded to avoid confusion between l and 1, O and 0, etc: <code>l, I, 1, 0, * O</code> * * @param n the length of the generated String * @return the generated random String */ public static String generateAlphanumericToken(int n) { if (n < 1) { throw new IllegalArgumentException("n is negative"); } var rand = new Random(); var alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; var result = new char[n]; for (int i = 0; i < result.length; i++) { result[i] = alphabet.charAt(rand.nextInt(alphabet.length())); } return new String(result); } private static Mono<ByteArrayInputStream> imageStream(BufferedImage img) { return Mono.fromCallable(() -> { final var os = new ByteArrayOutputStream(100_000); ImageIO.write(img, "png", os); return new ByteArrayInputStream(os.toByteArray()); }).subscribeOn(Schedulers.boundedElastic()); }
public Mono<MessageCreateSpec> buildProfile(Translator tr, GDUserProfile gdUser, EmbedType type) {
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/service/GDUserService.java
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/util/EmbedType.java // public enum EmbedType { // USER_PROMOTED(tr -> tr.translate(Strings.GD, "gdevents_title_promoted"), "https://i.imgur.com/zY61GDD.png"), // USER_DEMOTED(tr -> tr.translate(Strings.GD, "gdevents_title_demoted"), "https://i.imgur.com/X53HV7d.png"), // USER_PROFILE(tr -> tr.translate(Strings.GD, "user_profile"), "https://i.imgur.com/ppg4HqJ.png"), // LEVEL_SEARCH_RESULT(tr -> tr.translate(Strings.GD, "search_result"), "https://i.imgur.com/a9B6LyS.png"), // DAILY_LEVEL(tr -> tr.translate(Strings.GD, "daily"), "https://i.imgur.com/enpYuB8.png"), // WEEKLY_DEMON(tr -> tr.translate(Strings.GD, "weekly"), "https://i.imgur.com/kcsP5SN.png"), // RATE(tr -> tr.translate(Strings.GD, "gdevents_title_rate"), "https://i.imgur.com/asoMj1W.png"), // UNRATE(tr -> tr.translate(Strings.GD, "gdevents_title_unrate"), "https://i.imgur.com/fPECXUz.png"), // MOD(tr -> tr.translate(Strings.GD, "gdevents_title_promoted"), "https://i.imgur.com/zY61GDD.png"), // UNMOD(tr -> tr.translate(Strings.GD, "gdevents_title_demoted"), "https://i.imgur.com/X53HV7d.png"); // // private final Function<Translator, String> authorName; // private final String authorIconUrl; // // EmbedType(Function<Translator, String> authorName, String authorIconUrl) { // this.authorName = authorName; // this.authorIconUrl = authorIconUrl; // } // // public String getAuthorName(Translator tr) { // return authorName.apply(tr); // } // // public String getAuthorIconUrl() { // return authorIconUrl; // } // } // // Path: app/src/main/java/ultimategdbot/util/GDFormatter.java // public static String formatCode(Object val, int n) { // var sb = new StringBuilder("" + val); // for (var i = sb.length() ; i <= n ; i++) { // sb.insert(0, " ‌‌"); // } // sb.insert(0, '`').append('`'); // return sb.toString(); // } // // Path: app/src/main/java/ultimategdbot/util/GDFormatter.java // public static String formatPolicy(Translator tr, AccessPolicy policy) { // String str; // switch (policy) { // case NONE: // str = "policy_none"; // break; // case FRIENDS_ONLY: // str = "policy_friends_only"; // break; // case ALL: // str = "policy_all"; // break; // default: // throw new AssertionError(); // } // return tr.translate(Strings.GD, str); // }
import botrino.api.i18n.Translator; import botrino.interaction.InteractionFailedException; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.common.util.Snowflake; import discord4j.core.GatewayDiscordClient; import discord4j.core.object.entity.User; import discord4j.core.spec.EmbedCreateSpec; import discord4j.core.spec.MessageCreateFields.File; import discord4j.core.spec.MessageCreateSpec; import jdash.client.GDClient; import jdash.common.IconType; import jdash.common.Role; import jdash.common.entity.GDUserProfile; import jdash.graphics.GDUserIconSet; import jdash.graphics.SpriteFactory; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import reactor.util.annotation.Nullable; import ultimategdbot.Strings; import ultimategdbot.util.EmbedType; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Objects; import java.util.Random; import java.util.stream.Collectors; import static botrino.api.util.Markdown.italic; import static discord4j.core.retriever.EntityRetrievalStrategy.STORE_FALLBACK_REST; import static reactor.function.TupleUtils.function; import static ultimategdbot.util.GDFormatter.formatCode; import static ultimategdbot.util.GDFormatter.formatPolicy;
for (var iconType : IconType.values()) { icons.add(iconSet.generateIcon(iconType)); } } catch (IllegalArgumentException e) { return Mono.just(new GeneratedIconSet(null, e.getMessage())); } final var iconSetImg = new BufferedImage(icons.stream().mapToInt(BufferedImage::getWidth).sum(), icons.get(0).getHeight(), icons.get(0).getType()); final var g = iconSetImg.createGraphics(); var offset = 0; for (var icon : icons) { g.drawImage(icon, offset, 0, null); offset += icon.getWidth(); } g.dispose(); return imageStream(iconSetImg).map(inputStream -> new GeneratedIconSet(inputStream, null)); }); } public Mono<GDUserProfile> stringToUser(Translator tr, String str) { final var gdClient = this.gdClient.withWriteOnlyCache(); if (!str.matches("[a-zA-Z0-9 _-]+")) { return Mono.error(new InteractionFailedException(tr.translate(Strings.GD, "error_invalid_characters"))); } return gdClient.searchUsers(str, 0).next() .filter(user -> user.accountId() > 0) .flatMap(user -> gdClient.getUserProfile(user.accountId())); } private String statEntry(String emojiName, int stat) {
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/util/EmbedType.java // public enum EmbedType { // USER_PROMOTED(tr -> tr.translate(Strings.GD, "gdevents_title_promoted"), "https://i.imgur.com/zY61GDD.png"), // USER_DEMOTED(tr -> tr.translate(Strings.GD, "gdevents_title_demoted"), "https://i.imgur.com/X53HV7d.png"), // USER_PROFILE(tr -> tr.translate(Strings.GD, "user_profile"), "https://i.imgur.com/ppg4HqJ.png"), // LEVEL_SEARCH_RESULT(tr -> tr.translate(Strings.GD, "search_result"), "https://i.imgur.com/a9B6LyS.png"), // DAILY_LEVEL(tr -> tr.translate(Strings.GD, "daily"), "https://i.imgur.com/enpYuB8.png"), // WEEKLY_DEMON(tr -> tr.translate(Strings.GD, "weekly"), "https://i.imgur.com/kcsP5SN.png"), // RATE(tr -> tr.translate(Strings.GD, "gdevents_title_rate"), "https://i.imgur.com/asoMj1W.png"), // UNRATE(tr -> tr.translate(Strings.GD, "gdevents_title_unrate"), "https://i.imgur.com/fPECXUz.png"), // MOD(tr -> tr.translate(Strings.GD, "gdevents_title_promoted"), "https://i.imgur.com/zY61GDD.png"), // UNMOD(tr -> tr.translate(Strings.GD, "gdevents_title_demoted"), "https://i.imgur.com/X53HV7d.png"); // // private final Function<Translator, String> authorName; // private final String authorIconUrl; // // EmbedType(Function<Translator, String> authorName, String authorIconUrl) { // this.authorName = authorName; // this.authorIconUrl = authorIconUrl; // } // // public String getAuthorName(Translator tr) { // return authorName.apply(tr); // } // // public String getAuthorIconUrl() { // return authorIconUrl; // } // } // // Path: app/src/main/java/ultimategdbot/util/GDFormatter.java // public static String formatCode(Object val, int n) { // var sb = new StringBuilder("" + val); // for (var i = sb.length() ; i <= n ; i++) { // sb.insert(0, " ‌‌"); // } // sb.insert(0, '`').append('`'); // return sb.toString(); // } // // Path: app/src/main/java/ultimategdbot/util/GDFormatter.java // public static String formatPolicy(Translator tr, AccessPolicy policy) { // String str; // switch (policy) { // case NONE: // str = "policy_none"; // break; // case FRIENDS_ONLY: // str = "policy_friends_only"; // break; // case ALL: // str = "policy_all"; // break; // default: // throw new AssertionError(); // } // return tr.translate(Strings.GD, str); // } // Path: app/src/main/java/ultimategdbot/service/GDUserService.java import botrino.api.i18n.Translator; import botrino.interaction.InteractionFailedException; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.common.util.Snowflake; import discord4j.core.GatewayDiscordClient; import discord4j.core.object.entity.User; import discord4j.core.spec.EmbedCreateSpec; import discord4j.core.spec.MessageCreateFields.File; import discord4j.core.spec.MessageCreateSpec; import jdash.client.GDClient; import jdash.common.IconType; import jdash.common.Role; import jdash.common.entity.GDUserProfile; import jdash.graphics.GDUserIconSet; import jdash.graphics.SpriteFactory; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import reactor.util.annotation.Nullable; import ultimategdbot.Strings; import ultimategdbot.util.EmbedType; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Objects; import java.util.Random; import java.util.stream.Collectors; import static botrino.api.util.Markdown.italic; import static discord4j.core.retriever.EntityRetrievalStrategy.STORE_FALLBACK_REST; import static reactor.function.TupleUtils.function; import static ultimategdbot.util.GDFormatter.formatCode; import static ultimategdbot.util.GDFormatter.formatPolicy; for (var iconType : IconType.values()) { icons.add(iconSet.generateIcon(iconType)); } } catch (IllegalArgumentException e) { return Mono.just(new GeneratedIconSet(null, e.getMessage())); } final var iconSetImg = new BufferedImage(icons.stream().mapToInt(BufferedImage::getWidth).sum(), icons.get(0).getHeight(), icons.get(0).getType()); final var g = iconSetImg.createGraphics(); var offset = 0; for (var icon : icons) { g.drawImage(icon, offset, 0, null); offset += icon.getWidth(); } g.dispose(); return imageStream(iconSetImg).map(inputStream -> new GeneratedIconSet(inputStream, null)); }); } public Mono<GDUserProfile> stringToUser(Translator tr, String str) { final var gdClient = this.gdClient.withWriteOnlyCache(); if (!str.matches("[a-zA-Z0-9 _-]+")) { return Mono.error(new InteractionFailedException(tr.translate(Strings.GD, "error_invalid_characters"))); } return gdClient.searchUsers(str, 0).next() .filter(user -> user.accountId() > 0) .flatMap(user -> gdClient.getUserProfile(user.accountId())); } private String statEntry(String emojiName, int stat) {
return emoji.get(emojiName) + " " + formatCode(stat, 9) + '\n';
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/util/Interactions.java
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // }
import botrino.api.i18n.Translator; import botrino.interaction.context.InteractionContext; import botrino.interaction.util.MessagePaginator; import discord4j.common.util.Snowflake; import discord4j.core.object.component.ActionRow; import discord4j.core.object.component.Button; import reactor.core.publisher.Mono; import ultimategdbot.Strings; import java.util.function.Function;
package ultimategdbot.util; public final class Interactions { private Interactions() { throw new AssertionError(); } public static ActionRow paginationButtons(Translator tr, MessagePaginator.State state) { return ActionRow.of( state.previousButton(customId -> Button.secondary(customId,
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // Path: app/src/main/java/ultimategdbot/util/Interactions.java import botrino.api.i18n.Translator; import botrino.interaction.context.InteractionContext; import botrino.interaction.util.MessagePaginator; import discord4j.common.util.Snowflake; import discord4j.core.object.component.ActionRow; import discord4j.core.object.component.Button; import reactor.core.publisher.Mono; import ultimategdbot.Strings; import java.util.function.Function; package ultimategdbot.util; public final class Interactions { private Interactions() { throw new AssertionError(); } public static ActionRow paginationButtons(Translator tr, MessagePaginator.State state) { return ActionRow.of( state.previousButton(customId -> Button.secondary(customId,
"<< " + tr.translate(Strings.GENERAL, "pagination_previous"))),
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/command/RuntimeCommand.java
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/util/SystemUnit.java // public enum SystemUnit { // BYTE, // KILOBYTE, // MEGABYTE, // GIGABYTE, // TERABYTE; // // /** // * Formats the given value to a human readable format, using the appropriate unit // * // * @param byteValue the value to format // * @return String // */ // public static String format(long byteValue) { // SystemUnit unit = BYTE; // double convertedValue = byteValue; // // while (unit.ordinal() < values().length && (convertedValue = unit.convert(byteValue)) >= 1024) // unit = values()[unit.ordinal() + 1]; // // convertedValue = Math.round(convertedValue * 100) / 100.0; // // return String.format("%.2f %s", convertedValue, unit.toString()); // } // // /** // * Converts the given value to the unit represented by the current object // * // * @param byteValue the value to convert // * @return double // */ // public double convert(long byteValue) { // return byteValue / Math.pow(2, this.ordinal() * 10); // } // // @Override // public String toString() { // return super.toString().charAt(0) + (this.ordinal() > 0 ? "B" : ""); // } // }
import botrino.api.i18n.Translator; import botrino.api.util.DurationUtils; import botrino.interaction.annotation.ChatInputCommand; import botrino.interaction.context.ChatInputInteractionContext; import botrino.interaction.listener.ChatInputInteractionListener; import com.sun.management.GarbageCollectionNotificationInfo; import discord4j.core.spec.EmbedCreateSpec; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; import ultimategdbot.Strings; import ultimategdbot.util.SystemUnit; import javax.management.NotificationEmitter; import javax.management.NotificationListener; import javax.management.openmbean.CompositeData; import java.lang.management.ManagementFactory; import java.time.Duration; import java.time.Instant; import java.util.Optional; import java.util.function.Function;
package ultimategdbot.command; @ChatInputCommand(name = "runtime", description = "Display runtime information on the bot.") public final class RuntimeCommand implements ChatInputInteractionListener { public RuntimeCommand() { MemoryStats.start(); } private static Mono<EmbedField> uptime(Translator tr) {
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/util/SystemUnit.java // public enum SystemUnit { // BYTE, // KILOBYTE, // MEGABYTE, // GIGABYTE, // TERABYTE; // // /** // * Formats the given value to a human readable format, using the appropriate unit // * // * @param byteValue the value to format // * @return String // */ // public static String format(long byteValue) { // SystemUnit unit = BYTE; // double convertedValue = byteValue; // // while (unit.ordinal() < values().length && (convertedValue = unit.convert(byteValue)) >= 1024) // unit = values()[unit.ordinal() + 1]; // // convertedValue = Math.round(convertedValue * 100) / 100.0; // // return String.format("%.2f %s", convertedValue, unit.toString()); // } // // /** // * Converts the given value to the unit represented by the current object // * // * @param byteValue the value to convert // * @return double // */ // public double convert(long byteValue) { // return byteValue / Math.pow(2, this.ordinal() * 10); // } // // @Override // public String toString() { // return super.toString().charAt(0) + (this.ordinal() > 0 ? "B" : ""); // } // } // Path: app/src/main/java/ultimategdbot/command/RuntimeCommand.java import botrino.api.i18n.Translator; import botrino.api.util.DurationUtils; import botrino.interaction.annotation.ChatInputCommand; import botrino.interaction.context.ChatInputInteractionContext; import botrino.interaction.listener.ChatInputInteractionListener; import com.sun.management.GarbageCollectionNotificationInfo; import discord4j.core.spec.EmbedCreateSpec; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; import ultimategdbot.Strings; import ultimategdbot.util.SystemUnit; import javax.management.NotificationEmitter; import javax.management.NotificationListener; import javax.management.openmbean.CompositeData; import java.lang.management.ManagementFactory; import java.time.Duration; import java.time.Instant; import java.util.Optional; import java.util.function.Function; package ultimategdbot.command; @ChatInputCommand(name = "runtime", description = "Display runtime information on the bot.") public final class RuntimeCommand implements ChatInputInteractionListener { public RuntimeCommand() { MemoryStats.start(); } private static Mono<EmbedField> uptime(Translator tr) {
return Mono.just(new EmbedField(tr.translate(Strings.GENERAL, "uptime"),
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/command/RuntimeCommand.java
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/util/SystemUnit.java // public enum SystemUnit { // BYTE, // KILOBYTE, // MEGABYTE, // GIGABYTE, // TERABYTE; // // /** // * Formats the given value to a human readable format, using the appropriate unit // * // * @param byteValue the value to format // * @return String // */ // public static String format(long byteValue) { // SystemUnit unit = BYTE; // double convertedValue = byteValue; // // while (unit.ordinal() < values().length && (convertedValue = unit.convert(byteValue)) >= 1024) // unit = values()[unit.ordinal() + 1]; // // convertedValue = Math.round(convertedValue * 100) / 100.0; // // return String.format("%.2f %s", convertedValue, unit.toString()); // } // // /** // * Converts the given value to the unit represented by the current object // * // * @param byteValue the value to convert // * @return double // */ // public double convert(long byteValue) { // return byteValue / Math.pow(2, this.ordinal() * 10); // } // // @Override // public String toString() { // return super.toString().charAt(0) + (this.ordinal() > 0 ? "B" : ""); // } // }
import botrino.api.i18n.Translator; import botrino.api.util.DurationUtils; import botrino.interaction.annotation.ChatInputCommand; import botrino.interaction.context.ChatInputInteractionContext; import botrino.interaction.listener.ChatInputInteractionListener; import com.sun.management.GarbageCollectionNotificationInfo; import discord4j.core.spec.EmbedCreateSpec; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; import ultimategdbot.Strings; import ultimategdbot.util.SystemUnit; import javax.management.NotificationEmitter; import javax.management.NotificationListener; import javax.management.openmbean.CompositeData; import java.lang.management.ManagementFactory; import java.time.Duration; import java.time.Instant; import java.util.Optional; import java.util.function.Function;
package ultimategdbot.command; @ChatInputCommand(name = "runtime", description = "Display runtime information on the bot.") public final class RuntimeCommand implements ChatInputInteractionListener { public RuntimeCommand() { MemoryStats.start(); } private static Mono<EmbedField> uptime(Translator tr) { return Mono.just(new EmbedField(tr.translate(Strings.GENERAL, "uptime"), tr.translate(Strings.GENERAL, "uptime_value", DurationUtils.format( Duration.ofMillis(ManagementFactory.getRuntimeMXBean().getUptime()).withNanos(0))))); } private static Mono<EmbedField> memory(ChatInputInteractionContext ctx) { return MemoryStats.getStats() .map(memStats -> { var total = memStats.totalMemory; var max = memStats.maxMemory; var used = memStats.usedMemory;
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/util/SystemUnit.java // public enum SystemUnit { // BYTE, // KILOBYTE, // MEGABYTE, // GIGABYTE, // TERABYTE; // // /** // * Formats the given value to a human readable format, using the appropriate unit // * // * @param byteValue the value to format // * @return String // */ // public static String format(long byteValue) { // SystemUnit unit = BYTE; // double convertedValue = byteValue; // // while (unit.ordinal() < values().length && (convertedValue = unit.convert(byteValue)) >= 1024) // unit = values()[unit.ordinal() + 1]; // // convertedValue = Math.round(convertedValue * 100) / 100.0; // // return String.format("%.2f %s", convertedValue, unit.toString()); // } // // /** // * Converts the given value to the unit represented by the current object // * // * @param byteValue the value to convert // * @return double // */ // public double convert(long byteValue) { // return byteValue / Math.pow(2, this.ordinal() * 10); // } // // @Override // public String toString() { // return super.toString().charAt(0) + (this.ordinal() > 0 ? "B" : ""); // } // } // Path: app/src/main/java/ultimategdbot/command/RuntimeCommand.java import botrino.api.i18n.Translator; import botrino.api.util.DurationUtils; import botrino.interaction.annotation.ChatInputCommand; import botrino.interaction.context.ChatInputInteractionContext; import botrino.interaction.listener.ChatInputInteractionListener; import com.sun.management.GarbageCollectionNotificationInfo; import discord4j.core.spec.EmbedCreateSpec; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.Sinks; import ultimategdbot.Strings; import ultimategdbot.util.SystemUnit; import javax.management.NotificationEmitter; import javax.management.NotificationListener; import javax.management.openmbean.CompositeData; import java.lang.management.ManagementFactory; import java.time.Duration; import java.time.Instant; import java.util.Optional; import java.util.function.Function; package ultimategdbot.command; @ChatInputCommand(name = "runtime", description = "Display runtime information on the bot.") public final class RuntimeCommand implements ChatInputInteractionListener { public RuntimeCommand() { MemoryStats.start(); } private static Mono<EmbedField> uptime(Translator tr) { return Mono.just(new EmbedField(tr.translate(Strings.GENERAL, "uptime"), tr.translate(Strings.GENERAL, "uptime_value", DurationUtils.format( Duration.ofMillis(ManagementFactory.getRuntimeMXBean().getUptime()).withNanos(0))))); } private static Mono<EmbedField> memory(ChatInputInteractionContext ctx) { return MemoryStats.getStats() .map(memStats -> { var total = memStats.totalMemory; var max = memStats.maxMemory; var used = memStats.usedMemory;
var str = ctx.translate(Strings.GENERAL, "max_ram") + ' ' + SystemUnit.format(max) + "\n" +
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/command/AboutCommand.java
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/util/Resources.java // public final class Resources { // // private static final String UGDB_GIT_RESOURCE = "META-INF/git/ultimategdbot.git.properties"; // // public static Properties ugdbGitProperties() { // try { // var props = new Properties(); // try (var stream = ClassLoader.getSystemResourceAsStream(UGDB_GIT_RESOURCE)) { // if (stream != null) { // props.load(stream); // } // } // return props; // } catch (IOException e) { // throw new UncheckedIOException(e); // } // } // // public static String about() { // try { // return Files.readString(Path.of(".", "about.txt")); // } catch (IOException e) { // throw new UncheckedIOException(e); // } // } // // private Resources() { // throw new AssertionError(); // } // }
import botrino.api.Botrino; import botrino.api.i18n.Translator; import botrino.interaction.annotation.ChatInputCommand; import botrino.interaction.context.ChatInputInteractionContext; import botrino.interaction.listener.ChatInputInteractionListener; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.common.GitProperties; import discord4j.core.object.entity.ApplicationInfo; import discord4j.core.object.entity.User; import org.reactivestreams.Publisher; import reactor.core.publisher.Mono; import ultimategdbot.Strings; import ultimategdbot.util.Resources; import java.util.HashMap; import java.util.Optional; import java.util.Properties; import static reactor.function.TupleUtils.function;
package ultimategdbot.command; @RdiService @ChatInputCommand(name = "about", description = "Show information about the bot itself.") public final class AboutCommand implements ChatInputInteractionListener { private static final Properties D4J_PROPS = GitProperties.getProperties();
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/util/Resources.java // public final class Resources { // // private static final String UGDB_GIT_RESOURCE = "META-INF/git/ultimategdbot.git.properties"; // // public static Properties ugdbGitProperties() { // try { // var props = new Properties(); // try (var stream = ClassLoader.getSystemResourceAsStream(UGDB_GIT_RESOURCE)) { // if (stream != null) { // props.load(stream); // } // } // return props; // } catch (IOException e) { // throw new UncheckedIOException(e); // } // } // // public static String about() { // try { // return Files.readString(Path.of(".", "about.txt")); // } catch (IOException e) { // throw new UncheckedIOException(e); // } // } // // private Resources() { // throw new AssertionError(); // } // } // Path: app/src/main/java/ultimategdbot/command/AboutCommand.java import botrino.api.Botrino; import botrino.api.i18n.Translator; import botrino.interaction.annotation.ChatInputCommand; import botrino.interaction.context.ChatInputInteractionContext; import botrino.interaction.listener.ChatInputInteractionListener; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.common.GitProperties; import discord4j.core.object.entity.ApplicationInfo; import discord4j.core.object.entity.User; import org.reactivestreams.Publisher; import reactor.core.publisher.Mono; import ultimategdbot.Strings; import ultimategdbot.util.Resources; import java.util.HashMap; import java.util.Optional; import java.util.Properties; import static reactor.function.TupleUtils.function; package ultimategdbot.command; @RdiService @ChatInputCommand(name = "about", description = "Show information about the bot itself.") public final class AboutCommand implements ChatInputInteractionListener { private static final Properties D4J_PROPS = GitProperties.getProperties();
private static final Properties UGDB_PROPS = Resources.ugdbGitProperties();
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/command/AboutCommand.java
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/util/Resources.java // public final class Resources { // // private static final String UGDB_GIT_RESOURCE = "META-INF/git/ultimategdbot.git.properties"; // // public static Properties ugdbGitProperties() { // try { // var props = new Properties(); // try (var stream = ClassLoader.getSystemResourceAsStream(UGDB_GIT_RESOURCE)) { // if (stream != null) { // props.load(stream); // } // } // return props; // } catch (IOException e) { // throw new UncheckedIOException(e); // } // } // // public static String about() { // try { // return Files.readString(Path.of(".", "about.txt")); // } catch (IOException e) { // throw new UncheckedIOException(e); // } // } // // private Resources() { // throw new AssertionError(); // } // }
import botrino.api.Botrino; import botrino.api.i18n.Translator; import botrino.interaction.annotation.ChatInputCommand; import botrino.interaction.context.ChatInputInteractionContext; import botrino.interaction.listener.ChatInputInteractionListener; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.common.GitProperties; import discord4j.core.object.entity.ApplicationInfo; import discord4j.core.object.entity.User; import org.reactivestreams.Publisher; import reactor.core.publisher.Mono; import ultimategdbot.Strings; import ultimategdbot.util.Resources; import java.util.HashMap; import java.util.Optional; import java.util.Properties; import static reactor.function.TupleUtils.function;
package ultimategdbot.command; @RdiService @ChatInputCommand(name = "about", description = "Show information about the bot itself.") public final class AboutCommand implements ChatInputInteractionListener { private static final Properties D4J_PROPS = GitProperties.getProperties(); private static final Properties UGDB_PROPS = Resources.ugdbGitProperties(); private static final String ABOUT = Resources.about(); private final User botOwner; private AboutCommand(User botOwner) { this.botOwner = botOwner; } @RdiFactory public static Mono<AboutCommand> create(ApplicationInfo applicationInfo) { return applicationInfo.getOwner().map(AboutCommand::new); } private static String version(Translator tr, Properties props) { return Optional.ofNullable(props.getProperty(GitProperties.APPLICATION_VERSION))
// Path: app/src/main/java/ultimategdbot/Strings.java // public final class Strings { // // public static final String GENERAL = "GeneralStrings"; // public static final String GD = "GDStrings"; // // private Strings() { // throw new AssertionError(); // } // } // // Path: app/src/main/java/ultimategdbot/util/Resources.java // public final class Resources { // // private static final String UGDB_GIT_RESOURCE = "META-INF/git/ultimategdbot.git.properties"; // // public static Properties ugdbGitProperties() { // try { // var props = new Properties(); // try (var stream = ClassLoader.getSystemResourceAsStream(UGDB_GIT_RESOURCE)) { // if (stream != null) { // props.load(stream); // } // } // return props; // } catch (IOException e) { // throw new UncheckedIOException(e); // } // } // // public static String about() { // try { // return Files.readString(Path.of(".", "about.txt")); // } catch (IOException e) { // throw new UncheckedIOException(e); // } // } // // private Resources() { // throw new AssertionError(); // } // } // Path: app/src/main/java/ultimategdbot/command/AboutCommand.java import botrino.api.Botrino; import botrino.api.i18n.Translator; import botrino.interaction.annotation.ChatInputCommand; import botrino.interaction.context.ChatInputInteractionContext; import botrino.interaction.listener.ChatInputInteractionListener; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.common.GitProperties; import discord4j.core.object.entity.ApplicationInfo; import discord4j.core.object.entity.User; import org.reactivestreams.Publisher; import reactor.core.publisher.Mono; import ultimategdbot.Strings; import ultimategdbot.util.Resources; import java.util.HashMap; import java.util.Optional; import java.util.Properties; import static reactor.function.TupleUtils.function; package ultimategdbot.command; @RdiService @ChatInputCommand(name = "about", description = "Show information about the bot itself.") public final class AboutCommand implements ChatInputInteractionListener { private static final Properties D4J_PROPS = GitProperties.getProperties(); private static final Properties UGDB_PROPS = Resources.ugdbGitProperties(); private static final String ABOUT = Resources.about(); private final User botOwner; private AboutCommand(User botOwner) { this.botOwner = botOwner; } @RdiFactory public static Mono<AboutCommand> create(ApplicationInfo applicationInfo) { return applicationInfo.getOwner().map(AboutCommand::new); } private static String version(Translator tr, Properties props) { return Optional.ofNullable(props.getProperty(GitProperties.APPLICATION_VERSION))
.orElse("*" + tr.translate(Strings.GENERAL, "unknown") + "*");
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/service/ExternalServices.java
// Path: app/src/main/java/ultimategdbot/config/UltimateGDBotConfig.java // @ConfigEntry("ultimategdbot") // @Value.Immutable // @JsonDeserialize(as = ImmutableUltimateGDBotConfig.class) // public interface UltimateGDBotConfig { // // @JsonProperty("pagination_max_entries") // int paginationMaxEntries(); // // @JsonProperty("emoji_guild_ids") // Set<Long> emojiGuildIds(); // // @JsonProperty("command_cooldown") // Optional<Limiter> commandCooldown(); // // @JsonProperty("legacy_command_redirect_prefix") // Optional<String> legacyCommandRedirectPrefix(); // // @Value.Default // @JsonProperty("command_permissions") // default List<CommandPermission> commandPermissions() { // return List.of(); // } // // @Value.Default // @JsonProperty("bot_announcements_channel_ids") // default Set<Long> botAnnouncementsChannelIds() { // return Set.of(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableCommandPermission.class) // interface CommandPermission { // // String name(); // // @JsonProperty("guild_id") // long guildId(); // // @JsonProperty("role_id") // long roleId(); // } // // GD gd(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableGD.class) // interface GD { // // Client client(); // // Events events(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableClient.class) // interface Client { // // String username(); // // String password(); // // String host(); // // @JsonProperty("cache_ttl_seconds") // int cacheTtlSeconds(); // // @JsonProperty("request_timeout_seconds") // int requestTimeoutSeconds(); // // @JsonProperty("request_limiter") // Optional<Limiter> requestLimiter(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableEvents.class) // interface Events { // // @JsonProperty("event_loop_interval_seconds") // int eventLoopIntervalSeconds(); // // boolean crosspost(); // // @JsonProperty("rates_channel_ids") // Set<Long> ratesChannelIds(); // // @JsonProperty("demons_channel_ids") // Set<Long> demonsChannelIds(); // // @JsonProperty("timely_channel_id") // Optional<Long> timelyChannelId(); // // @JsonProperty("mods_channel_id") // Optional<Long> modsChannelId(); // // @JsonProperty("public_random_messages") // RandomMessages publicRandomMessages(); // // @JsonProperty("dm_random_messages") // RandomMessages dmRandomMessages(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableRandomMessages.class) // interface RandomMessages { // // List<String> rates(); // // List<String> unrates(); // // List<String> daily(); // // List<String> weekly(); // // List<String> mod(); // // @JsonProperty("elder_mod") // List<String> elderMod(); // // List<String> unmod(); // // @JsonProperty("elder_unmod") // List<String> elderUnmod(); // } // } // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableLimiter.class) // interface Limiter { // // @Value.Default // default int limit() { // return 10; // } // // @Value.Default // @JsonProperty("interval_seconds") // default int intervalSeconds() { // return 60; // } // } // }
import botrino.api.config.ConfigContainer; import discord4j.core.GatewayDiscordClient; import discord4j.core.object.entity.ApplicationInfo; import jdash.client.GDClient; import jdash.client.cache.GDCache; import jdash.client.request.GDRouter; import jdash.client.request.RequestLimiter; import jdash.graphics.SpriteFactory; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import reactor.util.Logger; import reactor.util.Loggers; import ultimategdbot.config.UltimateGDBotConfig; import java.time.Duration;
package ultimategdbot.service; public final class ExternalServices { private static final Logger LOGGER = Loggers.getLogger(ExternalServices.class); private ExternalServices() { throw new AssertionError(); } public static Mono<ApplicationInfo> applicationInfo(GatewayDiscordClient gateway) { return gateway.getApplicationInfo(); } public static Mono<GDClient> gdClient(ConfigContainer configContainer) {
// Path: app/src/main/java/ultimategdbot/config/UltimateGDBotConfig.java // @ConfigEntry("ultimategdbot") // @Value.Immutable // @JsonDeserialize(as = ImmutableUltimateGDBotConfig.class) // public interface UltimateGDBotConfig { // // @JsonProperty("pagination_max_entries") // int paginationMaxEntries(); // // @JsonProperty("emoji_guild_ids") // Set<Long> emojiGuildIds(); // // @JsonProperty("command_cooldown") // Optional<Limiter> commandCooldown(); // // @JsonProperty("legacy_command_redirect_prefix") // Optional<String> legacyCommandRedirectPrefix(); // // @Value.Default // @JsonProperty("command_permissions") // default List<CommandPermission> commandPermissions() { // return List.of(); // } // // @Value.Default // @JsonProperty("bot_announcements_channel_ids") // default Set<Long> botAnnouncementsChannelIds() { // return Set.of(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableCommandPermission.class) // interface CommandPermission { // // String name(); // // @JsonProperty("guild_id") // long guildId(); // // @JsonProperty("role_id") // long roleId(); // } // // GD gd(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableGD.class) // interface GD { // // Client client(); // // Events events(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableClient.class) // interface Client { // // String username(); // // String password(); // // String host(); // // @JsonProperty("cache_ttl_seconds") // int cacheTtlSeconds(); // // @JsonProperty("request_timeout_seconds") // int requestTimeoutSeconds(); // // @JsonProperty("request_limiter") // Optional<Limiter> requestLimiter(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableEvents.class) // interface Events { // // @JsonProperty("event_loop_interval_seconds") // int eventLoopIntervalSeconds(); // // boolean crosspost(); // // @JsonProperty("rates_channel_ids") // Set<Long> ratesChannelIds(); // // @JsonProperty("demons_channel_ids") // Set<Long> demonsChannelIds(); // // @JsonProperty("timely_channel_id") // Optional<Long> timelyChannelId(); // // @JsonProperty("mods_channel_id") // Optional<Long> modsChannelId(); // // @JsonProperty("public_random_messages") // RandomMessages publicRandomMessages(); // // @JsonProperty("dm_random_messages") // RandomMessages dmRandomMessages(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableRandomMessages.class) // interface RandomMessages { // // List<String> rates(); // // List<String> unrates(); // // List<String> daily(); // // List<String> weekly(); // // List<String> mod(); // // @JsonProperty("elder_mod") // List<String> elderMod(); // // List<String> unmod(); // // @JsonProperty("elder_unmod") // List<String> elderUnmod(); // } // } // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableLimiter.class) // interface Limiter { // // @Value.Default // default int limit() { // return 10; // } // // @Value.Default // @JsonProperty("interval_seconds") // default int intervalSeconds() { // return 60; // } // } // } // Path: app/src/main/java/ultimategdbot/service/ExternalServices.java import botrino.api.config.ConfigContainer; import discord4j.core.GatewayDiscordClient; import discord4j.core.object.entity.ApplicationInfo; import jdash.client.GDClient; import jdash.client.cache.GDCache; import jdash.client.request.GDRouter; import jdash.client.request.RequestLimiter; import jdash.graphics.SpriteFactory; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import reactor.util.Logger; import reactor.util.Loggers; import ultimategdbot.config.UltimateGDBotConfig; import java.time.Duration; package ultimategdbot.service; public final class ExternalServices { private static final Logger LOGGER = Loggers.getLogger(ExternalServices.class); private ExternalServices() { throw new AssertionError(); } public static Mono<ApplicationInfo> applicationInfo(GatewayDiscordClient gateway) { return gateway.getApplicationInfo(); } public static Mono<GDClient> gdClient(ConfigContainer configContainer) {
var config = configContainer.get(UltimateGDBotConfig.class).gd().client();
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/service/LegacyCommandRedirectService.java
// Path: app/src/main/java/ultimategdbot/config/UltimateGDBotConfig.java // @ConfigEntry("ultimategdbot") // @Value.Immutable // @JsonDeserialize(as = ImmutableUltimateGDBotConfig.class) // public interface UltimateGDBotConfig { // // @JsonProperty("pagination_max_entries") // int paginationMaxEntries(); // // @JsonProperty("emoji_guild_ids") // Set<Long> emojiGuildIds(); // // @JsonProperty("command_cooldown") // Optional<Limiter> commandCooldown(); // // @JsonProperty("legacy_command_redirect_prefix") // Optional<String> legacyCommandRedirectPrefix(); // // @Value.Default // @JsonProperty("command_permissions") // default List<CommandPermission> commandPermissions() { // return List.of(); // } // // @Value.Default // @JsonProperty("bot_announcements_channel_ids") // default Set<Long> botAnnouncementsChannelIds() { // return Set.of(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableCommandPermission.class) // interface CommandPermission { // // String name(); // // @JsonProperty("guild_id") // long guildId(); // // @JsonProperty("role_id") // long roleId(); // } // // GD gd(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableGD.class) // interface GD { // // Client client(); // // Events events(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableClient.class) // interface Client { // // String username(); // // String password(); // // String host(); // // @JsonProperty("cache_ttl_seconds") // int cacheTtlSeconds(); // // @JsonProperty("request_timeout_seconds") // int requestTimeoutSeconds(); // // @JsonProperty("request_limiter") // Optional<Limiter> requestLimiter(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableEvents.class) // interface Events { // // @JsonProperty("event_loop_interval_seconds") // int eventLoopIntervalSeconds(); // // boolean crosspost(); // // @JsonProperty("rates_channel_ids") // Set<Long> ratesChannelIds(); // // @JsonProperty("demons_channel_ids") // Set<Long> demonsChannelIds(); // // @JsonProperty("timely_channel_id") // Optional<Long> timelyChannelId(); // // @JsonProperty("mods_channel_id") // Optional<Long> modsChannelId(); // // @JsonProperty("public_random_messages") // RandomMessages publicRandomMessages(); // // @JsonProperty("dm_random_messages") // RandomMessages dmRandomMessages(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableRandomMessages.class) // interface RandomMessages { // // List<String> rates(); // // List<String> unrates(); // // List<String> daily(); // // List<String> weekly(); // // List<String> mod(); // // @JsonProperty("elder_mod") // List<String> elderMod(); // // List<String> unmod(); // // @JsonProperty("elder_unmod") // List<String> elderUnmod(); // } // } // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableLimiter.class) // interface Limiter { // // @Value.Default // default int limit() { // return 10; // } // // @Value.Default // @JsonProperty("interval_seconds") // default int intervalSeconds() { // return 60; // } // } // }
import botrino.api.config.ConfigContainer; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.GatewayDiscordClient; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.object.entity.ApplicationInfo; import reactor.core.publisher.Mono; import ultimategdbot.config.UltimateGDBotConfig;
package ultimategdbot.service; @RdiService public final class LegacyCommandRedirectService { @RdiFactory public LegacyCommandRedirectService(ApplicationInfo applicationInfo, ConfigContainer configContainer, GatewayDiscordClient gateway, EmojiService emoji) {
// Path: app/src/main/java/ultimategdbot/config/UltimateGDBotConfig.java // @ConfigEntry("ultimategdbot") // @Value.Immutable // @JsonDeserialize(as = ImmutableUltimateGDBotConfig.class) // public interface UltimateGDBotConfig { // // @JsonProperty("pagination_max_entries") // int paginationMaxEntries(); // // @JsonProperty("emoji_guild_ids") // Set<Long> emojiGuildIds(); // // @JsonProperty("command_cooldown") // Optional<Limiter> commandCooldown(); // // @JsonProperty("legacy_command_redirect_prefix") // Optional<String> legacyCommandRedirectPrefix(); // // @Value.Default // @JsonProperty("command_permissions") // default List<CommandPermission> commandPermissions() { // return List.of(); // } // // @Value.Default // @JsonProperty("bot_announcements_channel_ids") // default Set<Long> botAnnouncementsChannelIds() { // return Set.of(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableCommandPermission.class) // interface CommandPermission { // // String name(); // // @JsonProperty("guild_id") // long guildId(); // // @JsonProperty("role_id") // long roleId(); // } // // GD gd(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableGD.class) // interface GD { // // Client client(); // // Events events(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableClient.class) // interface Client { // // String username(); // // String password(); // // String host(); // // @JsonProperty("cache_ttl_seconds") // int cacheTtlSeconds(); // // @JsonProperty("request_timeout_seconds") // int requestTimeoutSeconds(); // // @JsonProperty("request_limiter") // Optional<Limiter> requestLimiter(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableEvents.class) // interface Events { // // @JsonProperty("event_loop_interval_seconds") // int eventLoopIntervalSeconds(); // // boolean crosspost(); // // @JsonProperty("rates_channel_ids") // Set<Long> ratesChannelIds(); // // @JsonProperty("demons_channel_ids") // Set<Long> demonsChannelIds(); // // @JsonProperty("timely_channel_id") // Optional<Long> timelyChannelId(); // // @JsonProperty("mods_channel_id") // Optional<Long> modsChannelId(); // // @JsonProperty("public_random_messages") // RandomMessages publicRandomMessages(); // // @JsonProperty("dm_random_messages") // RandomMessages dmRandomMessages(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableRandomMessages.class) // interface RandomMessages { // // List<String> rates(); // // List<String> unrates(); // // List<String> daily(); // // List<String> weekly(); // // List<String> mod(); // // @JsonProperty("elder_mod") // List<String> elderMod(); // // List<String> unmod(); // // @JsonProperty("elder_unmod") // List<String> elderUnmod(); // } // } // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableLimiter.class) // interface Limiter { // // @Value.Default // default int limit() { // return 10; // } // // @Value.Default // @JsonProperty("interval_seconds") // default int intervalSeconds() { // return 60; // } // } // } // Path: app/src/main/java/ultimategdbot/service/LegacyCommandRedirectService.java import botrino.api.config.ConfigContainer; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import discord4j.core.GatewayDiscordClient; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.object.entity.ApplicationInfo; import reactor.core.publisher.Mono; import ultimategdbot.config.UltimateGDBotConfig; package ultimategdbot.service; @RdiService public final class LegacyCommandRedirectService { @RdiFactory public LegacyCommandRedirectService(ApplicationInfo applicationInfo, ConfigContainer configContainer, GatewayDiscordClient gateway, EmojiService emoji) {
configContainer.get(UltimateGDBotConfig.class).legacyCommandRedirectPrefix()
Alex1304/ultimategdbot
app/src/main/java/ultimategdbot/service/GDCommandCooldown.java
// Path: app/src/main/java/ultimategdbot/config/UltimateGDBotConfig.java // @ConfigEntry("ultimategdbot") // @Value.Immutable // @JsonDeserialize(as = ImmutableUltimateGDBotConfig.class) // public interface UltimateGDBotConfig { // // @JsonProperty("pagination_max_entries") // int paginationMaxEntries(); // // @JsonProperty("emoji_guild_ids") // Set<Long> emojiGuildIds(); // // @JsonProperty("command_cooldown") // Optional<Limiter> commandCooldown(); // // @JsonProperty("legacy_command_redirect_prefix") // Optional<String> legacyCommandRedirectPrefix(); // // @Value.Default // @JsonProperty("command_permissions") // default List<CommandPermission> commandPermissions() { // return List.of(); // } // // @Value.Default // @JsonProperty("bot_announcements_channel_ids") // default Set<Long> botAnnouncementsChannelIds() { // return Set.of(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableCommandPermission.class) // interface CommandPermission { // // String name(); // // @JsonProperty("guild_id") // long guildId(); // // @JsonProperty("role_id") // long roleId(); // } // // GD gd(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableGD.class) // interface GD { // // Client client(); // // Events events(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableClient.class) // interface Client { // // String username(); // // String password(); // // String host(); // // @JsonProperty("cache_ttl_seconds") // int cacheTtlSeconds(); // // @JsonProperty("request_timeout_seconds") // int requestTimeoutSeconds(); // // @JsonProperty("request_limiter") // Optional<Limiter> requestLimiter(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableEvents.class) // interface Events { // // @JsonProperty("event_loop_interval_seconds") // int eventLoopIntervalSeconds(); // // boolean crosspost(); // // @JsonProperty("rates_channel_ids") // Set<Long> ratesChannelIds(); // // @JsonProperty("demons_channel_ids") // Set<Long> demonsChannelIds(); // // @JsonProperty("timely_channel_id") // Optional<Long> timelyChannelId(); // // @JsonProperty("mods_channel_id") // Optional<Long> modsChannelId(); // // @JsonProperty("public_random_messages") // RandomMessages publicRandomMessages(); // // @JsonProperty("dm_random_messages") // RandomMessages dmRandomMessages(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableRandomMessages.class) // interface RandomMessages { // // List<String> rates(); // // List<String> unrates(); // // List<String> daily(); // // List<String> weekly(); // // List<String> mod(); // // @JsonProperty("elder_mod") // List<String> elderMod(); // // List<String> unmod(); // // @JsonProperty("elder_unmod") // List<String> elderUnmod(); // } // } // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableLimiter.class) // interface Limiter { // // @Value.Default // default int limit() { // return 10; // } // // @Value.Default // @JsonProperty("interval_seconds") // default int intervalSeconds() { // return 60; // } // } // }
import botrino.api.config.ConfigContainer; import botrino.interaction.cooldown.Cooldown; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import ultimategdbot.config.UltimateGDBotConfig; import java.time.Duration;
package ultimategdbot.service; @RdiService public final class GDCommandCooldown { private final Cooldown cooldown; @RdiFactory public GDCommandCooldown(ConfigContainer configContainer) {
// Path: app/src/main/java/ultimategdbot/config/UltimateGDBotConfig.java // @ConfigEntry("ultimategdbot") // @Value.Immutable // @JsonDeserialize(as = ImmutableUltimateGDBotConfig.class) // public interface UltimateGDBotConfig { // // @JsonProperty("pagination_max_entries") // int paginationMaxEntries(); // // @JsonProperty("emoji_guild_ids") // Set<Long> emojiGuildIds(); // // @JsonProperty("command_cooldown") // Optional<Limiter> commandCooldown(); // // @JsonProperty("legacy_command_redirect_prefix") // Optional<String> legacyCommandRedirectPrefix(); // // @Value.Default // @JsonProperty("command_permissions") // default List<CommandPermission> commandPermissions() { // return List.of(); // } // // @Value.Default // @JsonProperty("bot_announcements_channel_ids") // default Set<Long> botAnnouncementsChannelIds() { // return Set.of(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableCommandPermission.class) // interface CommandPermission { // // String name(); // // @JsonProperty("guild_id") // long guildId(); // // @JsonProperty("role_id") // long roleId(); // } // // GD gd(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableGD.class) // interface GD { // // Client client(); // // Events events(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableClient.class) // interface Client { // // String username(); // // String password(); // // String host(); // // @JsonProperty("cache_ttl_seconds") // int cacheTtlSeconds(); // // @JsonProperty("request_timeout_seconds") // int requestTimeoutSeconds(); // // @JsonProperty("request_limiter") // Optional<Limiter> requestLimiter(); // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableEvents.class) // interface Events { // // @JsonProperty("event_loop_interval_seconds") // int eventLoopIntervalSeconds(); // // boolean crosspost(); // // @JsonProperty("rates_channel_ids") // Set<Long> ratesChannelIds(); // // @JsonProperty("demons_channel_ids") // Set<Long> demonsChannelIds(); // // @JsonProperty("timely_channel_id") // Optional<Long> timelyChannelId(); // // @JsonProperty("mods_channel_id") // Optional<Long> modsChannelId(); // // @JsonProperty("public_random_messages") // RandomMessages publicRandomMessages(); // // @JsonProperty("dm_random_messages") // RandomMessages dmRandomMessages(); // // @Value.Immutable // @JsonDeserialize(as = ImmutableRandomMessages.class) // interface RandomMessages { // // List<String> rates(); // // List<String> unrates(); // // List<String> daily(); // // List<String> weekly(); // // List<String> mod(); // // @JsonProperty("elder_mod") // List<String> elderMod(); // // List<String> unmod(); // // @JsonProperty("elder_unmod") // List<String> elderUnmod(); // } // } // } // // @Value.Immutable // @JsonDeserialize(as = ImmutableLimiter.class) // interface Limiter { // // @Value.Default // default int limit() { // return 10; // } // // @Value.Default // @JsonProperty("interval_seconds") // default int intervalSeconds() { // return 60; // } // } // } // Path: app/src/main/java/ultimategdbot/service/GDCommandCooldown.java import botrino.api.config.ConfigContainer; import botrino.interaction.cooldown.Cooldown; import com.github.alex1304.rdi.finder.annotation.RdiFactory; import com.github.alex1304.rdi.finder.annotation.RdiService; import ultimategdbot.config.UltimateGDBotConfig; import java.time.Duration; package ultimategdbot.service; @RdiService public final class GDCommandCooldown { private final Cooldown cooldown; @RdiFactory public GDCommandCooldown(ConfigContainer configContainer) {
final var config = configContainer.get(UltimateGDBotConfig.class);
jescov/jescov
src/test/com/olabini/jescov/LineCoverageStepdefs.java
// Path: src/test/com/olabini/jescov/matchers/LineCoverageMatcher.java // public static LineCoverageMatcher hasLineCoverage(int expected) { // return new LineCoverageMatcher(expected); // } // // Path: src/test/com/olabini/jescov/matchers/LineCoverageMatcher.java // public static LineCoverageMatcher haveBlankLineCoverage() { // return new LineCoverageMatcher(-1); // }
import static org.hamcrest.MatcherAssert.assertThat; import static com.olabini.jescov.matchers.LineCoverageMatcher.hasLineCoverage; import static com.olabini.jescov.matchers.LineCoverageMatcher.haveBlankLineCoverage; import cucumber.annotation.en.Then; import java.util.List;
/* * See LICENSE file in distribution for copyright and licensing information. */ package com.olabini.jescov; public class LineCoverageStepdefs { private CucumberData data; public LineCoverageStepdefs(CucumberData data) { this.data = data; } @Then("^the line coverage on line (\\d+) should be (\\d+)$") public void the_line_coverage_on_line_should_be_(int line, int expectedCoverage) {
// Path: src/test/com/olabini/jescov/matchers/LineCoverageMatcher.java // public static LineCoverageMatcher hasLineCoverage(int expected) { // return new LineCoverageMatcher(expected); // } // // Path: src/test/com/olabini/jescov/matchers/LineCoverageMatcher.java // public static LineCoverageMatcher haveBlankLineCoverage() { // return new LineCoverageMatcher(-1); // } // Path: src/test/com/olabini/jescov/LineCoverageStepdefs.java import static org.hamcrest.MatcherAssert.assertThat; import static com.olabini.jescov.matchers.LineCoverageMatcher.hasLineCoverage; import static com.olabini.jescov.matchers.LineCoverageMatcher.haveBlankLineCoverage; import cucumber.annotation.en.Then; import java.util.List; /* * See LICENSE file in distribution for copyright and licensing information. */ package com.olabini.jescov; public class LineCoverageStepdefs { private CucumberData data; public LineCoverageStepdefs(CucumberData data) { this.data = data; } @Then("^the line coverage on line (\\d+) should be (\\d+)$") public void the_line_coverage_on_line_should_be_(int line, int expectedCoverage) {
assertThat(data.getCoverageData(), hasLineCoverage(expectedCoverage).onLine(line));
jescov/jescov
src/test/com/olabini/jescov/LineCoverageStepdefs.java
// Path: src/test/com/olabini/jescov/matchers/LineCoverageMatcher.java // public static LineCoverageMatcher hasLineCoverage(int expected) { // return new LineCoverageMatcher(expected); // } // // Path: src/test/com/olabini/jescov/matchers/LineCoverageMatcher.java // public static LineCoverageMatcher haveBlankLineCoverage() { // return new LineCoverageMatcher(-1); // }
import static org.hamcrest.MatcherAssert.assertThat; import static com.olabini.jescov.matchers.LineCoverageMatcher.hasLineCoverage; import static com.olabini.jescov.matchers.LineCoverageMatcher.haveBlankLineCoverage; import cucumber.annotation.en.Then; import java.util.List;
/* * See LICENSE file in distribution for copyright and licensing information. */ package com.olabini.jescov; public class LineCoverageStepdefs { private CucumberData data; public LineCoverageStepdefs(CucumberData data) { this.data = data; } @Then("^the line coverage on line (\\d+) should be (\\d+)$") public void the_line_coverage_on_line_should_be_(int line, int expectedCoverage) { assertThat(data.getCoverageData(), hasLineCoverage(expectedCoverage).onLine(line)); } @Then("^the line coverage on line (\\d+) should be blank$") public void the_line_coverage_on_line_should_be_blank(int line) {
// Path: src/test/com/olabini/jescov/matchers/LineCoverageMatcher.java // public static LineCoverageMatcher hasLineCoverage(int expected) { // return new LineCoverageMatcher(expected); // } // // Path: src/test/com/olabini/jescov/matchers/LineCoverageMatcher.java // public static LineCoverageMatcher haveBlankLineCoverage() { // return new LineCoverageMatcher(-1); // } // Path: src/test/com/olabini/jescov/LineCoverageStepdefs.java import static org.hamcrest.MatcherAssert.assertThat; import static com.olabini.jescov.matchers.LineCoverageMatcher.hasLineCoverage; import static com.olabini.jescov.matchers.LineCoverageMatcher.haveBlankLineCoverage; import cucumber.annotation.en.Then; import java.util.List; /* * See LICENSE file in distribution for copyright and licensing information. */ package com.olabini.jescov; public class LineCoverageStepdefs { private CucumberData data; public LineCoverageStepdefs(CucumberData data) { this.data = data; } @Then("^the line coverage on line (\\d+) should be (\\d+)$") public void the_line_coverage_on_line_should_be_(int line, int expectedCoverage) { assertThat(data.getCoverageData(), hasLineCoverage(expectedCoverage).onLine(line)); } @Then("^the line coverage on line (\\d+) should be blank$") public void the_line_coverage_on_line_should_be_blank(int line) {
assertThat(data.getCoverageData(), haveBlankLineCoverage().onLine(line));
jescov/jescov
src/test/com/olabini/jescov/CucumberData.java
// Path: src/main/com/olabini/jescov/console/Runner.java // public class Runner { // private final Context ctx; // private final Scriptable scope; // private final Coverage coverage; // private final Configuration configuration; // // public Runner(Configuration configuration) { // ctx = Context.enter(); // scope = ctx.initStandardObjects(); // this.configuration = configuration; // coverage = on(ctx, scope, configuration); // } // // public CoverageData done() { // coverage.done(); // Context.exit(); // return coverage.getCoverageData(); // } // // public void executeReader(String filename, Reader reader) throws IOException { // ctx.evaluateReader(scope, reader, filename, 0, null); // } // // public void executeSource(String filename, String sourceCode) { // ctx.evaluateString(scope, sourceCode, filename, 0, null); // } // // public static void main(final String[] args) throws Exception { // Configuration c = new Configuration(); // String fileout = c.getJsonOutputFile(); // FileWriter fw = new FileWriter(fileout); // c.setGenerator(new CombinedGenerator(new JsonGenerator(fw), new HtmlGenerator(c))); // Runner r = new Runner(c); // for(String file : args) { // r.executeReader(file, new FileReader(file)); // } // CoverageData data = r.done(); // // if(c.isJsonOutputMerge() && new File(fileout).exists()) { // FileReader fr = new FileReader(fileout); // CoverageData moreData = new JsonIngester().ingest(fr); // fr.close(); // data = moreData.plus(data); // } // // c.getGenerator().generate(data); // fw.close(); // } // }// Runner
import com.olabini.jescov.console.Runner;
/* * See LICENSE file in distribution for copyright and licensing information. */ package com.olabini.jescov; public class CucumberData { private CoverageData coverageData;
// Path: src/main/com/olabini/jescov/console/Runner.java // public class Runner { // private final Context ctx; // private final Scriptable scope; // private final Coverage coverage; // private final Configuration configuration; // // public Runner(Configuration configuration) { // ctx = Context.enter(); // scope = ctx.initStandardObjects(); // this.configuration = configuration; // coverage = on(ctx, scope, configuration); // } // // public CoverageData done() { // coverage.done(); // Context.exit(); // return coverage.getCoverageData(); // } // // public void executeReader(String filename, Reader reader) throws IOException { // ctx.evaluateReader(scope, reader, filename, 0, null); // } // // public void executeSource(String filename, String sourceCode) { // ctx.evaluateString(scope, sourceCode, filename, 0, null); // } // // public static void main(final String[] args) throws Exception { // Configuration c = new Configuration(); // String fileout = c.getJsonOutputFile(); // FileWriter fw = new FileWriter(fileout); // c.setGenerator(new CombinedGenerator(new JsonGenerator(fw), new HtmlGenerator(c))); // Runner r = new Runner(c); // for(String file : args) { // r.executeReader(file, new FileReader(file)); // } // CoverageData data = r.done(); // // if(c.isJsonOutputMerge() && new File(fileout).exists()) { // FileReader fr = new FileReader(fileout); // CoverageData moreData = new JsonIngester().ingest(fr); // fr.close(); // data = moreData.plus(data); // } // // c.getGenerator().generate(data); // fw.close(); // } // }// Runner // Path: src/test/com/olabini/jescov/CucumberData.java import com.olabini.jescov.console.Runner; /* * See LICENSE file in distribution for copyright and licensing information. */ package com.olabini.jescov; public class CucumberData { private CoverageData coverageData;
private Runner runner;
jescov/jescov
src/main/com/olabini/jescov/Configuration.java
// Path: src/main/com/olabini/jescov/generators/Generator.java // public interface Generator { // void generate(CoverageData data) throws IOException; // }
import com.olabini.jescov.generators.Generator;
} public void setEnabled(boolean enabled) { this.enabled = enabled; } public void ignore(String filename) { ignore(new File(filename)); } public void ignore(Ignore ignore) { this.ignore = new Chained(ignore, this.ignore); } public String getJsonOutputFile() { return this.jsonOutputFile; } public boolean isJsonOutputMerge() { return this.jsonOutputMerge; } public void setJsonOutputMerge(boolean merge) { this.jsonOutputMerge = merge; } public boolean allow(String filename) { return ignore.allow(filename); }
// Path: src/main/com/olabini/jescov/generators/Generator.java // public interface Generator { // void generate(CoverageData data) throws IOException; // } // Path: src/main/com/olabini/jescov/Configuration.java import com.olabini.jescov.generators.Generator; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public void ignore(String filename) { ignore(new File(filename)); } public void ignore(Ignore ignore) { this.ignore = new Chained(ignore, this.ignore); } public String getJsonOutputFile() { return this.jsonOutputFile; } public boolean isJsonOutputMerge() { return this.jsonOutputMerge; } public void setJsonOutputMerge(boolean merge) { this.jsonOutputMerge = merge; } public boolean allow(String filename) { return ignore.allow(filename); }
private Generator generator;
jescov/jescov
src/main/com/olabini/jescov/generators/CombinedGenerator.java
// Path: src/main/com/olabini/jescov/CoverageData.java // public class CoverageData { // private final Map<String, FileCoverage> fileCoverage; // // public CoverageData(List<FileCoverage> fileCoverage) { // this.fileCoverage = new TreeMap<String, FileCoverage>(); // for(FileCoverage fc : fileCoverage) { // this.fileCoverage.put(fc.getFilename(), fc); // } // } // // public FileCoverage getFileCoverageFor(String filename) { // return fileCoverage.get(filename); // } // // public Collection<String> getFileNames() { // return fileCoverage.keySet(); // } // // public int getLinesValid() { // int sum = 0; // for(FileCoverage fc : fileCoverage.values()) { // sum += fc.getLinesValid(); // } // return sum; // } // // public int getBranchesValid() { // int sum = 0; // for(FileCoverage fc : fileCoverage.values()) { // sum += fc.getBranchesValid(); // } // return sum; // } // // public int getLinesCovered() { // int sum = 0; // for(FileCoverage fc : fileCoverage.values()) { // sum += fc.getLinesCovered(); // } // return sum; // } // // public int getBranchesCovered() { // int sum = 0; // for(FileCoverage fc : fileCoverage.values()) { // sum += fc.getBranchesCovered(); // } // return sum; // } // // public double getLineRate() { // return getLinesCovered() / (double)getLinesValid(); // } // // public double getBranchRate() { // return getBranchesCovered() / (double)getBranchesValid(); // } // // public CoverageData plus(CoverageData other) { // List<FileCoverage> fcs = new ArrayList<FileCoverage>(); // Set<String> files = new HashSet<String>(); // files.addAll(this.getFileNames()); // files.addAll(other.getFileNames()); // for(String file : files) { // FileCoverage left = this.getFileCoverageFor(file); // FileCoverage right = other.getFileCoverageFor(file); // // if(left == null || right == null) { // if(left == null) { // fcs.add(right); // } else { // fcs.add(left); // } // } else { // fcs.add(left.plus(right)); // } // } // // return new CoverageData(fcs); // } // }
import java.io.IOException; import com.olabini.jescov.CoverageData; import java.util.List; import static java.util.Arrays.asList;
/* * See LICENSE file in distribution for copyright and licensing information. */ package com.olabini.jescov.generators; public class CombinedGenerator implements Generator { private final List<Generator> generators; public CombinedGenerator(Generator... generators) { this.generators = asList(generators); }
// Path: src/main/com/olabini/jescov/CoverageData.java // public class CoverageData { // private final Map<String, FileCoverage> fileCoverage; // // public CoverageData(List<FileCoverage> fileCoverage) { // this.fileCoverage = new TreeMap<String, FileCoverage>(); // for(FileCoverage fc : fileCoverage) { // this.fileCoverage.put(fc.getFilename(), fc); // } // } // // public FileCoverage getFileCoverageFor(String filename) { // return fileCoverage.get(filename); // } // // public Collection<String> getFileNames() { // return fileCoverage.keySet(); // } // // public int getLinesValid() { // int sum = 0; // for(FileCoverage fc : fileCoverage.values()) { // sum += fc.getLinesValid(); // } // return sum; // } // // public int getBranchesValid() { // int sum = 0; // for(FileCoverage fc : fileCoverage.values()) { // sum += fc.getBranchesValid(); // } // return sum; // } // // public int getLinesCovered() { // int sum = 0; // for(FileCoverage fc : fileCoverage.values()) { // sum += fc.getLinesCovered(); // } // return sum; // } // // public int getBranchesCovered() { // int sum = 0; // for(FileCoverage fc : fileCoverage.values()) { // sum += fc.getBranchesCovered(); // } // return sum; // } // // public double getLineRate() { // return getLinesCovered() / (double)getLinesValid(); // } // // public double getBranchRate() { // return getBranchesCovered() / (double)getBranchesValid(); // } // // public CoverageData plus(CoverageData other) { // List<FileCoverage> fcs = new ArrayList<FileCoverage>(); // Set<String> files = new HashSet<String>(); // files.addAll(this.getFileNames()); // files.addAll(other.getFileNames()); // for(String file : files) { // FileCoverage left = this.getFileCoverageFor(file); // FileCoverage right = other.getFileCoverageFor(file); // // if(left == null || right == null) { // if(left == null) { // fcs.add(right); // } else { // fcs.add(left); // } // } else { // fcs.add(left.plus(right)); // } // } // // return new CoverageData(fcs); // } // } // Path: src/main/com/olabini/jescov/generators/CombinedGenerator.java import java.io.IOException; import com.olabini.jescov.CoverageData; import java.util.List; import static java.util.Arrays.asList; /* * See LICENSE file in distribution for copyright and licensing information. */ package com.olabini.jescov.generators; public class CombinedGenerator implements Generator { private final List<Generator> generators; public CombinedGenerator(Generator... generators) { this.generators = asList(generators); }
public void generate(CoverageData data) throws IOException {
jescov/jescov
src/test/com/olabini/jescov/matchers/LineCoverageMatcher.java
// Path: src/main/com/olabini/jescov/LineCoverage.java // public class LineCoverage { // private final int line; // private final int hits; // // public LineCoverage(int line, int hits) { // this.line = line; // this.hits = hits; // } // // public int getLine() { // return this.line; // } // // public int getHits() { // return this.hits; // } // // public int getLinesValid() { // return 1; // } // // public int getLinesCovered() { // return hits > 0 ? 1 : 0; // } // } // // Path: src/main/com/olabini/jescov/CoverageData.java // public class CoverageData { // private final Map<String, FileCoverage> fileCoverage; // // public CoverageData(List<FileCoverage> fileCoverage) { // this.fileCoverage = new TreeMap<String, FileCoverage>(); // for(FileCoverage fc : fileCoverage) { // this.fileCoverage.put(fc.getFilename(), fc); // } // } // // public FileCoverage getFileCoverageFor(String filename) { // return fileCoverage.get(filename); // } // // public Collection<String> getFileNames() { // return fileCoverage.keySet(); // } // // public int getLinesValid() { // int sum = 0; // for(FileCoverage fc : fileCoverage.values()) { // sum += fc.getLinesValid(); // } // return sum; // } // // public int getBranchesValid() { // int sum = 0; // for(FileCoverage fc : fileCoverage.values()) { // sum += fc.getBranchesValid(); // } // return sum; // } // // public int getLinesCovered() { // int sum = 0; // for(FileCoverage fc : fileCoverage.values()) { // sum += fc.getLinesCovered(); // } // return sum; // } // // public int getBranchesCovered() { // int sum = 0; // for(FileCoverage fc : fileCoverage.values()) { // sum += fc.getBranchesCovered(); // } // return sum; // } // // public double getLineRate() { // return getLinesCovered() / (double)getLinesValid(); // } // // public double getBranchRate() { // return getBranchesCovered() / (double)getBranchesValid(); // } // // public CoverageData plus(CoverageData other) { // List<FileCoverage> fcs = new ArrayList<FileCoverage>(); // Set<String> files = new HashSet<String>(); // files.addAll(this.getFileNames()); // files.addAll(other.getFileNames()); // for(String file : files) { // FileCoverage left = this.getFileCoverageFor(file); // FileCoverage right = other.getFileCoverageFor(file); // // if(left == null || right == null) { // if(left == null) { // fcs.add(right); // } else { // fcs.add(left); // } // } else { // fcs.add(left.plus(right)); // } // } // // return new CoverageData(fcs); // } // } // // Path: src/main/com/olabini/jescov/console/Runner.java // public class Runner { // private final Context ctx; // private final Scriptable scope; // private final Coverage coverage; // private final Configuration configuration; // // public Runner(Configuration configuration) { // ctx = Context.enter(); // scope = ctx.initStandardObjects(); // this.configuration = configuration; // coverage = on(ctx, scope, configuration); // } // // public CoverageData done() { // coverage.done(); // Context.exit(); // return coverage.getCoverageData(); // } // // public void executeReader(String filename, Reader reader) throws IOException { // ctx.evaluateReader(scope, reader, filename, 0, null); // } // // public void executeSource(String filename, String sourceCode) { // ctx.evaluateString(scope, sourceCode, filename, 0, null); // } // // public static void main(final String[] args) throws Exception { // Configuration c = new Configuration(); // String fileout = c.getJsonOutputFile(); // FileWriter fw = new FileWriter(fileout); // c.setGenerator(new CombinedGenerator(new JsonGenerator(fw), new HtmlGenerator(c))); // Runner r = new Runner(c); // for(String file : args) { // r.executeReader(file, new FileReader(file)); // } // CoverageData data = r.done(); // // if(c.isJsonOutputMerge() && new File(fileout).exists()) { // FileReader fr = new FileReader(fileout); // CoverageData moreData = new JsonIngester().ingest(fr); // fr.close(); // data = moreData.plus(data); // } // // c.getGenerator().generate(data); // fw.close(); // } // }// Runner
import com.olabini.jescov.LineCoverage; import com.olabini.jescov.CoverageData; import com.olabini.jescov.console.Runner; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher;
/* * See LICENSE file in distribution for copyright and licensing information. */ package com.olabini.jescov.matchers; public class LineCoverageMatcher extends TypeSafeMatcher<CoverageData> { private final int expected; private final Integer line; public LineCoverageMatcher(int expected) { this(expected, null); } public LineCoverageMatcher(int expected, Integer line) { this.expected = expected; this.line = line; }
// Path: src/main/com/olabini/jescov/LineCoverage.java // public class LineCoverage { // private final int line; // private final int hits; // // public LineCoverage(int line, int hits) { // this.line = line; // this.hits = hits; // } // // public int getLine() { // return this.line; // } // // public int getHits() { // return this.hits; // } // // public int getLinesValid() { // return 1; // } // // public int getLinesCovered() { // return hits > 0 ? 1 : 0; // } // } // // Path: src/main/com/olabini/jescov/CoverageData.java // public class CoverageData { // private final Map<String, FileCoverage> fileCoverage; // // public CoverageData(List<FileCoverage> fileCoverage) { // this.fileCoverage = new TreeMap<String, FileCoverage>(); // for(FileCoverage fc : fileCoverage) { // this.fileCoverage.put(fc.getFilename(), fc); // } // } // // public FileCoverage getFileCoverageFor(String filename) { // return fileCoverage.get(filename); // } // // public Collection<String> getFileNames() { // return fileCoverage.keySet(); // } // // public int getLinesValid() { // int sum = 0; // for(FileCoverage fc : fileCoverage.values()) { // sum += fc.getLinesValid(); // } // return sum; // } // // public int getBranchesValid() { // int sum = 0; // for(FileCoverage fc : fileCoverage.values()) { // sum += fc.getBranchesValid(); // } // return sum; // } // // public int getLinesCovered() { // int sum = 0; // for(FileCoverage fc : fileCoverage.values()) { // sum += fc.getLinesCovered(); // } // return sum; // } // // public int getBranchesCovered() { // int sum = 0; // for(FileCoverage fc : fileCoverage.values()) { // sum += fc.getBranchesCovered(); // } // return sum; // } // // public double getLineRate() { // return getLinesCovered() / (double)getLinesValid(); // } // // public double getBranchRate() { // return getBranchesCovered() / (double)getBranchesValid(); // } // // public CoverageData plus(CoverageData other) { // List<FileCoverage> fcs = new ArrayList<FileCoverage>(); // Set<String> files = new HashSet<String>(); // files.addAll(this.getFileNames()); // files.addAll(other.getFileNames()); // for(String file : files) { // FileCoverage left = this.getFileCoverageFor(file); // FileCoverage right = other.getFileCoverageFor(file); // // if(left == null || right == null) { // if(left == null) { // fcs.add(right); // } else { // fcs.add(left); // } // } else { // fcs.add(left.plus(right)); // } // } // // return new CoverageData(fcs); // } // } // // Path: src/main/com/olabini/jescov/console/Runner.java // public class Runner { // private final Context ctx; // private final Scriptable scope; // private final Coverage coverage; // private final Configuration configuration; // // public Runner(Configuration configuration) { // ctx = Context.enter(); // scope = ctx.initStandardObjects(); // this.configuration = configuration; // coverage = on(ctx, scope, configuration); // } // // public CoverageData done() { // coverage.done(); // Context.exit(); // return coverage.getCoverageData(); // } // // public void executeReader(String filename, Reader reader) throws IOException { // ctx.evaluateReader(scope, reader, filename, 0, null); // } // // public void executeSource(String filename, String sourceCode) { // ctx.evaluateString(scope, sourceCode, filename, 0, null); // } // // public static void main(final String[] args) throws Exception { // Configuration c = new Configuration(); // String fileout = c.getJsonOutputFile(); // FileWriter fw = new FileWriter(fileout); // c.setGenerator(new CombinedGenerator(new JsonGenerator(fw), new HtmlGenerator(c))); // Runner r = new Runner(c); // for(String file : args) { // r.executeReader(file, new FileReader(file)); // } // CoverageData data = r.done(); // // if(c.isJsonOutputMerge() && new File(fileout).exists()) { // FileReader fr = new FileReader(fileout); // CoverageData moreData = new JsonIngester().ingest(fr); // fr.close(); // data = moreData.plus(data); // } // // c.getGenerator().generate(data); // fw.close(); // } // }// Runner // Path: src/test/com/olabini/jescov/matchers/LineCoverageMatcher.java import com.olabini.jescov.LineCoverage; import com.olabini.jescov.CoverageData; import com.olabini.jescov.console.Runner; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; /* * See LICENSE file in distribution for copyright and licensing information. */ package com.olabini.jescov.matchers; public class LineCoverageMatcher extends TypeSafeMatcher<CoverageData> { private final int expected; private final Integer line; public LineCoverageMatcher(int expected) { this(expected, null); } public LineCoverageMatcher(int expected, Integer line) { this.expected = expected; this.line = line; }
private LineCoverage lc;
jescov/jescov
src/main/com/olabini/jescov/CoverageRewriter.java
// Path: src/main/org/mozilla/javascript/MozillaPackageProxy.java // public class MozillaPackageProxy { // public static void copyInterpreterInternals(Script from, DebuggableScript to) { // InterpreterData fromId = ((InterpretedFunction)from).idata; // InterpreterData toId = (InterpreterData)to; // // toId.itsName = fromId.itsName; // toId.itsSourceFile = fromId.itsSourceFile; // toId.itsNeedsActivation = fromId.itsNeedsActivation; // toId.itsFunctionType = fromId.itsFunctionType; // // toId.itsStringTable = fromId.itsStringTable; // toId.itsDoubleTable = fromId.itsDoubleTable; // toId.itsNestedFunctions = fromId.itsNestedFunctions; // toId.itsRegExpLiterals = fromId.itsRegExpLiterals; // // toId.itsICode = fromId.itsICode; // // toId.itsExceptionTable = fromId.itsExceptionTable; // // toId.itsMaxVars = fromId.itsMaxVars; // toId.itsMaxLocals = fromId.itsMaxLocals; // toId.itsMaxStack = fromId.itsMaxStack; // toId.itsMaxFrameArray = fromId.itsMaxFrameArray; // // toId.argNames = fromId.argNames; // toId.argIsConst = fromId.argIsConst; // toId.argCount = fromId.argCount; // // toId.itsMaxCalleeArgs= fromId.itsMaxCalleeArgs; // // toId.encodedSource = fromId.encodedSource; // toId.encodedSourceStart= fromId.encodedSourceStart; // toId.encodedSourceEnd = fromId.encodedSourceEnd; // // toId.languageVersion = fromId.languageVersion; // // toId.useDynamicScope = fromId.useDynamicScope; // toId.isStrict = fromId.isStrict; // toId.topLevel = fromId.topLevel; // // toId.literalIds = fromId.literalIds; // // toId.longJumps = fromId.longJumps; // // toId.firstLinePC = fromId.firstLinePC; // // toId.parentData = fromId.parentData; // // toId.evalScriptFlag = fromId.evalScriptFlag; // } // }
import org.mozilla.javascript.Context; import org.mozilla.javascript.MozillaPackageProxy; import org.mozilla.javascript.Script; import org.mozilla.javascript.debug.DebuggableScript;
package com.olabini.jescov; public class CoverageRewriter { private final CoverageNameMapper nameMapper; private final Context context; public CoverageRewriter(CoverageNameMapper nameMapper, Context context) { this.nameMapper = nameMapper; this.context = context; } public void rewrite(DebuggableScript input, String source) { CodeInstrumentor ci = new CodeInstrumentor(nameMapper); String ic = ci.instrument(input.getSourceName(), source); // System.err.println("New code: " + ic); Script s = context.compileString(ic, input.getSourceName(), 0, null);
// Path: src/main/org/mozilla/javascript/MozillaPackageProxy.java // public class MozillaPackageProxy { // public static void copyInterpreterInternals(Script from, DebuggableScript to) { // InterpreterData fromId = ((InterpretedFunction)from).idata; // InterpreterData toId = (InterpreterData)to; // // toId.itsName = fromId.itsName; // toId.itsSourceFile = fromId.itsSourceFile; // toId.itsNeedsActivation = fromId.itsNeedsActivation; // toId.itsFunctionType = fromId.itsFunctionType; // // toId.itsStringTable = fromId.itsStringTable; // toId.itsDoubleTable = fromId.itsDoubleTable; // toId.itsNestedFunctions = fromId.itsNestedFunctions; // toId.itsRegExpLiterals = fromId.itsRegExpLiterals; // // toId.itsICode = fromId.itsICode; // // toId.itsExceptionTable = fromId.itsExceptionTable; // // toId.itsMaxVars = fromId.itsMaxVars; // toId.itsMaxLocals = fromId.itsMaxLocals; // toId.itsMaxStack = fromId.itsMaxStack; // toId.itsMaxFrameArray = fromId.itsMaxFrameArray; // // toId.argNames = fromId.argNames; // toId.argIsConst = fromId.argIsConst; // toId.argCount = fromId.argCount; // // toId.itsMaxCalleeArgs= fromId.itsMaxCalleeArgs; // // toId.encodedSource = fromId.encodedSource; // toId.encodedSourceStart= fromId.encodedSourceStart; // toId.encodedSourceEnd = fromId.encodedSourceEnd; // // toId.languageVersion = fromId.languageVersion; // // toId.useDynamicScope = fromId.useDynamicScope; // toId.isStrict = fromId.isStrict; // toId.topLevel = fromId.topLevel; // // toId.literalIds = fromId.literalIds; // // toId.longJumps = fromId.longJumps; // // toId.firstLinePC = fromId.firstLinePC; // // toId.parentData = fromId.parentData; // // toId.evalScriptFlag = fromId.evalScriptFlag; // } // } // Path: src/main/com/olabini/jescov/CoverageRewriter.java import org.mozilla.javascript.Context; import org.mozilla.javascript.MozillaPackageProxy; import org.mozilla.javascript.Script; import org.mozilla.javascript.debug.DebuggableScript; package com.olabini.jescov; public class CoverageRewriter { private final CoverageNameMapper nameMapper; private final Context context; public CoverageRewriter(CoverageNameMapper nameMapper, Context context) { this.nameMapper = nameMapper; this.context = context; } public void rewrite(DebuggableScript input, String source) { CodeInstrumentor ci = new CodeInstrumentor(nameMapper); String ic = ci.instrument(input.getSourceName(), source); // System.err.println("New code: " + ic); Script s = context.compileString(ic, input.getSourceName(), 0, null);
MozillaPackageProxy.copyInterpreterInternals(s, input);
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/LiteralValuesProviderForTypeScriptTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import org.junit.Test; import static org.junit.Assert.assertEquals;
package org.telosys.tools.generic.model.types; public class LiteralValuesProviderForTypeScriptTest { //---------------------------------------------------------------------------------- private TypeConverter getTypeConverter() { return new TypeConverterForJavaScript() ; } private LiteralValuesProvider getLiteralValuesProvider() { return new LiteralValuesProviderForJavaScript() ; } private LanguageType getLanguageType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private LanguageType getLanguageType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); System.out.println("AttributeTypeInfo : " + attributeTypeInfo); return getLanguageType(attributeTypeInfo); } //---------------------------------------------------------------------------------- @Test public void testLiteralNull() { assertEquals("null", getLiteralValuesProvider().getLiteralNull() ); } @Test public void testLiteralValuesForBOOLEAN() {
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // Path: src/test/java/org/telosys/tools/generic/model/types/LiteralValuesProviderForTypeScriptTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import org.junit.Test; import static org.junit.Assert.assertEquals; package org.telosys.tools.generic.model.types; public class LiteralValuesProviderForTypeScriptTest { //---------------------------------------------------------------------------------- private TypeConverter getTypeConverter() { return new TypeConverterForJavaScript() ; } private LiteralValuesProvider getLiteralValuesProvider() { return new LiteralValuesProviderForJavaScript() ; } private LanguageType getLanguageType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private LanguageType getLanguageType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); System.out.println("AttributeTypeInfo : " + attributeTypeInfo); return getLanguageType(attributeTypeInfo); } //---------------------------------------------------------------------------------- @Test public void testLiteralNull() { assertEquals("null", getLiteralValuesProvider().getLiteralNull() ); } @Test public void testLiteralValuesForBOOLEAN() {
LanguageType lt = getLanguageType(NeutralType.BOOLEAN, NONE );
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/CascadeOptionsTest.java
// Path: src/main/java/org/telosys/tools/generic/model/enums/CascadeOption.java // public enum CascadeOption { // // /** // * // */ // MERGE(0, "MERGE"), // // /** // * // */ // PERSIST(1, "PERSIST"), // // /** // * // */ // REFRESH(2, "REFRESH"), // // /** // * // */ // REMOVE(3, "REMOVE"), // // /** // * // */ // ALL(4, "ALL"); // // //--------------------------------------------------- // private final int value ; // private final String text ; // // private CascadeOption(int value, String text) { // this.value = value ; // this.text = text ; // } // // /** // * Returns the fetch type as an int value (0 to 3) <br> // * @return // */ // public int getValue() { // return this.value ; // } // // /** // * Returns the fetch type as a text<br> // * e.g. : 'MERGE', 'PERSIST', etc // * @return // */ // public String getText() { // return this.text; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; import org.telosys.tools.generic.model.enums.CascadeOption;
package org.telosys.tools.generic.model; public class CascadeOptionsTest { @Test public void test0() { System.out.println("\nCascadeOptionsTest : test0 : ");
// Path: src/main/java/org/telosys/tools/generic/model/enums/CascadeOption.java // public enum CascadeOption { // // /** // * // */ // MERGE(0, "MERGE"), // // /** // * // */ // PERSIST(1, "PERSIST"), // // /** // * // */ // REFRESH(2, "REFRESH"), // // /** // * // */ // REMOVE(3, "REMOVE"), // // /** // * // */ // ALL(4, "ALL"); // // //--------------------------------------------------- // private final int value ; // private final String text ; // // private CascadeOption(int value, String text) { // this.value = value ; // this.text = text ; // } // // /** // * Returns the fetch type as an int value (0 to 3) <br> // * @return // */ // public int getValue() { // return this.value ; // } // // /** // * Returns the fetch type as a text<br> // * e.g. : 'MERGE', 'PERSIST', etc // * @return // */ // public String getText() { // return this.text; // } // } // Path: src/test/java/org/telosys/tools/generic/model/CascadeOptionsTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; import org.telosys.tools.generic.model.enums.CascadeOption; package org.telosys.tools.generic.model; public class CascadeOptionsTest { @Test public void test0() { System.out.println("\nCascadeOptionsTest : test0 : ");
System.out.println("CascadeOption.values().length = " + CascadeOption.values().length);
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/CardinalityTest.java
// Path: src/main/java/org/telosys/tools/generic/model/enums/Cardinality.java // public enum Cardinality { // // /** // * Undefined or not managed by the model implementation // */ // UNDEFINED(0, ""), // // /** // * // */ // ONE_TO_MANY(1, "OneToMany"), // // /** // * // */ // MANY_TO_ONE(2, "ManyToOne"), // // /** // * // */ // ONE_TO_ONE(3, "OneToOne"), // // /** // * // */ // MANY_TO_MANY(4, "ManyToMany"); // // //--------------------------------------------------- // private final int value ; // private final String text ; // // private Cardinality(int value, String text) { // this.value = value ; // this.text = text ; // } // // /** // * Returns the cardinality as an int value (0 to 4) <br> // * @return // */ // public int getValue() { // return this.value ; // } // // /** // * Returns the cardinality as a text<br> // * e.g. : 'OneToMany', 'ManyToOne', 'OneToOne', 'ManyToMany' // * @return // */ // public String getText() { // return this.text; // } // // /** // * Returns true if the cardinality is "MANY_TO_ONE" or "ONE_TO_ONE" // * @return // */ // public boolean isToOne() { // if ( this == MANY_TO_ONE ) return true ; // if ( this == ONE_TO_ONE ) return true ; // return false ; // } // // /** // * Returns true if the cardinality is "ONE_TO_MANY" or "MANY_TO_MANY" // * @return // */ // public boolean isToMany() { // if ( this == ONE_TO_MANY ) return true ; // if ( this == MANY_TO_MANY ) return true ; // return false ; // } // }
import static org.junit.Assert.*; import org.junit.Test; import org.telosys.tools.generic.model.enums.Cardinality;
package org.telosys.tools.generic.model; public class CardinalityTest { @Test public void test1() { System.out.println("Cardinality test1 : ");
// Path: src/main/java/org/telosys/tools/generic/model/enums/Cardinality.java // public enum Cardinality { // // /** // * Undefined or not managed by the model implementation // */ // UNDEFINED(0, ""), // // /** // * // */ // ONE_TO_MANY(1, "OneToMany"), // // /** // * // */ // MANY_TO_ONE(2, "ManyToOne"), // // /** // * // */ // ONE_TO_ONE(3, "OneToOne"), // // /** // * // */ // MANY_TO_MANY(4, "ManyToMany"); // // //--------------------------------------------------- // private final int value ; // private final String text ; // // private Cardinality(int value, String text) { // this.value = value ; // this.text = text ; // } // // /** // * Returns the cardinality as an int value (0 to 4) <br> // * @return // */ // public int getValue() { // return this.value ; // } // // /** // * Returns the cardinality as a text<br> // * e.g. : 'OneToMany', 'ManyToOne', 'OneToOne', 'ManyToMany' // * @return // */ // public String getText() { // return this.text; // } // // /** // * Returns true if the cardinality is "MANY_TO_ONE" or "ONE_TO_ONE" // * @return // */ // public boolean isToOne() { // if ( this == MANY_TO_ONE ) return true ; // if ( this == ONE_TO_ONE ) return true ; // return false ; // } // // /** // * Returns true if the cardinality is "ONE_TO_MANY" or "MANY_TO_MANY" // * @return // */ // public boolean isToMany() { // if ( this == ONE_TO_MANY ) return true ; // if ( this == MANY_TO_MANY ) return true ; // return false ; // } // } // Path: src/test/java/org/telosys/tools/generic/model/CardinalityTest.java import static org.junit.Assert.*; import org.junit.Test; import org.telosys.tools.generic.model.enums.Cardinality; package org.telosys.tools.generic.model; public class CardinalityTest { @Test public void test1() { System.out.println("Cardinality test1 : ");
check(Cardinality.ONE_TO_MANY, 1, "OneToMany");
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/LiteralValuesProviderForJavaScriptTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import org.junit.Test; import static org.junit.Assert.assertEquals;
package org.telosys.tools.generic.model.types; public class LiteralValuesProviderForJavaScriptTest { //---------------------------------------------------------------------------------- private TypeConverter getTypeConverter() { return new TypeConverterForJavaScript() ; } private LiteralValuesProvider getLiteralValuesProvider() { return new LiteralValuesProviderForJavaScript() ; } private LanguageType getLanguageType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private LanguageType getLanguageType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); System.out.println("AttributeTypeInfo : " + attributeTypeInfo); return getLanguageType(attributeTypeInfo); } //---------------------------------------------------------------------------------- @Test public void testLiteralNull() { assertEquals("null", getLiteralValuesProvider().getLiteralNull() ); } @Test public void testLiteralValuesForBOOLEAN() {
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // Path: src/test/java/org/telosys/tools/generic/model/types/LiteralValuesProviderForJavaScriptTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import org.junit.Test; import static org.junit.Assert.assertEquals; package org.telosys.tools.generic.model.types; public class LiteralValuesProviderForJavaScriptTest { //---------------------------------------------------------------------------------- private TypeConverter getTypeConverter() { return new TypeConverterForJavaScript() ; } private LiteralValuesProvider getLiteralValuesProvider() { return new LiteralValuesProviderForJavaScript() ; } private LanguageType getLanguageType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private LanguageType getLanguageType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); System.out.println("AttributeTypeInfo : " + attributeTypeInfo); return getLanguageType(attributeTypeInfo); } //---------------------------------------------------------------------------------- @Test public void testLiteralNull() { assertEquals("null", getLiteralValuesProvider().getLiteralNull() ); } @Test public void testLiteralValuesForBOOLEAN() {
LanguageType lt = getLanguageType(NeutralType.BOOLEAN, NONE );
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/LiteralValuesProviderForPythonTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import org.junit.Test; import static org.junit.Assert.assertEquals;
package org.telosys.tools.generic.model.types; public class LiteralValuesProviderForPythonTest { //---------------------------------------------------------------------------------- private TypeConverter getTypeConverter() { return new TypeConverterForPython() ; } private LiteralValuesProvider getLiteralValuesProvider() { return new LiteralValuesProviderForPython() ; } private LanguageType getLanguageType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private LanguageType getLanguageType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); System.out.println("AttributeTypeInfo : " + attributeTypeInfo); return getLanguageType(attributeTypeInfo); } //---------------------------------------------------------------------------------- @Test public void testLiteralNull() { assertEquals("None", getLiteralValuesProvider().getLiteralNull() ); } @Test public void testLiteralValuesForBOOLEAN() {
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // Path: src/test/java/org/telosys/tools/generic/model/types/LiteralValuesProviderForPythonTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import org.junit.Test; import static org.junit.Assert.assertEquals; package org.telosys.tools.generic.model.types; public class LiteralValuesProviderForPythonTest { //---------------------------------------------------------------------------------- private TypeConverter getTypeConverter() { return new TypeConverterForPython() ; } private LiteralValuesProvider getLiteralValuesProvider() { return new LiteralValuesProviderForPython() ; } private LanguageType getLanguageType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private LanguageType getLanguageType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); System.out.println("AttributeTypeInfo : " + attributeTypeInfo); return getLanguageType(attributeTypeInfo); } //---------------------------------------------------------------------------------- @Test public void testLiteralNull() { assertEquals("None", getLiteralValuesProvider().getLiteralNull() ); } @Test public void testLiteralValuesForBOOLEAN() {
LanguageType lt = getLanguageType(NeutralType.BOOLEAN, NONE );
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForGoTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
System.out.println("AttributeTypeInfo : " + attributeTypeInfo); return getType(attributeTypeInfo); } private LanguageType getType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- ");
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForGoTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; System.out.println("AttributeTypeInfo : " + attributeTypeInfo); return getType(attributeTypeInfo); } private LanguageType getType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- ");
checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "string");
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForGoTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
return getType(attributeTypeInfo); } private LanguageType getType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "string");
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForGoTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; return getType(attributeTypeInfo); } private LanguageType getType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "string");
checkPrimitiveType( getType(NeutralType.STRING, NOT_NULL ), "string", "string");
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForGoTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
} private LanguageType getType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "string"); checkPrimitiveType( getType(NeutralType.STRING, NOT_NULL ), "string", "string");
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForGoTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; } private LanguageType getType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "string"); checkPrimitiveType( getType(NeutralType.STRING, NOT_NULL ), "string", "string");
checkPrimitiveType( getType(NeutralType.STRING, PRIMITIVE_TYPE ), "string", "string");
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForGoTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
private LanguageType getType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "string"); checkPrimitiveType( getType(NeutralType.STRING, NOT_NULL ), "string", "string"); checkPrimitiveType( getType(NeutralType.STRING, PRIMITIVE_TYPE ), "string", "string");
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForGoTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; private LanguageType getType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "string"); checkPrimitiveType( getType(NeutralType.STRING, NOT_NULL ), "string", "string"); checkPrimitiveType( getType(NeutralType.STRING, PRIMITIVE_TYPE ), "string", "string");
checkPrimitiveType( getType(NeutralType.STRING, UNSIGNED_TYPE ), "string", "string");
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForGoTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "string"); checkPrimitiveType( getType(NeutralType.STRING, NOT_NULL ), "string", "string"); checkPrimitiveType( getType(NeutralType.STRING, PRIMITIVE_TYPE ), "string", "string"); checkPrimitiveType( getType(NeutralType.STRING, UNSIGNED_TYPE ), "string", "string"); checkPrimitiveType( getType(NeutralType.STRING, PRIMITIVE_TYPE + UNSIGNED_TYPE ), "string", "string");
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForGoTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "string"); checkPrimitiveType( getType(NeutralType.STRING, NOT_NULL ), "string", "string"); checkPrimitiveType( getType(NeutralType.STRING, PRIMITIVE_TYPE ), "string", "string"); checkPrimitiveType( getType(NeutralType.STRING, UNSIGNED_TYPE ), "string", "string"); checkPrimitiveType( getType(NeutralType.STRING, PRIMITIVE_TYPE + UNSIGNED_TYPE ), "string", "string");
checkPrimitiveType( getType(NeutralType.STRING, OBJECT_TYPE), "string", "string" );
telosys-tools-bricks/telosys-tools-generic-model
src/main/java/org/telosys/tools/generic/model/Attribute.java
// Path: src/main/java/org/telosys/tools/generic/model/enums/BooleanValue.java // public enum BooleanValue { // // /** // * Undefined or not managed by the model implementation // */ // UNDEFINED(-1, "undefined"), // // /** // * // */ // FALSE(0, "false"), // // /** // * // */ // TRUE(1, "true"); // // //--------------------------------------------------- // private final int value ; // private final String text ; // // private BooleanValue(int value, String text) { // this.value = value ; // this.text = text ; // } // // /** // * Returns the value as an int <br> // * @return // */ // public int getValue() { // return this.value ; // } // // /** // * Returns the value as a text<br> // * e.g. : 'undefined', 'true', 'false' // * @return // */ // public String getText() { // return this.text; // } // // } // // Path: src/main/java/org/telosys/tools/generic/model/enums/DateType.java // public enum DateType { // // /** // * Undefined or not managed by the model implementation // */ // UNDEFINED(0), // // /** // * Date information only (no time) // */ // DATE_ONLY(1), // // /** // * Time information only (no date) // */ // TIME_ONLY(2), // // /** // * Date and time information // */ // DATE_AND_TIME(3); // // //--------------------------------------------------- // private int value ; // // private DateType(int value) { // this.value = value ; // } // // public int getValue() { // return this.value ; // } // } // // Path: src/main/java/org/telosys/tools/generic/model/enums/GeneratedValueStrategy.java // public enum GeneratedValueStrategy { // UNDEFINED(0, ""), // AUTO(1, "AUTO"), // IDENTITY(2, "IDENTITY"), // SEQUENCE(3, "SEQUENCE"), // TABLE(4, "TABLE"); // // //--------------------------------------------------- // private final int value ; // private final String text ; // // private GeneratedValueStrategy(int value, String text) { // this.value = value ; // this.text = text ; // } // // /** // * Returns the strategy as an int value (0 to 4) <br> // * @return // */ // public int getValue() { // return this.value ; // } // // /** // * Returns the strategy as a text<br> // * e.g. : 'AUTO' or 'IDENTITY' or 'SEQUENCE' or 'TABLE' // * @return // */ // public String getText() { // return this.text; // } // // }
import java.math.BigDecimal; import java.util.List; import org.telosys.tools.generic.model.enums.BooleanValue; import org.telosys.tools.generic.model.enums.DateType; import org.telosys.tools.generic.model.enums.GeneratedValueStrategy;
* @return * @since v 3.0.0 */ public boolean isUsedInLinks(); /** * Returns true if the attribute is used as FK (or "pseudo FK") in one or more selected links of its entity * @return * @since v 3.0.0 */ public boolean isUsedInSelectedLinks(); // /** // * Returns all the tags defined in the attribute // * @return // * @since v 3.3.0 // */ // public Map<String, String> getTagsMap(); /** * Returns all the tags defined in the link * @return * @since v 3.4.0 */ public TagContainer getTagContainer(); // v 3.4.0 /** * Returns the 'insertable' flag values * @return * @since v 3.3.0 */
// Path: src/main/java/org/telosys/tools/generic/model/enums/BooleanValue.java // public enum BooleanValue { // // /** // * Undefined or not managed by the model implementation // */ // UNDEFINED(-1, "undefined"), // // /** // * // */ // FALSE(0, "false"), // // /** // * // */ // TRUE(1, "true"); // // //--------------------------------------------------- // private final int value ; // private final String text ; // // private BooleanValue(int value, String text) { // this.value = value ; // this.text = text ; // } // // /** // * Returns the value as an int <br> // * @return // */ // public int getValue() { // return this.value ; // } // // /** // * Returns the value as a text<br> // * e.g. : 'undefined', 'true', 'false' // * @return // */ // public String getText() { // return this.text; // } // // } // // Path: src/main/java/org/telosys/tools/generic/model/enums/DateType.java // public enum DateType { // // /** // * Undefined or not managed by the model implementation // */ // UNDEFINED(0), // // /** // * Date information only (no time) // */ // DATE_ONLY(1), // // /** // * Time information only (no date) // */ // TIME_ONLY(2), // // /** // * Date and time information // */ // DATE_AND_TIME(3); // // //--------------------------------------------------- // private int value ; // // private DateType(int value) { // this.value = value ; // } // // public int getValue() { // return this.value ; // } // } // // Path: src/main/java/org/telosys/tools/generic/model/enums/GeneratedValueStrategy.java // public enum GeneratedValueStrategy { // UNDEFINED(0, ""), // AUTO(1, "AUTO"), // IDENTITY(2, "IDENTITY"), // SEQUENCE(3, "SEQUENCE"), // TABLE(4, "TABLE"); // // //--------------------------------------------------- // private final int value ; // private final String text ; // // private GeneratedValueStrategy(int value, String text) { // this.value = value ; // this.text = text ; // } // // /** // * Returns the strategy as an int value (0 to 4) <br> // * @return // */ // public int getValue() { // return this.value ; // } // // /** // * Returns the strategy as a text<br> // * e.g. : 'AUTO' or 'IDENTITY' or 'SEQUENCE' or 'TABLE' // * @return // */ // public String getText() { // return this.text; // } // // } // Path: src/main/java/org/telosys/tools/generic/model/Attribute.java import java.math.BigDecimal; import java.util.List; import org.telosys.tools.generic.model.enums.BooleanValue; import org.telosys.tools.generic.model.enums.DateType; import org.telosys.tools.generic.model.enums.GeneratedValueStrategy; * @return * @since v 3.0.0 */ public boolean isUsedInLinks(); /** * Returns true if the attribute is used as FK (or "pseudo FK") in one or more selected links of its entity * @return * @since v 3.0.0 */ public boolean isUsedInSelectedLinks(); // /** // * Returns all the tags defined in the attribute // * @return // * @since v 3.3.0 // */ // public Map<String, String> getTagsMap(); /** * Returns all the tags defined in the link * @return * @since v 3.4.0 */ public TagContainer getTagContainer(); // v 3.4.0 /** * Returns the 'insertable' flag values * @return * @since v 3.3.0 */
public BooleanValue getInsertable() ; // v 3.3.0
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/LiteralValuesProviderForCSharpTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import org.junit.Test; import static org.junit.Assert.assertEquals;
package org.telosys.tools.generic.model.types; public class LiteralValuesProviderForCSharpTest { //---------------------------------------------------------------------------------- private TypeConverter getTypeConverter() { return new TypeConverterForCSharp() ; } private LiteralValuesProvider getLiteralValuesProvider() { return new LiteralValuesProviderForCSharp() ; } private LanguageType getLanguageType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private LanguageType getLanguageType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); System.out.println("AttributeTypeInfo : " + attributeTypeInfo); return getLanguageType(attributeTypeInfo); } //---------------------------------------------------------------------------------- @Test public void testLiteralNull() { assertEquals("null", getLiteralValuesProvider().getLiteralNull() ); } @Test public void testLiteralValuesForBOOLEAN() {
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // Path: src/test/java/org/telosys/tools/generic/model/types/LiteralValuesProviderForCSharpTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import org.junit.Test; import static org.junit.Assert.assertEquals; package org.telosys.tools.generic.model.types; public class LiteralValuesProviderForCSharpTest { //---------------------------------------------------------------------------------- private TypeConverter getTypeConverter() { return new TypeConverterForCSharp() ; } private LiteralValuesProvider getLiteralValuesProvider() { return new LiteralValuesProviderForCSharp() ; } private LanguageType getLanguageType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private LanguageType getLanguageType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); System.out.println("AttributeTypeInfo : " + attributeTypeInfo); return getLanguageType(attributeTypeInfo); } //---------------------------------------------------------------------------------- @Test public void testLiteralNull() { assertEquals("null", getLiteralValuesProvider().getLiteralNull() ); } @Test public void testLiteralValuesForBOOLEAN() {
LanguageType lt = getLanguageType(NeutralType.BOOLEAN, NONE );
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/LiteralValuesProviderForGoTest_BAK.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import org.junit.Test; import static org.junit.Assert.assertEquals;
package org.telosys.tools.generic.model.types; public class LiteralValuesProviderForGoTest_BAK { //---------------------------------------------------------------------------------- private TypeConverter getTypeConverter() { return new TypeConverterForGo() ; } private LiteralValuesProvider getLiteralValuesProvider() { return new LiteralValuesProviderForGo() ; } private LanguageType getLanguageType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private LanguageType getLanguageType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); System.out.println("AttributeTypeInfo : " + attributeTypeInfo); return getLanguageType(attributeTypeInfo); } //---------------------------------------------------------------------------------- @Test public void testLiteralNull() { assertEquals("nil", getLiteralValuesProvider().getLiteralNull() ); } @Test public void testLiteralBooleanValues() {
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // Path: src/test/java/org/telosys/tools/generic/model/types/LiteralValuesProviderForGoTest_BAK.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import org.junit.Test; import static org.junit.Assert.assertEquals; package org.telosys.tools.generic.model.types; public class LiteralValuesProviderForGoTest_BAK { //---------------------------------------------------------------------------------- private TypeConverter getTypeConverter() { return new TypeConverterForGo() ; } private LiteralValuesProvider getLiteralValuesProvider() { return new LiteralValuesProviderForGo() ; } private LanguageType getLanguageType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private LanguageType getLanguageType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); System.out.println("AttributeTypeInfo : " + attributeTypeInfo); return getLanguageType(attributeTypeInfo); } //---------------------------------------------------------------------------------- @Test public void testLiteralNull() { assertEquals("nil", getLiteralValuesProvider().getLiteralNull() ); } @Test public void testLiteralBooleanValues() {
LanguageType lt = getLanguageType(NeutralType.BOOLEAN, NONE );
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/LiteralValuesProviderForPHPTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import org.junit.Test; import static org.junit.Assert.assertEquals;
package org.telosys.tools.generic.model.types; public class LiteralValuesProviderForPHPTest { //---------------------------------------------------------------------------------- private TypeConverter getTypeConverter() { return new TypeConverterForPHP() ; } private LiteralValuesProvider getLiteralValuesProvider() { return new LiteralValuesProviderForPHP() ; } private LanguageType getLanguageType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private LanguageType getLanguageType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); System.out.println("AttributeTypeInfo : " + attributeTypeInfo); return getLanguageType(attributeTypeInfo); } //---------------------------------------------------------------------------------- @Test public void testLiteralNull() { assertEquals("null", getLiteralValuesProvider().getLiteralNull() ); } @Test public void testLiteralValuesForBOOLEAN() {
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // Path: src/test/java/org/telosys/tools/generic/model/types/LiteralValuesProviderForPHPTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import org.junit.Test; import static org.junit.Assert.assertEquals; package org.telosys.tools.generic.model.types; public class LiteralValuesProviderForPHPTest { //---------------------------------------------------------------------------------- private TypeConverter getTypeConverter() { return new TypeConverterForPHP() ; } private LiteralValuesProvider getLiteralValuesProvider() { return new LiteralValuesProviderForPHP() ; } private LanguageType getLanguageType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private LanguageType getLanguageType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); System.out.println("AttributeTypeInfo : " + attributeTypeInfo); return getLanguageType(attributeTypeInfo); } //---------------------------------------------------------------------------------- @Test public void testLiteralNull() { assertEquals("null", getLiteralValuesProvider().getLiteralNull() ); } @Test public void testLiteralValuesForBOOLEAN() {
LanguageType lt = getLanguageType(NeutralType.BOOLEAN, NONE );
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/AttributeTypeInfoTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public class AttributeTypeInfo { // // public static final int NONE = 0 ; // public static final int NOT_NULL = 1 ; // public static final int PRIMITIVE_TYPE = 2 ; // public static final int OBJECT_TYPE = 4 ; // public static final int UNSIGNED_TYPE = 8 ; // //public static final int SQL_TYPE = 16 ; // // private final String neutralType ; // // private final boolean notNull ; // // private final boolean primitiveTypeExpected ; // private final boolean objectTypeExpected ; // // private final boolean unsignedTypeExpected ; // //private final boolean sqlTypeExpected ; // Removed in v 3.3.0 // // /** // * Constructor // * @param neutralType // * @param typeInfo // */ // public AttributeTypeInfo(String neutralType, int typeInfo) { // super(); // this.neutralType = neutralType; // // this.notNull = ( typeInfo & NOT_NULL ) != 0 ; // this.primitiveTypeExpected = ( typeInfo & PRIMITIVE_TYPE ) != 0 ; // this.objectTypeExpected = ( typeInfo & OBJECT_TYPE ) != 0 ; // this.unsignedTypeExpected = ( typeInfo & UNSIGNED_TYPE ) != 0 ; // //this.sqlTypeExpected = ( typeInfo & SQL_TYPE ) != 0 ; // Removed in v 3.3.0 // } // // public AttributeTypeInfo(Attribute attribute) { // super(); // this.neutralType = attribute.getNeutralType(); // this.notNull = attribute.isNotNull(); // this.primitiveTypeExpected = attribute.isPrimitiveTypeExpected(); // this.objectTypeExpected = attribute.isObjectTypeExpected(); // this.unsignedTypeExpected = attribute.isUnsignedTypeExpected(); // //this.sqlTypeExpected = attribute.isSqlTypeExpected(); // Removed in v 3.3.0 // } // // public String getNeutralType() { // return neutralType; // } // // public boolean isNotNull() { // return notNull; // } // // public boolean isPrimitiveTypeExpected() { // return primitiveTypeExpected; // } // // public boolean isObjectTypeExpected() { // return objectTypeExpected; // } // // public boolean isUnsignedTypeExpected() { // return unsignedTypeExpected; // } // // // public boolean isSqlTypeExpected() { // Removed in v 3.3.0 // // return sqlTypeExpected; // // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("'" + neutralType + "' " ); // // if ( notNull || primitiveTypeExpected || objectTypeExpected || unsignedTypeExpected || sqlTypeExpected ) { // if ( notNull || primitiveTypeExpected || objectTypeExpected || unsignedTypeExpected ) { // sb.append("( " ); // if ( notNull ) { // sb.append("notNull " ); // } // if ( primitiveTypeExpected ) { // sb.append("primitiveType " ); // } // if ( unsignedTypeExpected ) { // sb.append("unsignedType " ); // } // if ( objectTypeExpected ) { // sb.append("objectType " ); // } // // if ( sqlTypeExpected ) { // Removed in v 3.3.0 // // sb.append("sqlType " ); // // } // sb.append(")" ); // } // return sb.toString(); // } // // }
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.*; import org.junit.Test;
package org.telosys.tools.generic.model.types; public class AttributeTypeInfoTest { @Test public void test1() {
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public class AttributeTypeInfo { // // public static final int NONE = 0 ; // public static final int NOT_NULL = 1 ; // public static final int PRIMITIVE_TYPE = 2 ; // public static final int OBJECT_TYPE = 4 ; // public static final int UNSIGNED_TYPE = 8 ; // //public static final int SQL_TYPE = 16 ; // // private final String neutralType ; // // private final boolean notNull ; // // private final boolean primitiveTypeExpected ; // private final boolean objectTypeExpected ; // // private final boolean unsignedTypeExpected ; // //private final boolean sqlTypeExpected ; // Removed in v 3.3.0 // // /** // * Constructor // * @param neutralType // * @param typeInfo // */ // public AttributeTypeInfo(String neutralType, int typeInfo) { // super(); // this.neutralType = neutralType; // // this.notNull = ( typeInfo & NOT_NULL ) != 0 ; // this.primitiveTypeExpected = ( typeInfo & PRIMITIVE_TYPE ) != 0 ; // this.objectTypeExpected = ( typeInfo & OBJECT_TYPE ) != 0 ; // this.unsignedTypeExpected = ( typeInfo & UNSIGNED_TYPE ) != 0 ; // //this.sqlTypeExpected = ( typeInfo & SQL_TYPE ) != 0 ; // Removed in v 3.3.0 // } // // public AttributeTypeInfo(Attribute attribute) { // super(); // this.neutralType = attribute.getNeutralType(); // this.notNull = attribute.isNotNull(); // this.primitiveTypeExpected = attribute.isPrimitiveTypeExpected(); // this.objectTypeExpected = attribute.isObjectTypeExpected(); // this.unsignedTypeExpected = attribute.isUnsignedTypeExpected(); // //this.sqlTypeExpected = attribute.isSqlTypeExpected(); // Removed in v 3.3.0 // } // // public String getNeutralType() { // return neutralType; // } // // public boolean isNotNull() { // return notNull; // } // // public boolean isPrimitiveTypeExpected() { // return primitiveTypeExpected; // } // // public boolean isObjectTypeExpected() { // return objectTypeExpected; // } // // public boolean isUnsignedTypeExpected() { // return unsignedTypeExpected; // } // // // public boolean isSqlTypeExpected() { // Removed in v 3.3.0 // // return sqlTypeExpected; // // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("'" + neutralType + "' " ); // // if ( notNull || primitiveTypeExpected || objectTypeExpected || unsignedTypeExpected || sqlTypeExpected ) { // if ( notNull || primitiveTypeExpected || objectTypeExpected || unsignedTypeExpected ) { // sb.append("( " ); // if ( notNull ) { // sb.append("notNull " ); // } // if ( primitiveTypeExpected ) { // sb.append("primitiveType " ); // } // if ( unsignedTypeExpected ) { // sb.append("unsignedType " ); // } // if ( objectTypeExpected ) { // sb.append("objectType " ); // } // // if ( sqlTypeExpected ) { // Removed in v 3.3.0 // // sb.append("sqlType " ); // // } // sb.append(")" ); // } // return sb.toString(); // } // // } // Path: src/test/java/org/telosys/tools/generic/model/types/AttributeTypeInfoTest.java import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.*; import org.junit.Test; package org.telosys.tools.generic.model.types; public class AttributeTypeInfoTest { @Test public void test1() {
AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(NeutralType.STRING, NONE);
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForCSharpTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
LanguageType lt = getTypeConverter().getType(typeInfo); System.out.println( typeInfo + " --> " + lt ); return lt ; } private LanguageType getType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); return getType(attributeTypeInfo); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- ");
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForCSharpTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; LanguageType lt = getTypeConverter().getType(typeInfo); System.out.println( typeInfo + " --> " + lt ); return lt ; } private LanguageType getType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); return getType(attributeTypeInfo); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- ");
checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "System.String");
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForCSharpTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
System.out.println( typeInfo + " --> " + lt ); return lt ; } private LanguageType getType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); return getType(attributeTypeInfo); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "System.String");
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForCSharpTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; System.out.println( typeInfo + " --> " + lt ); return lt ; } private LanguageType getType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); return getType(attributeTypeInfo); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "System.String");
checkPrimitiveType( getType(NeutralType.STRING, NOT_NULL ), "string", "System.String");
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForCSharpTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
return lt ; } private LanguageType getType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); return getType(attributeTypeInfo); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "System.String"); checkPrimitiveType( getType(NeutralType.STRING, NOT_NULL ), "string", "System.String");
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForCSharpTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; return lt ; } private LanguageType getType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); return getType(attributeTypeInfo); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "System.String"); checkPrimitiveType( getType(NeutralType.STRING, NOT_NULL ), "string", "System.String");
checkPrimitiveType( getType(NeutralType.STRING, PRIMITIVE_TYPE ), "string", "System.String");
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForCSharpTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
} private LanguageType getType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); return getType(attributeTypeInfo); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "System.String"); checkPrimitiveType( getType(NeutralType.STRING, NOT_NULL ), "string", "System.String"); checkPrimitiveType( getType(NeutralType.STRING, PRIMITIVE_TYPE ), "string", "System.String");
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForCSharpTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; } private LanguageType getType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); return getType(attributeTypeInfo); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "System.String"); checkPrimitiveType( getType(NeutralType.STRING, NOT_NULL ), "string", "System.String"); checkPrimitiveType( getType(NeutralType.STRING, PRIMITIVE_TYPE ), "string", "System.String");
checkPrimitiveType( getType(NeutralType.STRING, UNSIGNED_TYPE ), "string", "System.String");
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForCSharpTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
return getType(attributeTypeInfo); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "System.String"); checkPrimitiveType( getType(NeutralType.STRING, NOT_NULL ), "string", "System.String"); checkPrimitiveType( getType(NeutralType.STRING, PRIMITIVE_TYPE ), "string", "System.String"); checkPrimitiveType( getType(NeutralType.STRING, UNSIGNED_TYPE ), "string", "System.String"); checkPrimitiveType( getType(NeutralType.STRING, PRIMITIVE_TYPE + UNSIGNED_TYPE ), "string", "System.String"); // checkPrimitiveType( getType(NeutralType.STRING, SQL_TYPE), "string", "System.String" );
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForCSharpTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; return getType(attributeTypeInfo); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertEquals(simpleType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); checkPrimitiveType( getType(NeutralType.STRING, NONE ), "string", "System.String"); checkPrimitiveType( getType(NeutralType.STRING, NOT_NULL ), "string", "System.String"); checkPrimitiveType( getType(NeutralType.STRING, PRIMITIVE_TYPE ), "string", "System.String"); checkPrimitiveType( getType(NeutralType.STRING, UNSIGNED_TYPE ), "string", "System.String"); checkPrimitiveType( getType(NeutralType.STRING, PRIMITIVE_TYPE + UNSIGNED_TYPE ), "string", "System.String"); // checkPrimitiveType( getType(NeutralType.STRING, SQL_TYPE), "string", "System.String" );
checkObjectType( getType(NeutralType.STRING, OBJECT_TYPE), "String", "System.String" );
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForJavaTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import java.math.BigDecimal; import org.junit.Test; import org.telosys.tools.commons.JavaTypeUtil; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
assertTrue ( lt.isPrimitiveType() ) ; } else { assertFalse ( lt.isPrimitiveType() ) ; } } private void checkLocalDate( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE), lt.getSimpleType() ); assertEquals(LOCAL_DATE, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_TIME), lt.getSimpleType() ); assertEquals(LOCAL_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalDateTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE_TIME), lt.getSimpleType() ); assertEquals(LOCAL_DATE_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } @Test public void testString() { System.out.println("--- "); TypeConverter tc = new TypeConverterForJava() ;
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForJavaTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import java.math.BigDecimal; import org.junit.Test; import org.telosys.tools.commons.JavaTypeUtil; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; assertTrue ( lt.isPrimitiveType() ) ; } else { assertFalse ( lt.isPrimitiveType() ) ; } } private void checkLocalDate( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE), lt.getSimpleType() ); assertEquals(LOCAL_DATE, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_TIME), lt.getSimpleType() ); assertEquals(LOCAL_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalDateTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE_TIME), lt.getSimpleType() ); assertEquals(LOCAL_DATE_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } @Test public void testString() { System.out.println("--- "); TypeConverter tc = new TypeConverterForJava() ;
check( getType(tc, NeutralType.STRING, NONE ), String.class);
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForJavaTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import java.math.BigDecimal; import org.junit.Test; import org.telosys.tools.commons.JavaTypeUtil; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
} else { assertFalse ( lt.isPrimitiveType() ) ; } } private void checkLocalDate( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE), lt.getSimpleType() ); assertEquals(LOCAL_DATE, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_TIME), lt.getSimpleType() ); assertEquals(LOCAL_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalDateTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE_TIME), lt.getSimpleType() ); assertEquals(LOCAL_DATE_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } @Test public void testString() { System.out.println("--- "); TypeConverter tc = new TypeConverterForJava() ; check( getType(tc, NeutralType.STRING, NONE ), String.class);
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForJavaTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import java.math.BigDecimal; import org.junit.Test; import org.telosys.tools.commons.JavaTypeUtil; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; } else { assertFalse ( lt.isPrimitiveType() ) ; } } private void checkLocalDate( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE), lt.getSimpleType() ); assertEquals(LOCAL_DATE, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_TIME), lt.getSimpleType() ); assertEquals(LOCAL_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalDateTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE_TIME), lt.getSimpleType() ); assertEquals(LOCAL_DATE_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } @Test public void testString() { System.out.println("--- "); TypeConverter tc = new TypeConverterForJava() ; check( getType(tc, NeutralType.STRING, NONE ), String.class);
check( getType(tc, NeutralType.STRING, NOT_NULL ), String.class);
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForJavaTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import java.math.BigDecimal; import org.junit.Test; import org.telosys.tools.commons.JavaTypeUtil; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
assertFalse ( lt.isPrimitiveType() ) ; } } private void checkLocalDate( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE), lt.getSimpleType() ); assertEquals(LOCAL_DATE, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_TIME), lt.getSimpleType() ); assertEquals(LOCAL_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalDateTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE_TIME), lt.getSimpleType() ); assertEquals(LOCAL_DATE_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } @Test public void testString() { System.out.println("--- "); TypeConverter tc = new TypeConverterForJava() ; check( getType(tc, NeutralType.STRING, NONE ), String.class); check( getType(tc, NeutralType.STRING, NOT_NULL ), String.class);
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForJavaTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import java.math.BigDecimal; import org.junit.Test; import org.telosys.tools.commons.JavaTypeUtil; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; assertFalse ( lt.isPrimitiveType() ) ; } } private void checkLocalDate( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE), lt.getSimpleType() ); assertEquals(LOCAL_DATE, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_TIME), lt.getSimpleType() ); assertEquals(LOCAL_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalDateTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE_TIME), lt.getSimpleType() ); assertEquals(LOCAL_DATE_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } @Test public void testString() { System.out.println("--- "); TypeConverter tc = new TypeConverterForJava() ; check( getType(tc, NeutralType.STRING, NONE ), String.class); check( getType(tc, NeutralType.STRING, NOT_NULL ), String.class);
check( getType(tc, NeutralType.STRING, PRIMITIVE_TYPE ), String.class);
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForJavaTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import java.math.BigDecimal; import org.junit.Test; import org.telosys.tools.commons.JavaTypeUtil; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
} } private void checkLocalDate( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE), lt.getSimpleType() ); assertEquals(LOCAL_DATE, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_TIME), lt.getSimpleType() ); assertEquals(LOCAL_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalDateTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE_TIME), lt.getSimpleType() ); assertEquals(LOCAL_DATE_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } @Test public void testString() { System.out.println("--- "); TypeConverter tc = new TypeConverterForJava() ; check( getType(tc, NeutralType.STRING, NONE ), String.class); check( getType(tc, NeutralType.STRING, NOT_NULL ), String.class); check( getType(tc, NeutralType.STRING, PRIMITIVE_TYPE ), String.class);
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForJavaTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import java.math.BigDecimal; import org.junit.Test; import org.telosys.tools.commons.JavaTypeUtil; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; } } private void checkLocalDate( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE), lt.getSimpleType() ); assertEquals(LOCAL_DATE, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_TIME), lt.getSimpleType() ); assertEquals(LOCAL_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalDateTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE_TIME), lt.getSimpleType() ); assertEquals(LOCAL_DATE_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } @Test public void testString() { System.out.println("--- "); TypeConverter tc = new TypeConverterForJava() ; check( getType(tc, NeutralType.STRING, NONE ), String.class); check( getType(tc, NeutralType.STRING, NOT_NULL ), String.class); check( getType(tc, NeutralType.STRING, PRIMITIVE_TYPE ), String.class);
check( getType(tc, NeutralType.STRING, UNSIGNED_TYPE ), String.class);
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForJavaTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import java.math.BigDecimal; import org.junit.Test; import org.telosys.tools.commons.JavaTypeUtil; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE), lt.getSimpleType() ); assertEquals(LOCAL_DATE, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_TIME), lt.getSimpleType() ); assertEquals(LOCAL_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalDateTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE_TIME), lt.getSimpleType() ); assertEquals(LOCAL_DATE_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } @Test public void testString() { System.out.println("--- "); TypeConverter tc = new TypeConverterForJava() ; check( getType(tc, NeutralType.STRING, NONE ), String.class); check( getType(tc, NeutralType.STRING, NOT_NULL ), String.class); check( getType(tc, NeutralType.STRING, PRIMITIVE_TYPE ), String.class); check( getType(tc, NeutralType.STRING, UNSIGNED_TYPE ), String.class); check( getType(tc, NeutralType.STRING, PRIMITIVE_TYPE + UNSIGNED_TYPE ), String.class);
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForJavaTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import java.math.BigDecimal; import org.junit.Test; import org.telosys.tools.commons.JavaTypeUtil; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE), lt.getSimpleType() ); assertEquals(LOCAL_DATE, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_TIME), lt.getSimpleType() ); assertEquals(LOCAL_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } private void checkLocalDateTime( LanguageType lt ) { assertNotNull(lt); assertEquals(JavaTypeUtil.shortType(LOCAL_DATE_TIME), lt.getSimpleType() ); assertEquals(LOCAL_DATE_TIME, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; } @Test public void testString() { System.out.println("--- "); TypeConverter tc = new TypeConverterForJava() ; check( getType(tc, NeutralType.STRING, NONE ), String.class); check( getType(tc, NeutralType.STRING, NOT_NULL ), String.class); check( getType(tc, NeutralType.STRING, PRIMITIVE_TYPE ), String.class); check( getType(tc, NeutralType.STRING, UNSIGNED_TYPE ), String.class); check( getType(tc, NeutralType.STRING, PRIMITIVE_TYPE + UNSIGNED_TYPE ), String.class);
check( getType(tc, NeutralType.STRING, OBJECT_TYPE), String.class);
telosys-tools-bricks/telosys-tools-generic-model
src/main/java/org/telosys/tools/generic/model/Model.java
// Path: src/main/java/org/telosys/tools/generic/model/enums/ModelType.java // public enum ModelType { // // /** // * Model created from a SQL Database Schema (Telosys Tools Database Repository) // */ // DATABASE_SCHEMA, // // /** // * Model created by using the "Telosys Tools DSL" // */ // DOMAIN_SPECIFIC_LANGUAGE, // // /** // * Model created by Java classes introspection // */ // JAVA_CLASSES, // // /** // * Other type (specific model provided by an other tool) // */ // OTHER // }
import java.util.*; import org.telosys.tools.generic.model.enums.ModelType;
/** * Copyright (C) 2008-2017 Telosys project org. ( http://www.telosys.org/ ) * * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3.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.gnu.org/licenses/lgpl.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.telosys.tools.generic.model; /** * This interface describe an abstract model that must be implemented * by each concrete model * * @author Laurent Guerin * @since 3.0.0 */ public interface Model { /** * Returns the model name <br> * This information is MANDATORY, it must be provided by all models implementations <br> * It cannot be null or void * * @return */ public String getName() ; /** * Returns the model folder name if it exists for the type of model<br> * For example 'xxx_model' for model 'xxx' or '' (void) for a 'db-model' <br> * This information is MANDATORY, it must be provided by all models implementations <br> * It cannot be null, but can be void if not applicable * @return */ public String getFolderName() ; /** * Returns the Telosys model type <br> * This information is MANDATORY, it must be provided by all models implementations <br> * It cannot be null or void * * @return */
// Path: src/main/java/org/telosys/tools/generic/model/enums/ModelType.java // public enum ModelType { // // /** // * Model created from a SQL Database Schema (Telosys Tools Database Repository) // */ // DATABASE_SCHEMA, // // /** // * Model created by using the "Telosys Tools DSL" // */ // DOMAIN_SPECIFIC_LANGUAGE, // // /** // * Model created by Java classes introspection // */ // JAVA_CLASSES, // // /** // * Other type (specific model provided by an other tool) // */ // OTHER // } // Path: src/main/java/org/telosys/tools/generic/model/Model.java import java.util.*; import org.telosys.tools.generic.model.enums.ModelType; /** * Copyright (C) 2008-2017 Telosys project org. ( http://www.telosys.org/ ) * * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3.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.gnu.org/licenses/lgpl.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.telosys.tools.generic.model; /** * This interface describe an abstract model that must be implemented * by each concrete model * * @author Laurent Guerin * @since 3.0.0 */ public interface Model { /** * Returns the model name <br> * This information is MANDATORY, it must be provided by all models implementations <br> * It cannot be null or void * * @return */ public String getName() ; /** * Returns the model folder name if it exists for the type of model<br> * For example 'xxx_model' for model 'xxx' or '' (void) for a 'db-model' <br> * This information is MANDATORY, it must be provided by all models implementations <br> * It cannot be null, but can be void if not applicable * @return */ public String getFolderName() ; /** * Returns the Telosys model type <br> * This information is MANDATORY, it must be provided by all models implementations <br> * It cannot be null or void * * @return */
public ModelType getType() ;
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForTypeScriptTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
} private void checkTimeObjectType(TypeConverter tc, int typeInfo ) { checkObjectType( getType(tc, NeutralType.TIME, typeInfo ), "Date", "Date"); } private void checkTimestampObjectType(TypeConverter tc, int typeInfo ) { checkObjectType( getType(tc, NeutralType.TIMESTAMP, typeInfo ), "Date", "Date"); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(fullType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); TypeConverter tc = getTypeConverter() ; // Primitive type expected
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForTypeScriptTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; } private void checkTimeObjectType(TypeConverter tc, int typeInfo ) { checkObjectType( getType(tc, NeutralType.TIME, typeInfo ), "Date", "Date"); } private void checkTimestampObjectType(TypeConverter tc, int typeInfo ) { checkObjectType( getType(tc, NeutralType.TIMESTAMP, typeInfo ), "Date", "Date"); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(fullType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); TypeConverter tc = getTypeConverter() ; // Primitive type expected
checkStringPrimitiveType(tc, NONE);
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForTypeScriptTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
private void checkTimeObjectType(TypeConverter tc, int typeInfo ) { checkObjectType( getType(tc, NeutralType.TIME, typeInfo ), "Date", "Date"); } private void checkTimestampObjectType(TypeConverter tc, int typeInfo ) { checkObjectType( getType(tc, NeutralType.TIMESTAMP, typeInfo ), "Date", "Date"); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(fullType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); TypeConverter tc = getTypeConverter() ; // Primitive type expected checkStringPrimitiveType(tc, NONE);
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForTypeScriptTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; private void checkTimeObjectType(TypeConverter tc, int typeInfo ) { checkObjectType( getType(tc, NeutralType.TIME, typeInfo ), "Date", "Date"); } private void checkTimestampObjectType(TypeConverter tc, int typeInfo ) { checkObjectType( getType(tc, NeutralType.TIMESTAMP, typeInfo ), "Date", "Date"); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(fullType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); TypeConverter tc = getTypeConverter() ; // Primitive type expected checkStringPrimitiveType(tc, NONE);
checkStringPrimitiveType(tc, NOT_NULL);
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForTypeScriptTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
checkObjectType( getType(tc, NeutralType.TIME, typeInfo ), "Date", "Date"); } private void checkTimestampObjectType(TypeConverter tc, int typeInfo ) { checkObjectType( getType(tc, NeutralType.TIMESTAMP, typeInfo ), "Date", "Date"); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(fullType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); TypeConverter tc = getTypeConverter() ; // Primitive type expected checkStringPrimitiveType(tc, NONE); checkStringPrimitiveType(tc, NOT_NULL);
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForTypeScriptTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; checkObjectType( getType(tc, NeutralType.TIME, typeInfo ), "Date", "Date"); } private void checkTimestampObjectType(TypeConverter tc, int typeInfo ) { checkObjectType( getType(tc, NeutralType.TIMESTAMP, typeInfo ), "Date", "Date"); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(fullType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); TypeConverter tc = getTypeConverter() ; // Primitive type expected checkStringPrimitiveType(tc, NONE); checkStringPrimitiveType(tc, NOT_NULL);
checkStringPrimitiveType(tc, PRIMITIVE_TYPE);
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForTypeScriptTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
} private void checkTimestampObjectType(TypeConverter tc, int typeInfo ) { checkObjectType( getType(tc, NeutralType.TIMESTAMP, typeInfo ), "Date", "Date"); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(fullType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); TypeConverter tc = getTypeConverter() ; // Primitive type expected checkStringPrimitiveType(tc, NONE); checkStringPrimitiveType(tc, NOT_NULL); checkStringPrimitiveType(tc, PRIMITIVE_TYPE);
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForTypeScriptTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; } private void checkTimestampObjectType(TypeConverter tc, int typeInfo ) { checkObjectType( getType(tc, NeutralType.TIMESTAMP, typeInfo ), "Date", "Date"); } private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(fullType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); TypeConverter tc = getTypeConverter() ; // Primitive type expected checkStringPrimitiveType(tc, NONE); checkStringPrimitiveType(tc, NOT_NULL); checkStringPrimitiveType(tc, PRIMITIVE_TYPE);
checkStringPrimitiveType(tc, UNSIGNED_TYPE);
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/TypeConverterForTypeScriptTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue;
private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(fullType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); TypeConverter tc = getTypeConverter() ; // Primitive type expected checkStringPrimitiveType(tc, NONE); checkStringPrimitiveType(tc, NOT_NULL); checkStringPrimitiveType(tc, PRIMITIVE_TYPE); checkStringPrimitiveType(tc, UNSIGNED_TYPE); checkStringPrimitiveType(tc, PRIMITIVE_TYPE + UNSIGNED_TYPE); // checkStringPrimitiveType(tc, SQL_TYPE); // checkStringPrimitiveType(tc, NOT_NULL + SQL_TYPE);
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NOT_NULL = 1 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int OBJECT_TYPE = 4 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int PRIMITIVE_TYPE = 2 ; // // Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int UNSIGNED_TYPE = 8 ; // Path: src/test/java/org/telosys/tools/generic/model/types/TypeConverterForTypeScriptTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NOT_NULL; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.OBJECT_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.PRIMITIVE_TYPE; import static org.telosys.tools.generic.model.types.AttributeTypeInfo.UNSIGNED_TYPE; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; private void checkPrimitiveType( LanguageType lt, String primitiveType, String wrapperType) { assertNotNull(lt); assertEquals(primitiveType, lt.getSimpleType() ); assertEquals(primitiveType, lt.getFullType() ); assertTrue ( lt.isPrimitiveType() ) ; assertEquals(wrapperType, lt.getWrapperType() ); } private void checkObjectType( LanguageType lt, String simpleType, String fullType) { assertNotNull(lt); assertEquals(simpleType, lt.getSimpleType() ); assertEquals(fullType, lt.getFullType() ); assertFalse ( lt.isPrimitiveType() ) ; assertEquals(fullType, lt.getWrapperType() ); } @Test public void testString() { System.out.println("--- "); TypeConverter tc = getTypeConverter() ; // Primitive type expected checkStringPrimitiveType(tc, NONE); checkStringPrimitiveType(tc, NOT_NULL); checkStringPrimitiveType(tc, PRIMITIVE_TYPE); checkStringPrimitiveType(tc, UNSIGNED_TYPE); checkStringPrimitiveType(tc, PRIMITIVE_TYPE + UNSIGNED_TYPE); // checkStringPrimitiveType(tc, SQL_TYPE); // checkStringPrimitiveType(tc, NOT_NULL + SQL_TYPE);
checkStringPrimitiveType(tc, PRIMITIVE_TYPE + OBJECT_TYPE );
telosys-tools-bricks/telosys-tools-generic-model
src/test/java/org/telosys/tools/generic/model/types/LiteralValuesProviderForGoTest.java
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ;
import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import org.junit.Test; import static org.junit.Assert.assertEquals;
package org.telosys.tools.generic.model.types; public class LiteralValuesProviderForGoTest { //---------------------------------------------------------------------------------- private TypeConverter getTypeConverter() { return new TypeConverterForGo() ; } private LiteralValuesProvider getLiteralValuesProvider() { return new LiteralValuesProviderForGo() ; } private LanguageType getLanguageType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private LanguageType getLanguageType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); System.out.println("AttributeTypeInfo : " + attributeTypeInfo); return getLanguageType(attributeTypeInfo); } //---------------------------------------------------------------------------------- @Test public void testLiteralNull() { assertEquals("nil", getLiteralValuesProvider().getLiteralNull() ); } @Test public void testLiteralValuesForBOOLEAN() {
// Path: src/main/java/org/telosys/tools/generic/model/types/AttributeTypeInfo.java // public static final int NONE = 0 ; // Path: src/test/java/org/telosys/tools/generic/model/types/LiteralValuesProviderForGoTest.java import static org.telosys.tools.generic.model.types.AttributeTypeInfo.NONE; import org.junit.Test; import static org.junit.Assert.assertEquals; package org.telosys.tools.generic.model.types; public class LiteralValuesProviderForGoTest { //---------------------------------------------------------------------------------- private TypeConverter getTypeConverter() { return new TypeConverterForGo() ; } private LiteralValuesProvider getLiteralValuesProvider() { return new LiteralValuesProviderForGo() ; } private LanguageType getLanguageType(AttributeTypeInfo typeInfo ) { System.out.println( typeInfo + " --> " + typeInfo ); LanguageType lt = getTypeConverter().getType(typeInfo); return lt ; } private LanguageType getLanguageType(String neutralType, int typeInfo ) { AttributeTypeInfo attributeTypeInfo = new AttributeTypeInfo(neutralType, typeInfo); System.out.println("AttributeTypeInfo : " + attributeTypeInfo); return getLanguageType(attributeTypeInfo); } //---------------------------------------------------------------------------------- @Test public void testLiteralNull() { assertEquals("nil", getLiteralValuesProvider().getLiteralNull() ); } @Test public void testLiteralValuesForBOOLEAN() {
LanguageType lt = getLanguageType(NeutralType.BOOLEAN, NONE );
telosys-tools-bricks/telosys-tools-generic-model
src/main/java/org/telosys/tools/generic/model/CascadeOptions.java
// Path: src/main/java/org/telosys/tools/generic/model/enums/CascadeOption.java // public enum CascadeOption { // // /** // * // */ // MERGE(0, "MERGE"), // // /** // * // */ // PERSIST(1, "PERSIST"), // // /** // * // */ // REFRESH(2, "REFRESH"), // // /** // * // */ // REMOVE(3, "REMOVE"), // // /** // * // */ // ALL(4, "ALL"); // // //--------------------------------------------------- // private final int value ; // private final String text ; // // private CascadeOption(int value, String text) { // this.value = value ; // this.text = text ; // } // // /** // * Returns the fetch type as an int value (0 to 3) <br> // * @return // */ // public int getValue() { // return this.value ; // } // // /** // * Returns the fetch type as a text<br> // * e.g. : 'MERGE', 'PERSIST', etc // * @return // */ // public String getText() { // return this.text; // } // }
import java.io.Serializable; import java.util.LinkedList; import java.util.List; import org.telosys.tools.generic.model.enums.CascadeOption;
/** * Copyright (C) 2008-2017 Telosys project org. ( http://www.telosys.org/ ) * * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3.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.gnu.org/licenses/lgpl.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.telosys.tools.generic.model; /** * Object containing a set of selected 'cascade options' * * @author Laurent Guerin * */ public class CascadeOptions implements Serializable { private static final long serialVersionUID = 1L; private static final String CASCADE_ALL = "ALL";
// Path: src/main/java/org/telosys/tools/generic/model/enums/CascadeOption.java // public enum CascadeOption { // // /** // * // */ // MERGE(0, "MERGE"), // // /** // * // */ // PERSIST(1, "PERSIST"), // // /** // * // */ // REFRESH(2, "REFRESH"), // // /** // * // */ // REMOVE(3, "REMOVE"), // // /** // * // */ // ALL(4, "ALL"); // // //--------------------------------------------------- // private final int value ; // private final String text ; // // private CascadeOption(int value, String text) { // this.value = value ; // this.text = text ; // } // // /** // * Returns the fetch type as an int value (0 to 3) <br> // * @return // */ // public int getValue() { // return this.value ; // } // // /** // * Returns the fetch type as a text<br> // * e.g. : 'MERGE', 'PERSIST', etc // * @return // */ // public String getText() { // return this.text; // } // } // Path: src/main/java/org/telosys/tools/generic/model/CascadeOptions.java import java.io.Serializable; import java.util.LinkedList; import java.util.List; import org.telosys.tools.generic.model.enums.CascadeOption; /** * Copyright (C) 2008-2017 Telosys project org. ( http://www.telosys.org/ ) * * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3.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.gnu.org/licenses/lgpl.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.telosys.tools.generic.model; /** * Object containing a set of selected 'cascade options' * * @author Laurent Guerin * */ public class CascadeOptions implements Serializable { private static final long serialVersionUID = 1L; private static final String CASCADE_ALL = "ALL";
private final CascadeOption cascadeOptions[] = new CascadeOption[CascadeOption.values().length];
telosys-tools-bricks/telosys-tools-generic-model
src/main/java/org/telosys/tools/generic/model/types/TypeReverser.java
// Path: src/main/java/org/telosys/tools/generic/model/enums/DateType.java // public enum DateType { // // /** // * Undefined or not managed by the model implementation // */ // UNDEFINED(0), // // /** // * Date information only (no time) // */ // DATE_ONLY(1), // // /** // * Time information only (no date) // */ // TIME_ONLY(2), // // /** // * Date and time information // */ // DATE_AND_TIME(3); // // //--------------------------------------------------- // private int value ; // // private DateType(int value) { // this.value = value ; // } // // public int getValue() { // return this.value ; // } // }
import java.util.HashMap; import org.telosys.tools.generic.model.enums.DateType;
typesInfo.put(java.lang.Short.class.getCanonicalName(), objectType ) ; typesInfo.put(java.lang.Integer.class.getCanonicalName(), objectType ) ; typesInfo.put(java.lang.Long.class.getCanonicalName(), objectType ) ; typesInfo.put(java.lang.Float.class.getCanonicalName(), objectType ) ; typesInfo.put(java.lang.Double.class.getCanonicalName(), objectType ) ; typesInfo.put(java.util.Date.class.getCanonicalName(), objectType ) ; typesInfo.put(java.math.BigDecimal.class.getCanonicalName(), objectType ) ; // SQL type removed in v 3.3.0 // //--- Java object - SQL Types // typesInfo.put(java.sql.Date.class.getCanonicalName(), sqlType ) ; // typesInfo.put(java.sql.Time.class.getCanonicalName(), sqlType ) ; // typesInfo.put(java.sql.Timestamp.class.getCanonicalName(), sqlType ) ; // typesInfo.put(java.sql.Clob.class.getCanonicalName(), sqlType ) ; // typesInfo.put(java.sql.Blob.class.getCanonicalName(), sqlType ) ; typesInfo.put(java.sql.Date.class.getCanonicalName(), objectType ) ; typesInfo.put(java.sql.Time.class.getCanonicalName(), objectType ) ; typesInfo.put(java.sql.Timestamp.class.getCanonicalName(), objectType ) ; typesInfo.put(java.sql.Clob.class.getCanonicalName(), objectType ) ; typesInfo.put(java.sql.Blob.class.getCanonicalName(), objectType ) ; } /** * Returns the neutral type corresponding to the given Java type * @param javaType * @param dateType * @return */
// Path: src/main/java/org/telosys/tools/generic/model/enums/DateType.java // public enum DateType { // // /** // * Undefined or not managed by the model implementation // */ // UNDEFINED(0), // // /** // * Date information only (no time) // */ // DATE_ONLY(1), // // /** // * Time information only (no date) // */ // TIME_ONLY(2), // // /** // * Date and time information // */ // DATE_AND_TIME(3); // // //--------------------------------------------------- // private int value ; // // private DateType(int value) { // this.value = value ; // } // // public int getValue() { // return this.value ; // } // } // Path: src/main/java/org/telosys/tools/generic/model/types/TypeReverser.java import java.util.HashMap; import org.telosys.tools.generic.model.enums.DateType; typesInfo.put(java.lang.Short.class.getCanonicalName(), objectType ) ; typesInfo.put(java.lang.Integer.class.getCanonicalName(), objectType ) ; typesInfo.put(java.lang.Long.class.getCanonicalName(), objectType ) ; typesInfo.put(java.lang.Float.class.getCanonicalName(), objectType ) ; typesInfo.put(java.lang.Double.class.getCanonicalName(), objectType ) ; typesInfo.put(java.util.Date.class.getCanonicalName(), objectType ) ; typesInfo.put(java.math.BigDecimal.class.getCanonicalName(), objectType ) ; // SQL type removed in v 3.3.0 // //--- Java object - SQL Types // typesInfo.put(java.sql.Date.class.getCanonicalName(), sqlType ) ; // typesInfo.put(java.sql.Time.class.getCanonicalName(), sqlType ) ; // typesInfo.put(java.sql.Timestamp.class.getCanonicalName(), sqlType ) ; // typesInfo.put(java.sql.Clob.class.getCanonicalName(), sqlType ) ; // typesInfo.put(java.sql.Blob.class.getCanonicalName(), sqlType ) ; typesInfo.put(java.sql.Date.class.getCanonicalName(), objectType ) ; typesInfo.put(java.sql.Time.class.getCanonicalName(), objectType ) ; typesInfo.put(java.sql.Timestamp.class.getCanonicalName(), objectType ) ; typesInfo.put(java.sql.Clob.class.getCanonicalName(), objectType ) ; typesInfo.put(java.sql.Blob.class.getCanonicalName(), objectType ) ; } /** * Returns the neutral type corresponding to the given Java type * @param javaType * @param dateType * @return */
public String getNeutralType(String javaType, DateType dateType) {
geronimo-iia/winstone
winstone/src/main/java/net/winstone/config/builder/Ajp13ListenerConfigurationBuilder.java
// Path: winstone/src/main/java/net/winstone/config/Ajp13ListenerConfiguration.java // public class Ajp13ListenerConfiguration extends AddressConfiguration { // // /** // * serialVersionUID:long // */ // private static final long serialVersionUID = -4100806360220081365L; // // /** // * Build a new instance of Ajp13ListenerConfiguration. // * // * @param port // * @param address // */ // public Ajp13ListenerConfiguration(int port, String address) { // super(port, address); // } // // }
import net.winstone.config.Ajp13ListenerConfiguration;
/** * */ package net.winstone.config.builder; /** * Ajp13ListenerConfigurationBuilder. * * @author <a href="mailto:jguibert@intelligents-ia.com" >Jerome Guibert</a> * */ public class Ajp13ListenerConfigurationBuilder extends CompositeBuilder { protected int port = -1; protected String address = null; /** * Build a new instance of Ajp13ListenerConfigurationBuilder. * * @param builder */ public Ajp13ListenerConfigurationBuilder(ServerConfigurationBuilder builder) { super(builder); } /** * Set Address. * @param port * @param address * @return */ public Ajp13ListenerConfigurationBuilder setAddress(final int port, final String address) { this.port = port; this.address = address; return this; } /** * @param port * the port to set */ public final Ajp13ListenerConfigurationBuilder setPort(final int port) { this.port = port; return this; } /** * @param address * the address to set */ public final Ajp13ListenerConfigurationBuilder setAddress(final String address) { this.address = address; return this; } /** * @see net.winstone.config.builder.CompositeBuilder#build() */ @Override public ServerConfigurationBuilder build() {
// Path: winstone/src/main/java/net/winstone/config/Ajp13ListenerConfiguration.java // public class Ajp13ListenerConfiguration extends AddressConfiguration { // // /** // * serialVersionUID:long // */ // private static final long serialVersionUID = -4100806360220081365L; // // /** // * Build a new instance of Ajp13ListenerConfiguration. // * // * @param port // * @param address // */ // public Ajp13ListenerConfiguration(int port, String address) { // super(port, address); // } // // } // Path: winstone/src/main/java/net/winstone/config/builder/Ajp13ListenerConfigurationBuilder.java import net.winstone.config.Ajp13ListenerConfiguration; /** * */ package net.winstone.config.builder; /** * Ajp13ListenerConfigurationBuilder. * * @author <a href="mailto:jguibert@intelligents-ia.com" >Jerome Guibert</a> * */ public class Ajp13ListenerConfigurationBuilder extends CompositeBuilder { protected int port = -1; protected String address = null; /** * Build a new instance of Ajp13ListenerConfigurationBuilder. * * @param builder */ public Ajp13ListenerConfigurationBuilder(ServerConfigurationBuilder builder) { super(builder); } /** * Set Address. * @param port * @param address * @return */ public Ajp13ListenerConfigurationBuilder setAddress(final int port, final String address) { this.port = port; this.address = address; return this; } /** * @param port * the port to set */ public final Ajp13ListenerConfigurationBuilder setPort(final int port) { this.port = port; return this; } /** * @param address * the address to set */ public final Ajp13ListenerConfigurationBuilder setAddress(final String address) { this.address = address; return this; } /** * @see net.winstone.config.builder.CompositeBuilder#build() */ @Override public ServerConfigurationBuilder build() {
return builder.setAjp13ListenerConfiguration(new Ajp13ListenerConfiguration(port, address));
geronimo-iia/winstone
winstone/src/main/java/net/winstone/core/authentication/RetryRequestWrapper.java
// Path: winstone/src/main/java/net/winstone/util/SizeRestrictedHashtable.java // public class SizeRestrictedHashtable<K, V> extends Hashtable<K, V> { // // /** // * serialVersionUID:long // */ // private static final long serialVersionUID = -3783614228146621688L; // /** // * maximum Capacity. // */ // private final int maximumCapacity; // // public SizeRestrictedHashtable(final int initialCapacity, final float loadFactor, final int cap) { // super(initialCapacity, loadFactor); // this.maximumCapacity = cap; // } // // public SizeRestrictedHashtable(final int initialCapacity, final int cap) { // super(initialCapacity); // this.maximumCapacity = cap; // } // // public SizeRestrictedHashtable(final int cap) { // this.maximumCapacity = cap; // } // // public SizeRestrictedHashtable(final Map<? extends K, ? extends V> t, final int cap) { // super(t); // this.maximumCapacity = cap; // } // // @Override // public V put(final K key, final V value) { // if (size() > maximumCapacity) { // throw new IllegalStateException("Hash table size limit exceeded"); // } // return super.put(key, value); // } // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Enumeration; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import net.winstone.WinstoneException; import net.winstone.core.ObjectPool; import net.winstone.core.WinstoneInputStream; import net.winstone.core.WinstoneRequest; import net.winstone.util.SizeRestrictedHashMap; import net.winstone.util.SizeRestrictedHashtable; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
parseRequestParameters(); return Collections.enumeration(parsedParams.keySet()); } } @Override public String[] getParameterValues(final String name) { if (hasBeenForwarded()) { return super.getParameterValues(name); } else { parseRequestParameters(); final Object param = parsedParams.get(name); if (param == null) { return null; } else if (param instanceof String) { return new String[] { (String) param }; } else if (param instanceof String[]) { return (String[]) param; } else { throw new WinstoneException("Unknown param type: " + name + " - " + param.getClass()); } } } @Override @SuppressWarnings("rawtypes") public Map getParameterMap() { if (hasBeenForwarded()) { return super.getParameterMap(); } else {
// Path: winstone/src/main/java/net/winstone/util/SizeRestrictedHashtable.java // public class SizeRestrictedHashtable<K, V> extends Hashtable<K, V> { // // /** // * serialVersionUID:long // */ // private static final long serialVersionUID = -3783614228146621688L; // /** // * maximum Capacity. // */ // private final int maximumCapacity; // // public SizeRestrictedHashtable(final int initialCapacity, final float loadFactor, final int cap) { // super(initialCapacity, loadFactor); // this.maximumCapacity = cap; // } // // public SizeRestrictedHashtable(final int initialCapacity, final int cap) { // super(initialCapacity); // this.maximumCapacity = cap; // } // // public SizeRestrictedHashtable(final int cap) { // this.maximumCapacity = cap; // } // // public SizeRestrictedHashtable(final Map<? extends K, ? extends V> t, final int cap) { // super(t); // this.maximumCapacity = cap; // } // // @Override // public V put(final K key, final V value) { // if (size() > maximumCapacity) { // throw new IllegalStateException("Hash table size limit exceeded"); // } // return super.put(key, value); // } // } // Path: winstone/src/main/java/net/winstone/core/authentication/RetryRequestWrapper.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Enumeration; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import net.winstone.WinstoneException; import net.winstone.core.ObjectPool; import net.winstone.core.WinstoneInputStream; import net.winstone.core.WinstoneRequest; import net.winstone.util.SizeRestrictedHashMap; import net.winstone.util.SizeRestrictedHashtable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; parseRequestParameters(); return Collections.enumeration(parsedParams.keySet()); } } @Override public String[] getParameterValues(final String name) { if (hasBeenForwarded()) { return super.getParameterValues(name); } else { parseRequestParameters(); final Object param = parsedParams.get(name); if (param == null) { return null; } else if (param instanceof String) { return new String[] { (String) param }; } else if (param instanceof String[]) { return (String[]) param; } else { throw new WinstoneException("Unknown param type: " + name + " - " + param.getClass()); } } } @Override @SuppressWarnings("rawtypes") public Map getParameterMap() { if (hasBeenForwarded()) { return super.getParameterMap(); } else {
final Map<String, String[]> paramMap = new SizeRestrictedHashtable<String, String[]>(ObjectPool.getMaximumAllowedParameter());
geronimo-iia/winstone
winstone/src/main/java/net/winstone/MimeTypes.java
// Path: winstone/src/main/java/net/winstone/util/MapLoader.java // public final class MapLoader { // // /** // * Load the specified resource bundle and build a map with all keys finded. // * // * @param resourceBundle // * the specified resource bundle // * @return a <code>Map</code> instance representing key/value found in the // * specified resource bundle. // */ // public static Map<String, String> load(final ResourceBundle resourceBundle) { // final Map<String, String> resources = new HashMap<String, String>(); // if (resourceBundle != null) { // final Enumeration<String> keys = resourceBundle.getKeys(); // String key = null; // while (keys.hasMoreElements()) { // key = keys.nextElement(); // final String value = resourceBundle.getString(key); // resources.put(key, value); // } // } // return resources; // } // }
import java.net.FileNameMap; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import net.winstone.util.MapLoader;
package net.winstone; /** * MimeTypes implement a FileNameMap and using a <code>MapLoader</code> in order * to load data (localized on file MimeTypes.properties). MimeTypes is * initialized on demand (@see * http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom). * * @author <a href="mailto:jguibert@intelligents-ia.com" >Jerome Guibert</a> */ public class MimeTypes implements FileNameMap { private static final transient String UNKNOWN_EXTENSION = "unknown/unknown"; /** an unmodifiable map of Mime type. */ private final Map<String, String> ressource; /** * Build a new instance of MimeTypes. */ private MimeTypes() {
// Path: winstone/src/main/java/net/winstone/util/MapLoader.java // public final class MapLoader { // // /** // * Load the specified resource bundle and build a map with all keys finded. // * // * @param resourceBundle // * the specified resource bundle // * @return a <code>Map</code> instance representing key/value found in the // * specified resource bundle. // */ // public static Map<String, String> load(final ResourceBundle resourceBundle) { // final Map<String, String> resources = new HashMap<String, String>(); // if (resourceBundle != null) { // final Enumeration<String> keys = resourceBundle.getKeys(); // String key = null; // while (keys.hasMoreElements()) { // key = keys.nextElement(); // final String value = resourceBundle.getString(key); // resources.put(key, value); // } // } // return resources; // } // } // Path: winstone/src/main/java/net/winstone/MimeTypes.java import java.net.FileNameMap; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import net.winstone.util.MapLoader; package net.winstone; /** * MimeTypes implement a FileNameMap and using a <code>MapLoader</code> in order * to load data (localized on file MimeTypes.properties). MimeTypes is * initialized on demand (@see * http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom). * * @author <a href="mailto:jguibert@intelligents-ia.com" >Jerome Guibert</a> */ public class MimeTypes implements FileNameMap { private static final transient String UNKNOWN_EXTENSION = "unknown/unknown"; /** an unmodifiable map of Mime type. */ private final Map<String, String> ressource; /** * Build a new instance of MimeTypes. */ private MimeTypes() {
this(Collections.unmodifiableMap(MapLoader.load(ResourceBundle.getBundle("mime"))));
geronimo-iia/winstone
winstone/src/main/java/net/winstone/config/builder/HttpListenerConfigurationBuilder.java
// Path: winstone/src/main/java/net/winstone/config/HttpListenerConfiguration.java // public class HttpListenerConfiguration extends AddressConfiguration { // /** // * serialVersionUID:long // */ // private static final long serialVersionUID = 3804815852233764910L; // /** // * Enable or not host name lookup. // */ // protected final Boolean hostnameLookup; // // /** // * Build a new instance of HttpListenerConfiguration. // * // * @param port // * @param address // * @param enableHostnameLookup // */ // public HttpListenerConfiguration(int port, String address, Boolean enableHostnameLookup) { // super(port, address); // this.hostnameLookup = enableHostnameLookup; // } // // /** // * @return the doHostnameLookup // */ // public final Boolean isHostnameLookupEnabled() { // return hostnameLookup; // } // // }
import net.winstone.config.HttpListenerConfiguration;
*/ public final HttpListenerConfigurationBuilder setPort(final int port) { this.port = port; return this; } /** * @param address * the address to set */ public final HttpListenerConfigurationBuilder setAddress(final String address) { this.address = address; return this; } public final HttpListenerConfigurationBuilder enableHostnameLookups() { hostnameLookups = Boolean.TRUE; return this; } public final HttpListenerConfigurationBuilder disableHostnameLookups() { hostnameLookups = Boolean.FALSE; return this; } /** * @see net.winstone.config.builder.CompositeBuilder#build() */ @Override public ServerConfigurationBuilder build() {
// Path: winstone/src/main/java/net/winstone/config/HttpListenerConfiguration.java // public class HttpListenerConfiguration extends AddressConfiguration { // /** // * serialVersionUID:long // */ // private static final long serialVersionUID = 3804815852233764910L; // /** // * Enable or not host name lookup. // */ // protected final Boolean hostnameLookup; // // /** // * Build a new instance of HttpListenerConfiguration. // * // * @param port // * @param address // * @param enableHostnameLookup // */ // public HttpListenerConfiguration(int port, String address, Boolean enableHostnameLookup) { // super(port, address); // this.hostnameLookup = enableHostnameLookup; // } // // /** // * @return the doHostnameLookup // */ // public final Boolean isHostnameLookupEnabled() { // return hostnameLookup; // } // // } // Path: winstone/src/main/java/net/winstone/config/builder/HttpListenerConfigurationBuilder.java import net.winstone.config.HttpListenerConfiguration; */ public final HttpListenerConfigurationBuilder setPort(final int port) { this.port = port; return this; } /** * @param address * the address to set */ public final HttpListenerConfigurationBuilder setAddress(final String address) { this.address = address; return this; } public final HttpListenerConfigurationBuilder enableHostnameLookups() { hostnameLookups = Boolean.TRUE; return this; } public final HttpListenerConfigurationBuilder disableHostnameLookups() { hostnameLookups = Boolean.FALSE; return this; } /** * @see net.winstone.config.builder.CompositeBuilder#build() */ @Override public ServerConfigurationBuilder build() {
return builder.setHttpListenerConfiguration(new HttpListenerConfiguration(port, address, hostnameLookups));
geronimo-iia/winstone
winstone/src/main/java/net/winstone/config/SimpleAccessLoggerConfiguration.java
// Path: winstone/src/main/java/net/winstone/accesslog/SimpleAccessLogger.java // public final class SimpleAccessLogger implements AccessLogger { // protected Logger logger = LoggerFactory.getLogger(getClass()); // // private final DateCache dateCache; // private final String pattern; // private PrintWriter outWriter; // // /** // * // * Build a new instance of SimpleAccessLogger. // * @param host // * @param webapp // * @param patternType // * @param filePattern // */ // SimpleAccessLogger(final String host, final String webapp, final PatternType patternType, final String filePattern) { // super(); // dateCache = new DateCache(new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z")); // pattern = patternType.getPattern(); // final String fileName = StringUtils.replace(filePattern, new String[][] { { "###host###", host }, { "###webapp###", webapp } }); // // final File file = new File(fileName); // file.getParentFile().mkdirs(); // try { // outWriter = new PrintWriter(new FileOutputStream(file, Boolean.TRUE), Boolean.TRUE); // } catch (final FileNotFoundException e) { // logger.error("Unable to open " + fileName, e); // } // // logger.info(String.format("Initialized access log at %s (format: %s)", fileName, patternType)); // } // // @Override // public void log(final String originalURL, final WinstoneRequest request, final WinstoneResponse response) { // if (outWriter == null) { // return; // } // final String uriLine = request.getMethod() + " " + originalURL + " " + request.getProtocol(); // final int status = response.getErrorStatusCode() == null ? response.getStatus() : response.getErrorStatusCode().intValue(); // final long size = response.getWinstoneOutputStream().getBytesCommitted(); // final String date = dateCache.now(); // final String logLine = StringUtils.replace(pattern, // new String[][] { { "###ip###", request.getRemoteHost() }, { "###user###", SimpleAccessLogger.nvl(request.getRemoteUser()) }, { "###time###", "[" + date + "]" }, { "###uriLine###", uriLine }, { "###status###", "" + status }, // { "###size###", "" + size }, { "###referer###", SimpleAccessLogger.nvl(request.getHeader("Referer")) }, { "###userAgent###", SimpleAccessLogger.nvl(request.getHeader("User-Agent")) } }); // outWriter.println(logLine); // } // // private static String nvl(final String input) { // return input == null ? "-" : input; // } // // public void destroy() { // logger.info("Closed access log"); // if (outWriter != null) { // outWriter.flush(); // outWriter.close(); // outWriter = null; // } // } // // }
import net.winstone.accesslog.SimpleAccessLogger;
/** * */ package net.winstone.config; /** * SimpleAccessLoggerConfiguration. * * @author <a href="mailto:jguibert@intelligents-ia.com" >Jerome Guibert</a> * */ public class SimpleAccessLoggerConfiguration extends AccessLoggerConfiguration { /** * serialVersionUID:long */ private static final long serialVersionUID = 491570258594643467L; /** * The log format to use. Supports combined/common/resin/custom. */ private String loggerFormat; /** * The location pattern for the log file. */ private String loggerFilePattern; /** * Build a new instance of SimpleAccessLoggerConfiguration. * * @param className * @param loggerFormat * @param loggerFilePattern */ public SimpleAccessLoggerConfiguration(String loggerFormat, String loggerFilePattern) {
// Path: winstone/src/main/java/net/winstone/accesslog/SimpleAccessLogger.java // public final class SimpleAccessLogger implements AccessLogger { // protected Logger logger = LoggerFactory.getLogger(getClass()); // // private final DateCache dateCache; // private final String pattern; // private PrintWriter outWriter; // // /** // * // * Build a new instance of SimpleAccessLogger. // * @param host // * @param webapp // * @param patternType // * @param filePattern // */ // SimpleAccessLogger(final String host, final String webapp, final PatternType patternType, final String filePattern) { // super(); // dateCache = new DateCache(new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z")); // pattern = patternType.getPattern(); // final String fileName = StringUtils.replace(filePattern, new String[][] { { "###host###", host }, { "###webapp###", webapp } }); // // final File file = new File(fileName); // file.getParentFile().mkdirs(); // try { // outWriter = new PrintWriter(new FileOutputStream(file, Boolean.TRUE), Boolean.TRUE); // } catch (final FileNotFoundException e) { // logger.error("Unable to open " + fileName, e); // } // // logger.info(String.format("Initialized access log at %s (format: %s)", fileName, patternType)); // } // // @Override // public void log(final String originalURL, final WinstoneRequest request, final WinstoneResponse response) { // if (outWriter == null) { // return; // } // final String uriLine = request.getMethod() + " " + originalURL + " " + request.getProtocol(); // final int status = response.getErrorStatusCode() == null ? response.getStatus() : response.getErrorStatusCode().intValue(); // final long size = response.getWinstoneOutputStream().getBytesCommitted(); // final String date = dateCache.now(); // final String logLine = StringUtils.replace(pattern, // new String[][] { { "###ip###", request.getRemoteHost() }, { "###user###", SimpleAccessLogger.nvl(request.getRemoteUser()) }, { "###time###", "[" + date + "]" }, { "###uriLine###", uriLine }, { "###status###", "" + status }, // { "###size###", "" + size }, { "###referer###", SimpleAccessLogger.nvl(request.getHeader("Referer")) }, { "###userAgent###", SimpleAccessLogger.nvl(request.getHeader("User-Agent")) } }); // outWriter.println(logLine); // } // // private static String nvl(final String input) { // return input == null ? "-" : input; // } // // public void destroy() { // logger.info("Closed access log"); // if (outWriter != null) { // outWriter.flush(); // outWriter.close(); // outWriter = null; // } // } // // } // Path: winstone/src/main/java/net/winstone/config/SimpleAccessLoggerConfiguration.java import net.winstone.accesslog.SimpleAccessLogger; /** * */ package net.winstone.config; /** * SimpleAccessLoggerConfiguration. * * @author <a href="mailto:jguibert@intelligents-ia.com" >Jerome Guibert</a> * */ public class SimpleAccessLoggerConfiguration extends AccessLoggerConfiguration { /** * serialVersionUID:long */ private static final long serialVersionUID = 491570258594643467L; /** * The log format to use. Supports combined/common/resin/custom. */ private String loggerFormat; /** * The location pattern for the log file. */ private String loggerFilePattern; /** * Build a new instance of SimpleAccessLoggerConfiguration. * * @param className * @param loggerFormat * @param loggerFilePattern */ public SimpleAccessLoggerConfiguration(String loggerFormat, String loggerFilePattern) {
super(SimpleAccessLogger.class.getName());
MiguelSteph/data-structures-and-algorithm
Java-data-Structures/src/test/java/com/test/sorting/TestMergeSort.java
// Path: Java-data-Structures/src/main/java/com/sorting/MergeSort.java // public class MergeSort { // // /** // * Use the merge sort method to sort the given array A // * // * @param A // * Array of Comparable that contains the object to sort // */ // public static void sort(Comparable[] A) { // if (A == null) // return; // sort(A, 0, A.length - 1); // } // // private static void sort(Comparable[] A, int lo, int hi) { // if (lo >= hi) // return; // int mid = lo + (hi - lo) / 2; // sort(A, lo, mid); // sort(A, mid + 1, hi); // merge(A, lo, mid, hi); // } // // private static void merge(Comparable[] A, int lo, int mid, int hi) { // int leftSize = mid - lo + 1; // int rightSize = hi - mid; // Comparable[] left = new Comparable[leftSize]; // Comparable[] right = new Comparable[rightSize]; // // for (int i = 0; i < leftSize; i++) // left[i] = A[lo + i]; // // for (int i = 0; i < rightSize; i++) // right[i] = A[mid + i + 1]; // // int leftPt = 0; // int rightPt = 0; // for (int i = lo; i <= hi; i++) { // if (leftPt >= leftSize) { // A[i] = right[rightPt]; // rightPt++; // } else if (rightPt >= rightSize) { // A[i] = left[leftPt]; // leftPt++; // } else { // if (less(right[rightPt], left[leftPt])) { // A[i] = right[rightPt]; // rightPt++; // } else { // A[i] = left[leftPt]; // leftPt++; // } // } // } // } // // private static boolean less(Comparable a, Comparable b) { // int cmp = a.compareTo(b); // if (cmp < 0) // return true; // return false; // } // // }
import com.sorting.MergeSort; import junit.framework.TestCase;
package com.test.sorting; public class TestMergeSort extends TestCase { public void testMergeSort() { String[] A = { "zs", "qw", "qr", "miguel", "rtd", "fgs", "qq", "mk", "slao", "oiu", "vf", "xs", "er", "qw", "bv" }; Integer[] B = { 2, 4, 7, 542, 0, 1, 3, 0, 6, 2, 7, 9, 10, 2, 4, 6, 0, 3, 2, 9, 2, 77, 33, 22, 5, 4, 2, 2, 2 };
// Path: Java-data-Structures/src/main/java/com/sorting/MergeSort.java // public class MergeSort { // // /** // * Use the merge sort method to sort the given array A // * // * @param A // * Array of Comparable that contains the object to sort // */ // public static void sort(Comparable[] A) { // if (A == null) // return; // sort(A, 0, A.length - 1); // } // // private static void sort(Comparable[] A, int lo, int hi) { // if (lo >= hi) // return; // int mid = lo + (hi - lo) / 2; // sort(A, lo, mid); // sort(A, mid + 1, hi); // merge(A, lo, mid, hi); // } // // private static void merge(Comparable[] A, int lo, int mid, int hi) { // int leftSize = mid - lo + 1; // int rightSize = hi - mid; // Comparable[] left = new Comparable[leftSize]; // Comparable[] right = new Comparable[rightSize]; // // for (int i = 0; i < leftSize; i++) // left[i] = A[lo + i]; // // for (int i = 0; i < rightSize; i++) // right[i] = A[mid + i + 1]; // // int leftPt = 0; // int rightPt = 0; // for (int i = lo; i <= hi; i++) { // if (leftPt >= leftSize) { // A[i] = right[rightPt]; // rightPt++; // } else if (rightPt >= rightSize) { // A[i] = left[leftPt]; // leftPt++; // } else { // if (less(right[rightPt], left[leftPt])) { // A[i] = right[rightPt]; // rightPt++; // } else { // A[i] = left[leftPt]; // leftPt++; // } // } // } // } // // private static boolean less(Comparable a, Comparable b) { // int cmp = a.compareTo(b); // if (cmp < 0) // return true; // return false; // } // // } // Path: Java-data-Structures/src/test/java/com/test/sorting/TestMergeSort.java import com.sorting.MergeSort; import junit.framework.TestCase; package com.test.sorting; public class TestMergeSort extends TestCase { public void testMergeSort() { String[] A = { "zs", "qw", "qr", "miguel", "rtd", "fgs", "qq", "mk", "slao", "oiu", "vf", "xs", "er", "qw", "bv" }; Integer[] B = { 2, 4, 7, 542, 0, 1, 3, 0, 6, 2, 7, 9, 10, 2, 4, 6, 0, 3, 2, 9, 2, 77, 33, 22, 5, 4, 2, 2, 2 };
MergeSort.sort(A);
MiguelSteph/data-structures-and-algorithm
Java-data-Structures/src/test/java/com/test/queues/TestLinkedListImplOfQueue.java
// Path: Java-data-Structures/src/main/java/com/queues/LinkedListImplOfQueue.java // public class LinkedListImplOfQueue<Item> implements Queue<Item>{ // // /* // * Structure of each node of the linked list // */ // private class Node { // Item item; // Node next; // public Node(Item item, Node next) { // this.item = item; // this.next = next; // } // } // // /*** A reference to the Node on the top of the Queue. */ // private Node topQueue; // // /*** A reference to the Node at the end of the Queue. */ // private Node endQueue; // // /*** Contains the size of the Queue. */ // private int queueSize; // // /** // * Constructs an empty Queue. // */ // public LinkedListImplOfQueue() { // topQueue = null; // endQueue = null; // queueSize = 0; // } // // /*** {@inheritDoc} */ // @Override // public void add(Item item) { // if(item == null) // throw new NullPointerException("Null Item"); // Node newNode = new Node(item, null); // if (queueSize == 0) { // topQueue = newNode; // endQueue = topQueue; // }else{ // endQueue.next = newNode; // endQueue = endQueue.next; // } // queueSize++; // } // // /*** {@inheritDoc} */ // @Override // public Item poll() { // if (this.isEmpty()) { // throw new IllegalStateException("The queue is empty"); // } // Item polledItem = topQueue.item; // topQueue = topQueue.next; // queueSize--; // if (queueSize == 0) { // endQueue = null; // } // return polledItem; // } // // /*** {@inheritDoc} */ // @Override // public Item peek() { // if (this.isEmpty()) // throw new IllegalStateException("The queue is empty"); // return topQueue.item; // } // // /*** {@inheritDoc} */ // @Override // public boolean isEmpty() { // if(queueSize == 0) // return true; // return false; // } // // /*** {@inheritDoc} */ // @Override // public void clear() { // topQueue = null; // endQueue = null; // queueSize = 0; // } // // /*** {@inheritDoc} */ // @Override // public int size() { // return queueSize; // } // // /*** {@inheritDoc} */ // @Override // public boolean contains(Item item) { // Node top = topQueue; // while (top != null) { // if (top.item.equals(item)) // return true; // top = top.next; // } // return false; // } // // /*** {@inheritDoc} */ // @Override // public Iterator<Item> iterator() { // return new IteratorLinkedListImplOfQueue(); // } // // /** // * IteratorLinkedListImplOfQueue implements Iterator interface in order to // * provide iterable capabilities to the Queue. // * // * @author STEPHANE MIGUEL KAKANAKOU (Skakanakou@gmail.com) // * // */ // private class IteratorLinkedListImplOfQueue implements Iterator<Item> { // // /*** Reference on the current node in the iteration. */ // private Node currentNode; // // /*** Constructs IteratorLinkedListImplOfQueue. */ // public IteratorLinkedListImplOfQueue() { // currentNode = topQueue; // } // // /*** {@inheritDoc} */ // @Override // public boolean hasNext() { // if (currentNode != null) // return true; // return false; // } // // /*** {@inheritDoc} */ // @Override // public Item next() { // Item result = currentNode.item; // currentNode = currentNode.next; // return result; // } // } // // } // // Path: Java-data-Structures/src/main/java/com/queues/Queue.java // public interface Queue<Item> extends Iterable<Item> { // // /** // * Inserts the specified element at the end of this queue. // * // * @param item // * the element to add // * // * @exception java.lang.NullPointerException // * if item is null // */ // void add(Item item); // // /** // * Retrieves and removes the head of this queue. // * // * @return the head of this queue // * // * @exception java.lang.IllegalStateException // * if the Queue is empty // */ // Item poll(); // // /** // * Retrieves but not removes the head of this queue. // * // * @return the head of this queue // * // * @exception java.lang.IllegalStateException // * if the Queue is empty // */ // Item peek(); // // /** // * Tests if this Queue is empty. // * // * @return true if the Queue empty and false if not. // */ // boolean isEmpty(); // // /** // * Removes all of the elements from this Queue. // */ // void clear(); // // /** // * Returns the number of elements in this Queue. // * // * @return size the number of elements in this Queue. // */ // int size(); // // /** // * Returns true if this Queue contains the specified element. // * // * @param item // * the item to look for. // * // * @return true if the Queue contains the item and false if not. // */ // boolean contains(Item item); // // }
import com.queues.LinkedListImplOfQueue; import com.queues.Queue; import junit.framework.TestCase;
package com.test.queues; public class TestLinkedListImplOfQueue extends TestCase{ public void testEmpty() { // test empty queue
// Path: Java-data-Structures/src/main/java/com/queues/LinkedListImplOfQueue.java // public class LinkedListImplOfQueue<Item> implements Queue<Item>{ // // /* // * Structure of each node of the linked list // */ // private class Node { // Item item; // Node next; // public Node(Item item, Node next) { // this.item = item; // this.next = next; // } // } // // /*** A reference to the Node on the top of the Queue. */ // private Node topQueue; // // /*** A reference to the Node at the end of the Queue. */ // private Node endQueue; // // /*** Contains the size of the Queue. */ // private int queueSize; // // /** // * Constructs an empty Queue. // */ // public LinkedListImplOfQueue() { // topQueue = null; // endQueue = null; // queueSize = 0; // } // // /*** {@inheritDoc} */ // @Override // public void add(Item item) { // if(item == null) // throw new NullPointerException("Null Item"); // Node newNode = new Node(item, null); // if (queueSize == 0) { // topQueue = newNode; // endQueue = topQueue; // }else{ // endQueue.next = newNode; // endQueue = endQueue.next; // } // queueSize++; // } // // /*** {@inheritDoc} */ // @Override // public Item poll() { // if (this.isEmpty()) { // throw new IllegalStateException("The queue is empty"); // } // Item polledItem = topQueue.item; // topQueue = topQueue.next; // queueSize--; // if (queueSize == 0) { // endQueue = null; // } // return polledItem; // } // // /*** {@inheritDoc} */ // @Override // public Item peek() { // if (this.isEmpty()) // throw new IllegalStateException("The queue is empty"); // return topQueue.item; // } // // /*** {@inheritDoc} */ // @Override // public boolean isEmpty() { // if(queueSize == 0) // return true; // return false; // } // // /*** {@inheritDoc} */ // @Override // public void clear() { // topQueue = null; // endQueue = null; // queueSize = 0; // } // // /*** {@inheritDoc} */ // @Override // public int size() { // return queueSize; // } // // /*** {@inheritDoc} */ // @Override // public boolean contains(Item item) { // Node top = topQueue; // while (top != null) { // if (top.item.equals(item)) // return true; // top = top.next; // } // return false; // } // // /*** {@inheritDoc} */ // @Override // public Iterator<Item> iterator() { // return new IteratorLinkedListImplOfQueue(); // } // // /** // * IteratorLinkedListImplOfQueue implements Iterator interface in order to // * provide iterable capabilities to the Queue. // * // * @author STEPHANE MIGUEL KAKANAKOU (Skakanakou@gmail.com) // * // */ // private class IteratorLinkedListImplOfQueue implements Iterator<Item> { // // /*** Reference on the current node in the iteration. */ // private Node currentNode; // // /*** Constructs IteratorLinkedListImplOfQueue. */ // public IteratorLinkedListImplOfQueue() { // currentNode = topQueue; // } // // /*** {@inheritDoc} */ // @Override // public boolean hasNext() { // if (currentNode != null) // return true; // return false; // } // // /*** {@inheritDoc} */ // @Override // public Item next() { // Item result = currentNode.item; // currentNode = currentNode.next; // return result; // } // } // // } // // Path: Java-data-Structures/src/main/java/com/queues/Queue.java // public interface Queue<Item> extends Iterable<Item> { // // /** // * Inserts the specified element at the end of this queue. // * // * @param item // * the element to add // * // * @exception java.lang.NullPointerException // * if item is null // */ // void add(Item item); // // /** // * Retrieves and removes the head of this queue. // * // * @return the head of this queue // * // * @exception java.lang.IllegalStateException // * if the Queue is empty // */ // Item poll(); // // /** // * Retrieves but not removes the head of this queue. // * // * @return the head of this queue // * // * @exception java.lang.IllegalStateException // * if the Queue is empty // */ // Item peek(); // // /** // * Tests if this Queue is empty. // * // * @return true if the Queue empty and false if not. // */ // boolean isEmpty(); // // /** // * Removes all of the elements from this Queue. // */ // void clear(); // // /** // * Returns the number of elements in this Queue. // * // * @return size the number of elements in this Queue. // */ // int size(); // // /** // * Returns true if this Queue contains the specified element. // * // * @param item // * the item to look for. // * // * @return true if the Queue contains the item and false if not. // */ // boolean contains(Item item); // // } // Path: Java-data-Structures/src/test/java/com/test/queues/TestLinkedListImplOfQueue.java import com.queues.LinkedListImplOfQueue; import com.queues.Queue; import junit.framework.TestCase; package com.test.queues; public class TestLinkedListImplOfQueue extends TestCase{ public void testEmpty() { // test empty queue
Queue<String> que = new LinkedListImplOfQueue<String>();
MiguelSteph/data-structures-and-algorithm
Java-data-Structures/src/test/java/com/test/queues/TestLinkedListImplOfQueue.java
// Path: Java-data-Structures/src/main/java/com/queues/LinkedListImplOfQueue.java // public class LinkedListImplOfQueue<Item> implements Queue<Item>{ // // /* // * Structure of each node of the linked list // */ // private class Node { // Item item; // Node next; // public Node(Item item, Node next) { // this.item = item; // this.next = next; // } // } // // /*** A reference to the Node on the top of the Queue. */ // private Node topQueue; // // /*** A reference to the Node at the end of the Queue. */ // private Node endQueue; // // /*** Contains the size of the Queue. */ // private int queueSize; // // /** // * Constructs an empty Queue. // */ // public LinkedListImplOfQueue() { // topQueue = null; // endQueue = null; // queueSize = 0; // } // // /*** {@inheritDoc} */ // @Override // public void add(Item item) { // if(item == null) // throw new NullPointerException("Null Item"); // Node newNode = new Node(item, null); // if (queueSize == 0) { // topQueue = newNode; // endQueue = topQueue; // }else{ // endQueue.next = newNode; // endQueue = endQueue.next; // } // queueSize++; // } // // /*** {@inheritDoc} */ // @Override // public Item poll() { // if (this.isEmpty()) { // throw new IllegalStateException("The queue is empty"); // } // Item polledItem = topQueue.item; // topQueue = topQueue.next; // queueSize--; // if (queueSize == 0) { // endQueue = null; // } // return polledItem; // } // // /*** {@inheritDoc} */ // @Override // public Item peek() { // if (this.isEmpty()) // throw new IllegalStateException("The queue is empty"); // return topQueue.item; // } // // /*** {@inheritDoc} */ // @Override // public boolean isEmpty() { // if(queueSize == 0) // return true; // return false; // } // // /*** {@inheritDoc} */ // @Override // public void clear() { // topQueue = null; // endQueue = null; // queueSize = 0; // } // // /*** {@inheritDoc} */ // @Override // public int size() { // return queueSize; // } // // /*** {@inheritDoc} */ // @Override // public boolean contains(Item item) { // Node top = topQueue; // while (top != null) { // if (top.item.equals(item)) // return true; // top = top.next; // } // return false; // } // // /*** {@inheritDoc} */ // @Override // public Iterator<Item> iterator() { // return new IteratorLinkedListImplOfQueue(); // } // // /** // * IteratorLinkedListImplOfQueue implements Iterator interface in order to // * provide iterable capabilities to the Queue. // * // * @author STEPHANE MIGUEL KAKANAKOU (Skakanakou@gmail.com) // * // */ // private class IteratorLinkedListImplOfQueue implements Iterator<Item> { // // /*** Reference on the current node in the iteration. */ // private Node currentNode; // // /*** Constructs IteratorLinkedListImplOfQueue. */ // public IteratorLinkedListImplOfQueue() { // currentNode = topQueue; // } // // /*** {@inheritDoc} */ // @Override // public boolean hasNext() { // if (currentNode != null) // return true; // return false; // } // // /*** {@inheritDoc} */ // @Override // public Item next() { // Item result = currentNode.item; // currentNode = currentNode.next; // return result; // } // } // // } // // Path: Java-data-Structures/src/main/java/com/queues/Queue.java // public interface Queue<Item> extends Iterable<Item> { // // /** // * Inserts the specified element at the end of this queue. // * // * @param item // * the element to add // * // * @exception java.lang.NullPointerException // * if item is null // */ // void add(Item item); // // /** // * Retrieves and removes the head of this queue. // * // * @return the head of this queue // * // * @exception java.lang.IllegalStateException // * if the Queue is empty // */ // Item poll(); // // /** // * Retrieves but not removes the head of this queue. // * // * @return the head of this queue // * // * @exception java.lang.IllegalStateException // * if the Queue is empty // */ // Item peek(); // // /** // * Tests if this Queue is empty. // * // * @return true if the Queue empty and false if not. // */ // boolean isEmpty(); // // /** // * Removes all of the elements from this Queue. // */ // void clear(); // // /** // * Returns the number of elements in this Queue. // * // * @return size the number of elements in this Queue. // */ // int size(); // // /** // * Returns true if this Queue contains the specified element. // * // * @param item // * the item to look for. // * // * @return true if the Queue contains the item and false if not. // */ // boolean contains(Item item); // // }
import com.queues.LinkedListImplOfQueue; import com.queues.Queue; import junit.framework.TestCase;
package com.test.queues; public class TestLinkedListImplOfQueue extends TestCase{ public void testEmpty() { // test empty queue
// Path: Java-data-Structures/src/main/java/com/queues/LinkedListImplOfQueue.java // public class LinkedListImplOfQueue<Item> implements Queue<Item>{ // // /* // * Structure of each node of the linked list // */ // private class Node { // Item item; // Node next; // public Node(Item item, Node next) { // this.item = item; // this.next = next; // } // } // // /*** A reference to the Node on the top of the Queue. */ // private Node topQueue; // // /*** A reference to the Node at the end of the Queue. */ // private Node endQueue; // // /*** Contains the size of the Queue. */ // private int queueSize; // // /** // * Constructs an empty Queue. // */ // public LinkedListImplOfQueue() { // topQueue = null; // endQueue = null; // queueSize = 0; // } // // /*** {@inheritDoc} */ // @Override // public void add(Item item) { // if(item == null) // throw new NullPointerException("Null Item"); // Node newNode = new Node(item, null); // if (queueSize == 0) { // topQueue = newNode; // endQueue = topQueue; // }else{ // endQueue.next = newNode; // endQueue = endQueue.next; // } // queueSize++; // } // // /*** {@inheritDoc} */ // @Override // public Item poll() { // if (this.isEmpty()) { // throw new IllegalStateException("The queue is empty"); // } // Item polledItem = topQueue.item; // topQueue = topQueue.next; // queueSize--; // if (queueSize == 0) { // endQueue = null; // } // return polledItem; // } // // /*** {@inheritDoc} */ // @Override // public Item peek() { // if (this.isEmpty()) // throw new IllegalStateException("The queue is empty"); // return topQueue.item; // } // // /*** {@inheritDoc} */ // @Override // public boolean isEmpty() { // if(queueSize == 0) // return true; // return false; // } // // /*** {@inheritDoc} */ // @Override // public void clear() { // topQueue = null; // endQueue = null; // queueSize = 0; // } // // /*** {@inheritDoc} */ // @Override // public int size() { // return queueSize; // } // // /*** {@inheritDoc} */ // @Override // public boolean contains(Item item) { // Node top = topQueue; // while (top != null) { // if (top.item.equals(item)) // return true; // top = top.next; // } // return false; // } // // /*** {@inheritDoc} */ // @Override // public Iterator<Item> iterator() { // return new IteratorLinkedListImplOfQueue(); // } // // /** // * IteratorLinkedListImplOfQueue implements Iterator interface in order to // * provide iterable capabilities to the Queue. // * // * @author STEPHANE MIGUEL KAKANAKOU (Skakanakou@gmail.com) // * // */ // private class IteratorLinkedListImplOfQueue implements Iterator<Item> { // // /*** Reference on the current node in the iteration. */ // private Node currentNode; // // /*** Constructs IteratorLinkedListImplOfQueue. */ // public IteratorLinkedListImplOfQueue() { // currentNode = topQueue; // } // // /*** {@inheritDoc} */ // @Override // public boolean hasNext() { // if (currentNode != null) // return true; // return false; // } // // /*** {@inheritDoc} */ // @Override // public Item next() { // Item result = currentNode.item; // currentNode = currentNode.next; // return result; // } // } // // } // // Path: Java-data-Structures/src/main/java/com/queues/Queue.java // public interface Queue<Item> extends Iterable<Item> { // // /** // * Inserts the specified element at the end of this queue. // * // * @param item // * the element to add // * // * @exception java.lang.NullPointerException // * if item is null // */ // void add(Item item); // // /** // * Retrieves and removes the head of this queue. // * // * @return the head of this queue // * // * @exception java.lang.IllegalStateException // * if the Queue is empty // */ // Item poll(); // // /** // * Retrieves but not removes the head of this queue. // * // * @return the head of this queue // * // * @exception java.lang.IllegalStateException // * if the Queue is empty // */ // Item peek(); // // /** // * Tests if this Queue is empty. // * // * @return true if the Queue empty and false if not. // */ // boolean isEmpty(); // // /** // * Removes all of the elements from this Queue. // */ // void clear(); // // /** // * Returns the number of elements in this Queue. // * // * @return size the number of elements in this Queue. // */ // int size(); // // /** // * Returns true if this Queue contains the specified element. // * // * @param item // * the item to look for. // * // * @return true if the Queue contains the item and false if not. // */ // boolean contains(Item item); // // } // Path: Java-data-Structures/src/test/java/com/test/queues/TestLinkedListImplOfQueue.java import com.queues.LinkedListImplOfQueue; import com.queues.Queue; import junit.framework.TestCase; package com.test.queues; public class TestLinkedListImplOfQueue extends TestCase{ public void testEmpty() { // test empty queue
Queue<String> que = new LinkedListImplOfQueue<String>();
MiguelSteph/data-structures-and-algorithm
Java-data-Structures/src/test/java/com/test/sorting/TestShellSort.java
// Path: Java-data-Structures/src/main/java/com/sorting/ShellSort.java // public class ShellSort { // // /** // * Use the shell sort method to sort the given array A // * // * @param A // * Array of Comparable that contains the object to sort // */ // public static void sort(Comparable[] A) { // if (A == null) // return; // int h = computeMaxH(A.length); // while (h >= 1) { // hInsertionSort(A, h); // h = h / 3; // } // } // // private static void hInsertionSort(Comparable[] A, int h) { // Comparable curVal; // int j; // for (int i = h; i < A.length; i = i + h) { // curVal = A[i]; // j = i - h; // while ((j >= 0) && less(curVal, A[j])) { // A[j + h] = A[j]; // j = j - h; // } // A[j + h] = curVal; // } // } // // private static int computeMaxH(int len) { // int h = 1; // while (h < len / 3) // h = 3 * h + 1; // return h; // } // // private static boolean less(Comparable a, Comparable b) { // int cmp = a.compareTo(b); // if (cmp < 0) // return true; // return false; // } // // }
import com.sorting.ShellSort; import junit.framework.TestCase;
package com.test.sorting; public class TestShellSort extends TestCase{ public void testShellSort() { String[] A = { "zs", "qw", "qr", "miguel", "rtd", "fgs", "qq", "mk", "slao", "oiu", "vf", "xs", "er", "qw", "bv" }; Integer[] B = { 2, 4, 7, 542, 0, 1, 3, 0, 6, 2, 7, 9, 10, 2, 4, 6, 0, 3, 2, 9, 2, 77, 33, 22, 5, 4, 2, 2, 2 };
// Path: Java-data-Structures/src/main/java/com/sorting/ShellSort.java // public class ShellSort { // // /** // * Use the shell sort method to sort the given array A // * // * @param A // * Array of Comparable that contains the object to sort // */ // public static void sort(Comparable[] A) { // if (A == null) // return; // int h = computeMaxH(A.length); // while (h >= 1) { // hInsertionSort(A, h); // h = h / 3; // } // } // // private static void hInsertionSort(Comparable[] A, int h) { // Comparable curVal; // int j; // for (int i = h; i < A.length; i = i + h) { // curVal = A[i]; // j = i - h; // while ((j >= 0) && less(curVal, A[j])) { // A[j + h] = A[j]; // j = j - h; // } // A[j + h] = curVal; // } // } // // private static int computeMaxH(int len) { // int h = 1; // while (h < len / 3) // h = 3 * h + 1; // return h; // } // // private static boolean less(Comparable a, Comparable b) { // int cmp = a.compareTo(b); // if (cmp < 0) // return true; // return false; // } // // } // Path: Java-data-Structures/src/test/java/com/test/sorting/TestShellSort.java import com.sorting.ShellSort; import junit.framework.TestCase; package com.test.sorting; public class TestShellSort extends TestCase{ public void testShellSort() { String[] A = { "zs", "qw", "qr", "miguel", "rtd", "fgs", "qq", "mk", "slao", "oiu", "vf", "xs", "er", "qw", "bv" }; Integer[] B = { 2, 4, 7, 542, 0, 1, 3, 0, 6, 2, 7, 9, 10, 2, 4, 6, 0, 3, 2, 9, 2, 77, 33, 22, 5, 4, 2, 2, 2 };
ShellSort.sort(A);
MiguelSteph/data-structures-and-algorithm
Java-data-Structures/src/test/java/com/test/sorting/TestCountingSort.java
// Path: Java-data-Structures/src/main/java/com/sorting/CountingSort.java // public class CountingSort { // // public static int[] sort(int[] A) { // if (A == null) // return A; // // // find min and max // int min = A[0]; // int max = A[0]; // for (int i = 1; i < A.length; i++) { // min = Math.min(min, A[i]); // max = Math.max(max, A[i]); // } // // // fill the counting array // int countArraySize = max - min + 1; // int[] count = new int[countArraySize]; // for (int i = 0; i < A.length; i++) { // count[A[i] - min] = count[A[i] - min] + 1; // } // // // compute the partial sum of the counting array // for (int i = 1; i < countArraySize; i++) { // count[i] = count[i] + count[i - 1]; // } // // int[] B = new int[A.length]; // for (int i= A.length-1; i>=0; i--) { // count[A[i] - min] = count[A[i] - min] - 1; // B[count[A[i] - min]] = A[i]; // } // // return B; // } // // }
import com.sorting.CountingSort; import junit.framework.TestCase;
package com.test.sorting; public class TestCountingSort extends TestCase{ public void testCountingSort() { int[] A = { 2, 4, 7, 542, 0, 1, 3, 0, 6, 2, 7, 9, 10, 2, 4, -29, 6, 0, 3, 2, 9, 2, 77, 33, 22, 5, 4, 2, 2, 2 };
// Path: Java-data-Structures/src/main/java/com/sorting/CountingSort.java // public class CountingSort { // // public static int[] sort(int[] A) { // if (A == null) // return A; // // // find min and max // int min = A[0]; // int max = A[0]; // for (int i = 1; i < A.length; i++) { // min = Math.min(min, A[i]); // max = Math.max(max, A[i]); // } // // // fill the counting array // int countArraySize = max - min + 1; // int[] count = new int[countArraySize]; // for (int i = 0; i < A.length; i++) { // count[A[i] - min] = count[A[i] - min] + 1; // } // // // compute the partial sum of the counting array // for (int i = 1; i < countArraySize; i++) { // count[i] = count[i] + count[i - 1]; // } // // int[] B = new int[A.length]; // for (int i= A.length-1; i>=0; i--) { // count[A[i] - min] = count[A[i] - min] - 1; // B[count[A[i] - min]] = A[i]; // } // // return B; // } // // } // Path: Java-data-Structures/src/test/java/com/test/sorting/TestCountingSort.java import com.sorting.CountingSort; import junit.framework.TestCase; package com.test.sorting; public class TestCountingSort extends TestCase{ public void testCountingSort() { int[] A = { 2, 4, 7, 542, 0, 1, 3, 0, 6, 2, 7, 9, 10, 2, 4, -29, 6, 0, 3, 2, 9, 2, 77, 33, 22, 5, 4, 2, 2, 2 };
A = CountingSort.sort(A);
MiguelSteph/data-structures-and-algorithm
Java-data-Structures/src/test/java/com/test/graphs/TestGraphAdjacencyMatrixRepresentation.java
// Path: Java-data-Structures/src/main/java/com/graphs/GraphAdjacencyMatrixRepresentation.java // public class GraphAdjacencyMatrixRepresentation { // // /*** Size of vertices of the graph */ // private int V_Size; // // /*** Size of edges of the graph */ // private int E_Size; // // private boolean isDirected; // // /*** Adjacency Matrix that represent the graph */ // private int[][] adjMatrix; // // /** // * Constructor that take the number of vertices in the graph // * // * @param V_Size // * number of vertices in the graph // * @param isDirected // * true if the current graph is directed and false if not // * // * @exception IllegalArgumentException // * if V_Size <= 0 // */ // public GraphAdjacencyMatrixRepresentation(int V_Size, boolean isDirected) { // if (V_Size <= 0) // throw new IllegalArgumentException("Invalid Argument"); // this.V_Size = V_Size; // this.isDirected = isDirected; // E_Size = 0; // adjMatrix = new int[this.V_Size][this.V_Size]; // for (int i = 0; i < V_Size; i++) // Arrays.fill(adjMatrix[i], Integer.MIN_VALUE); // } // // /** // * Add a new edge to the graph and take the weight of the edge as 1. // * // * @param u // * Source of the edge // * @param v // * End of the edge // * // * @exception IllegalArgumentException // * if u or v is smaller than 0 or greater or equal to the // * number of vertices. // */ // public void addEdge(int u, int v) { // if ((u < 0) || (u >= V_Size) || (v < 0) || (v >= V_Size)) // throw new IllegalArgumentException("Invalid Argument"); // if (isDirectedGraph()) { // adjMatrix[u][v] = 1; // } else { // adjMatrix[u][v] = 1; // adjMatrix[v][u] = 1; // } // E_Size++; // } // // /** // * Add a new edge to the graph. // * // * @param u // * Source of the edge // * @param v // * End of the edge // * @param w // * Weight of the edge // * // * @exception IllegalArgumentException // * if u or v is smaller than 0 or greater or equal to the // * number of vertices or if w is equal to Integer.MIN_VALUE. // */ // public void addEdge(int u, int v, int w) { // if ((u < 0) || (u >= V_Size) || (v < 0) || (v >= V_Size) || (w == Integer.MIN_VALUE)) // throw new IllegalArgumentException("Invalid Argument"); // if (isDirectedGraph()) { // adjMatrix[u][v] = w; // } else { // adjMatrix[u][v] = w; // adjMatrix[v][u] = w; // } // E_Size++; // } // // /** // * Return the weigh of a given edge // * // * @param u // * the source of the edge // * @param v // * the destination of the edge // * // * @return the weight of the given edge or Integer.MIN_VALUE if the given // * edge doesn't exist. // * // * @exception IllegalArgumentException // * if u or v is smaller than 0 or greater or equal to the // * number of vertices. // */ // public int getWeight(int u, int v) { // return adjMatrix[u][v]; // } // // /** // * Test if this is directed or not. // * // * @return true if this graph is directed. // */ // public boolean isDirectedGraph() { // return isDirected; // } // // /** // * Test if the graph contains a given edge // * // * @param u // * Source of the Edge // * @param v // * End of the Edge // * @return true if that edge exist and false if not // */ // public boolean hasEdge(int u, int v) { // if ((u < 0) || (u >= V_Size) || (v < 0) || (v >= V_Size)) // throw new IllegalArgumentException("Invalid Argument"); // return adjMatrix[u][v] != Integer.MIN_VALUE; // } // // /** // * Number of vertices of the graph. // * // * @return Number of vertices of the graph. // */ // public int getV_Size() { // return V_Size; // } // // /** // * Number of edges of the graph. // * // * @return Number of edges of the graph. // */ // public int getE_Size() { // return E_Size; // } // // @Override // public String toString() { // StringBuilder str = new StringBuilder(); // str.append("[ "); // for (int i = 0; i < V_Size; i++) { // for (int j = 0; j < V_Size; j++) { // if (hasEdge(i, j)) { // str.append("[u=" + i + ", v=" + j + ", w=" + getWeight(i, j) + "] "); // } // } // } // str.append(" ]"); // return str.toString(); // } // // }
import com.graphs.GraphAdjacencyMatrixRepresentation; import junit.framework.TestCase;
package com.test.graphs; public class TestGraphAdjacencyMatrixRepresentation extends TestCase { public void testGraphAdjacencyMatrixRepresentationOperations() { // Undirected graph
// Path: Java-data-Structures/src/main/java/com/graphs/GraphAdjacencyMatrixRepresentation.java // public class GraphAdjacencyMatrixRepresentation { // // /*** Size of vertices of the graph */ // private int V_Size; // // /*** Size of edges of the graph */ // private int E_Size; // // private boolean isDirected; // // /*** Adjacency Matrix that represent the graph */ // private int[][] adjMatrix; // // /** // * Constructor that take the number of vertices in the graph // * // * @param V_Size // * number of vertices in the graph // * @param isDirected // * true if the current graph is directed and false if not // * // * @exception IllegalArgumentException // * if V_Size <= 0 // */ // public GraphAdjacencyMatrixRepresentation(int V_Size, boolean isDirected) { // if (V_Size <= 0) // throw new IllegalArgumentException("Invalid Argument"); // this.V_Size = V_Size; // this.isDirected = isDirected; // E_Size = 0; // adjMatrix = new int[this.V_Size][this.V_Size]; // for (int i = 0; i < V_Size; i++) // Arrays.fill(adjMatrix[i], Integer.MIN_VALUE); // } // // /** // * Add a new edge to the graph and take the weight of the edge as 1. // * // * @param u // * Source of the edge // * @param v // * End of the edge // * // * @exception IllegalArgumentException // * if u or v is smaller than 0 or greater or equal to the // * number of vertices. // */ // public void addEdge(int u, int v) { // if ((u < 0) || (u >= V_Size) || (v < 0) || (v >= V_Size)) // throw new IllegalArgumentException("Invalid Argument"); // if (isDirectedGraph()) { // adjMatrix[u][v] = 1; // } else { // adjMatrix[u][v] = 1; // adjMatrix[v][u] = 1; // } // E_Size++; // } // // /** // * Add a new edge to the graph. // * // * @param u // * Source of the edge // * @param v // * End of the edge // * @param w // * Weight of the edge // * // * @exception IllegalArgumentException // * if u or v is smaller than 0 or greater or equal to the // * number of vertices or if w is equal to Integer.MIN_VALUE. // */ // public void addEdge(int u, int v, int w) { // if ((u < 0) || (u >= V_Size) || (v < 0) || (v >= V_Size) || (w == Integer.MIN_VALUE)) // throw new IllegalArgumentException("Invalid Argument"); // if (isDirectedGraph()) { // adjMatrix[u][v] = w; // } else { // adjMatrix[u][v] = w; // adjMatrix[v][u] = w; // } // E_Size++; // } // // /** // * Return the weigh of a given edge // * // * @param u // * the source of the edge // * @param v // * the destination of the edge // * // * @return the weight of the given edge or Integer.MIN_VALUE if the given // * edge doesn't exist. // * // * @exception IllegalArgumentException // * if u or v is smaller than 0 or greater or equal to the // * number of vertices. // */ // public int getWeight(int u, int v) { // return adjMatrix[u][v]; // } // // /** // * Test if this is directed or not. // * // * @return true if this graph is directed. // */ // public boolean isDirectedGraph() { // return isDirected; // } // // /** // * Test if the graph contains a given edge // * // * @param u // * Source of the Edge // * @param v // * End of the Edge // * @return true if that edge exist and false if not // */ // public boolean hasEdge(int u, int v) { // if ((u < 0) || (u >= V_Size) || (v < 0) || (v >= V_Size)) // throw new IllegalArgumentException("Invalid Argument"); // return adjMatrix[u][v] != Integer.MIN_VALUE; // } // // /** // * Number of vertices of the graph. // * // * @return Number of vertices of the graph. // */ // public int getV_Size() { // return V_Size; // } // // /** // * Number of edges of the graph. // * // * @return Number of edges of the graph. // */ // public int getE_Size() { // return E_Size; // } // // @Override // public String toString() { // StringBuilder str = new StringBuilder(); // str.append("[ "); // for (int i = 0; i < V_Size; i++) { // for (int j = 0; j < V_Size; j++) { // if (hasEdge(i, j)) { // str.append("[u=" + i + ", v=" + j + ", w=" + getWeight(i, j) + "] "); // } // } // } // str.append(" ]"); // return str.toString(); // } // // } // Path: Java-data-Structures/src/test/java/com/test/graphs/TestGraphAdjacencyMatrixRepresentation.java import com.graphs.GraphAdjacencyMatrixRepresentation; import junit.framework.TestCase; package com.test.graphs; public class TestGraphAdjacencyMatrixRepresentation extends TestCase { public void testGraphAdjacencyMatrixRepresentationOperations() { // Undirected graph
GraphAdjacencyMatrixRepresentation graph = new GraphAdjacencyMatrixRepresentation(10, false);
MiguelSteph/data-structures-and-algorithm
Java-data-Structures/src/test/java/com/test/stacks/TestLinkedListImplOfStack.java
// Path: Java-data-Structures/src/main/java/com/stacks/LinkedListImplOfStack.java // public class LinkedListImplOfStack<Item> implements Stack<Item> { // // /* // * Structure of each node of the linked list // */ // private class Node { // Item item; // Node next; // public Node(Item item, Node next) { // this.item = item; // this.next = next; // } // } // // /*** A reference to the Node on the top of the stack. */ // private Node topStack; // // /*** Contains the size of the stack. */ // private int listSize; // // /** // * Constructs an empty stack. // */ // public LinkedListImplOfStack() { // this.listSize = 0; // this.topStack = null; // } // // /*** {@inheritDoc} */ // @Override // public Item pop() { // if (this.isEmpty()) { // throw new IllegalStateException("The stack is empty"); // } // Item poppedItem = topStack.item; // topStack = topStack.next; // listSize--; // return poppedItem; // } // // /*** {@inheritDoc} */ // @Override // public Item peek() { // if (this.isEmpty()) { // throw new IllegalStateException("The stack is empty"); // } // return topStack.item; // } // // /*** {@inheritDoc} */ // @Override // public void push(Item item) { // topStack = new Node(item, topStack); // listSize++; // } // // /*** {@inheritDoc} */ // @Override // public boolean isEmpty() { // if(topStack == null) // return true; // return false; // } // // /*** {@inheritDoc} */ // @Override // public void clear() { // topStack = null; // listSize = 0; // } // // /*** {@inheritDoc} */ // @Override // public int size() { // return listSize; // } // // /*** {@inheritDoc} */ // @Override // public boolean contains(Item item) { // Node top = topStack; // while (top != null) { // if (top.item.equals(item)) // return true; // top = top.next; // } // return false; // } // // /*** {@inheritDoc} */ // @Override // public Iterator<Item> iterator() { // return new IteratorLinkedListImplOfStack(); // } // // /** // * IteratorLinkedListImplOfStack implements Iterator interface in order to // * provide iterable capabilities to the stack. // * // * @author STEPHANE MIGUEL KAKANAKOU (Skakanakou@gmail.com) // * // */ // private class IteratorLinkedListImplOfStack implements Iterator<Item> { // // /*** Reference on the current node in the iteration. */ // private Node currentNode; // // /*** Constructs IteratorLinkedListImplOfStack. */ // public IteratorLinkedListImplOfStack() { // currentNode = topStack; // } // // /*** {@inheritDoc} */ // @Override // public boolean hasNext() { // if (currentNode != null) // return true; // return false; // } // // /*** {@inheritDoc} */ // @Override // public Item next() { // Item result = currentNode.item; // currentNode = currentNode.next; // return result; // } // } // // } // // Path: Java-data-Structures/src/main/java/com/stacks/Stack.java // public interface Stack<Item> extends Iterable<Item> { // // /** // * Removes and return the object at the top of this stack. // * // * @return item the object at the top of this stack. // * // * @exception java.lang.IllegalStateException // * if the Stack is empty // */ // Item pop(); // // /** // * Looks at the object at the top of this stack without removing it. // * // * @return item the object at the top of this stack. // * // * @exception java.lang.IllegalStateException // * if the Stack is empty // */ // Item peek(); // // /** // * Pushes an item onto the top of this stack. // * // * @param item // * the item to push on the top of the stack // * // * @exception java.lang.IllegalStateException // * if item is null // */ // void push(Item item); // // /** // * Tests if this stack is empty. // * // * @return true if the stack empty and false if not. // */ // boolean isEmpty(); // // /** // * Removes all of the elements from this stack. // */ // void clear(); // // /** // * Returns the number of elements in this stack. // * // * @return size the number of elements in this stack. // */ // int size(); // // /** // * Returns true if this stack contains the specified element. // * // * @param item // * the item to look for. // * // * @return true if the stack contains the item and false if not. // */ // boolean contains(Item item); // }
import com.stacks.LinkedListImplOfStack; import com.stacks.Stack; import junit.framework.TestCase;
package com.test.stacks; public class TestLinkedListImplOfStack extends TestCase{ public void testStack() {
// Path: Java-data-Structures/src/main/java/com/stacks/LinkedListImplOfStack.java // public class LinkedListImplOfStack<Item> implements Stack<Item> { // // /* // * Structure of each node of the linked list // */ // private class Node { // Item item; // Node next; // public Node(Item item, Node next) { // this.item = item; // this.next = next; // } // } // // /*** A reference to the Node on the top of the stack. */ // private Node topStack; // // /*** Contains the size of the stack. */ // private int listSize; // // /** // * Constructs an empty stack. // */ // public LinkedListImplOfStack() { // this.listSize = 0; // this.topStack = null; // } // // /*** {@inheritDoc} */ // @Override // public Item pop() { // if (this.isEmpty()) { // throw new IllegalStateException("The stack is empty"); // } // Item poppedItem = topStack.item; // topStack = topStack.next; // listSize--; // return poppedItem; // } // // /*** {@inheritDoc} */ // @Override // public Item peek() { // if (this.isEmpty()) { // throw new IllegalStateException("The stack is empty"); // } // return topStack.item; // } // // /*** {@inheritDoc} */ // @Override // public void push(Item item) { // topStack = new Node(item, topStack); // listSize++; // } // // /*** {@inheritDoc} */ // @Override // public boolean isEmpty() { // if(topStack == null) // return true; // return false; // } // // /*** {@inheritDoc} */ // @Override // public void clear() { // topStack = null; // listSize = 0; // } // // /*** {@inheritDoc} */ // @Override // public int size() { // return listSize; // } // // /*** {@inheritDoc} */ // @Override // public boolean contains(Item item) { // Node top = topStack; // while (top != null) { // if (top.item.equals(item)) // return true; // top = top.next; // } // return false; // } // // /*** {@inheritDoc} */ // @Override // public Iterator<Item> iterator() { // return new IteratorLinkedListImplOfStack(); // } // // /** // * IteratorLinkedListImplOfStack implements Iterator interface in order to // * provide iterable capabilities to the stack. // * // * @author STEPHANE MIGUEL KAKANAKOU (Skakanakou@gmail.com) // * // */ // private class IteratorLinkedListImplOfStack implements Iterator<Item> { // // /*** Reference on the current node in the iteration. */ // private Node currentNode; // // /*** Constructs IteratorLinkedListImplOfStack. */ // public IteratorLinkedListImplOfStack() { // currentNode = topStack; // } // // /*** {@inheritDoc} */ // @Override // public boolean hasNext() { // if (currentNode != null) // return true; // return false; // } // // /*** {@inheritDoc} */ // @Override // public Item next() { // Item result = currentNode.item; // currentNode = currentNode.next; // return result; // } // } // // } // // Path: Java-data-Structures/src/main/java/com/stacks/Stack.java // public interface Stack<Item> extends Iterable<Item> { // // /** // * Removes and return the object at the top of this stack. // * // * @return item the object at the top of this stack. // * // * @exception java.lang.IllegalStateException // * if the Stack is empty // */ // Item pop(); // // /** // * Looks at the object at the top of this stack without removing it. // * // * @return item the object at the top of this stack. // * // * @exception java.lang.IllegalStateException // * if the Stack is empty // */ // Item peek(); // // /** // * Pushes an item onto the top of this stack. // * // * @param item // * the item to push on the top of the stack // * // * @exception java.lang.IllegalStateException // * if item is null // */ // void push(Item item); // // /** // * Tests if this stack is empty. // * // * @return true if the stack empty and false if not. // */ // boolean isEmpty(); // // /** // * Removes all of the elements from this stack. // */ // void clear(); // // /** // * Returns the number of elements in this stack. // * // * @return size the number of elements in this stack. // */ // int size(); // // /** // * Returns true if this stack contains the specified element. // * // * @param item // * the item to look for. // * // * @return true if the stack contains the item and false if not. // */ // boolean contains(Item item); // } // Path: Java-data-Structures/src/test/java/com/test/stacks/TestLinkedListImplOfStack.java import com.stacks.LinkedListImplOfStack; import com.stacks.Stack; import junit.framework.TestCase; package com.test.stacks; public class TestLinkedListImplOfStack extends TestCase{ public void testStack() {
Stack<String> stack = new LinkedListImplOfStack<>();
MiguelSteph/data-structures-and-algorithm
Java-data-Structures/src/test/java/com/test/stacks/TestLinkedListImplOfStack.java
// Path: Java-data-Structures/src/main/java/com/stacks/LinkedListImplOfStack.java // public class LinkedListImplOfStack<Item> implements Stack<Item> { // // /* // * Structure of each node of the linked list // */ // private class Node { // Item item; // Node next; // public Node(Item item, Node next) { // this.item = item; // this.next = next; // } // } // // /*** A reference to the Node on the top of the stack. */ // private Node topStack; // // /*** Contains the size of the stack. */ // private int listSize; // // /** // * Constructs an empty stack. // */ // public LinkedListImplOfStack() { // this.listSize = 0; // this.topStack = null; // } // // /*** {@inheritDoc} */ // @Override // public Item pop() { // if (this.isEmpty()) { // throw new IllegalStateException("The stack is empty"); // } // Item poppedItem = topStack.item; // topStack = topStack.next; // listSize--; // return poppedItem; // } // // /*** {@inheritDoc} */ // @Override // public Item peek() { // if (this.isEmpty()) { // throw new IllegalStateException("The stack is empty"); // } // return topStack.item; // } // // /*** {@inheritDoc} */ // @Override // public void push(Item item) { // topStack = new Node(item, topStack); // listSize++; // } // // /*** {@inheritDoc} */ // @Override // public boolean isEmpty() { // if(topStack == null) // return true; // return false; // } // // /*** {@inheritDoc} */ // @Override // public void clear() { // topStack = null; // listSize = 0; // } // // /*** {@inheritDoc} */ // @Override // public int size() { // return listSize; // } // // /*** {@inheritDoc} */ // @Override // public boolean contains(Item item) { // Node top = topStack; // while (top != null) { // if (top.item.equals(item)) // return true; // top = top.next; // } // return false; // } // // /*** {@inheritDoc} */ // @Override // public Iterator<Item> iterator() { // return new IteratorLinkedListImplOfStack(); // } // // /** // * IteratorLinkedListImplOfStack implements Iterator interface in order to // * provide iterable capabilities to the stack. // * // * @author STEPHANE MIGUEL KAKANAKOU (Skakanakou@gmail.com) // * // */ // private class IteratorLinkedListImplOfStack implements Iterator<Item> { // // /*** Reference on the current node in the iteration. */ // private Node currentNode; // // /*** Constructs IteratorLinkedListImplOfStack. */ // public IteratorLinkedListImplOfStack() { // currentNode = topStack; // } // // /*** {@inheritDoc} */ // @Override // public boolean hasNext() { // if (currentNode != null) // return true; // return false; // } // // /*** {@inheritDoc} */ // @Override // public Item next() { // Item result = currentNode.item; // currentNode = currentNode.next; // return result; // } // } // // } // // Path: Java-data-Structures/src/main/java/com/stacks/Stack.java // public interface Stack<Item> extends Iterable<Item> { // // /** // * Removes and return the object at the top of this stack. // * // * @return item the object at the top of this stack. // * // * @exception java.lang.IllegalStateException // * if the Stack is empty // */ // Item pop(); // // /** // * Looks at the object at the top of this stack without removing it. // * // * @return item the object at the top of this stack. // * // * @exception java.lang.IllegalStateException // * if the Stack is empty // */ // Item peek(); // // /** // * Pushes an item onto the top of this stack. // * // * @param item // * the item to push on the top of the stack // * // * @exception java.lang.IllegalStateException // * if item is null // */ // void push(Item item); // // /** // * Tests if this stack is empty. // * // * @return true if the stack empty and false if not. // */ // boolean isEmpty(); // // /** // * Removes all of the elements from this stack. // */ // void clear(); // // /** // * Returns the number of elements in this stack. // * // * @return size the number of elements in this stack. // */ // int size(); // // /** // * Returns true if this stack contains the specified element. // * // * @param item // * the item to look for. // * // * @return true if the stack contains the item and false if not. // */ // boolean contains(Item item); // }
import com.stacks.LinkedListImplOfStack; import com.stacks.Stack; import junit.framework.TestCase;
package com.test.stacks; public class TestLinkedListImplOfStack extends TestCase{ public void testStack() {
// Path: Java-data-Structures/src/main/java/com/stacks/LinkedListImplOfStack.java // public class LinkedListImplOfStack<Item> implements Stack<Item> { // // /* // * Structure of each node of the linked list // */ // private class Node { // Item item; // Node next; // public Node(Item item, Node next) { // this.item = item; // this.next = next; // } // } // // /*** A reference to the Node on the top of the stack. */ // private Node topStack; // // /*** Contains the size of the stack. */ // private int listSize; // // /** // * Constructs an empty stack. // */ // public LinkedListImplOfStack() { // this.listSize = 0; // this.topStack = null; // } // // /*** {@inheritDoc} */ // @Override // public Item pop() { // if (this.isEmpty()) { // throw new IllegalStateException("The stack is empty"); // } // Item poppedItem = topStack.item; // topStack = topStack.next; // listSize--; // return poppedItem; // } // // /*** {@inheritDoc} */ // @Override // public Item peek() { // if (this.isEmpty()) { // throw new IllegalStateException("The stack is empty"); // } // return topStack.item; // } // // /*** {@inheritDoc} */ // @Override // public void push(Item item) { // topStack = new Node(item, topStack); // listSize++; // } // // /*** {@inheritDoc} */ // @Override // public boolean isEmpty() { // if(topStack == null) // return true; // return false; // } // // /*** {@inheritDoc} */ // @Override // public void clear() { // topStack = null; // listSize = 0; // } // // /*** {@inheritDoc} */ // @Override // public int size() { // return listSize; // } // // /*** {@inheritDoc} */ // @Override // public boolean contains(Item item) { // Node top = topStack; // while (top != null) { // if (top.item.equals(item)) // return true; // top = top.next; // } // return false; // } // // /*** {@inheritDoc} */ // @Override // public Iterator<Item> iterator() { // return new IteratorLinkedListImplOfStack(); // } // // /** // * IteratorLinkedListImplOfStack implements Iterator interface in order to // * provide iterable capabilities to the stack. // * // * @author STEPHANE MIGUEL KAKANAKOU (Skakanakou@gmail.com) // * // */ // private class IteratorLinkedListImplOfStack implements Iterator<Item> { // // /*** Reference on the current node in the iteration. */ // private Node currentNode; // // /*** Constructs IteratorLinkedListImplOfStack. */ // public IteratorLinkedListImplOfStack() { // currentNode = topStack; // } // // /*** {@inheritDoc} */ // @Override // public boolean hasNext() { // if (currentNode != null) // return true; // return false; // } // // /*** {@inheritDoc} */ // @Override // public Item next() { // Item result = currentNode.item; // currentNode = currentNode.next; // return result; // } // } // // } // // Path: Java-data-Structures/src/main/java/com/stacks/Stack.java // public interface Stack<Item> extends Iterable<Item> { // // /** // * Removes and return the object at the top of this stack. // * // * @return item the object at the top of this stack. // * // * @exception java.lang.IllegalStateException // * if the Stack is empty // */ // Item pop(); // // /** // * Looks at the object at the top of this stack without removing it. // * // * @return item the object at the top of this stack. // * // * @exception java.lang.IllegalStateException // * if the Stack is empty // */ // Item peek(); // // /** // * Pushes an item onto the top of this stack. // * // * @param item // * the item to push on the top of the stack // * // * @exception java.lang.IllegalStateException // * if item is null // */ // void push(Item item); // // /** // * Tests if this stack is empty. // * // * @return true if the stack empty and false if not. // */ // boolean isEmpty(); // // /** // * Removes all of the elements from this stack. // */ // void clear(); // // /** // * Returns the number of elements in this stack. // * // * @return size the number of elements in this stack. // */ // int size(); // // /** // * Returns true if this stack contains the specified element. // * // * @param item // * the item to look for. // * // * @return true if the stack contains the item and false if not. // */ // boolean contains(Item item); // } // Path: Java-data-Structures/src/test/java/com/test/stacks/TestLinkedListImplOfStack.java import com.stacks.LinkedListImplOfStack; import com.stacks.Stack; import junit.framework.TestCase; package com.test.stacks; public class TestLinkedListImplOfStack extends TestCase{ public void testStack() {
Stack<String> stack = new LinkedListImplOfStack<>();
MiguelSteph/data-structures-and-algorithm
Java-data-Structures/src/test/java/com/test/sorting/TestHeapSort.java
// Path: Java-data-Structures/src/main/java/com/sorting/HeapSort.java // public class HeapSort { // // /** // * Use the Heap sort method to sort the given array A // * // * @param A // * Array of Comparable that contains the object to sort // */ // public static void sort(Comparable[] A) { // if (A == null) // return; // heapify(A); // for (int k = A.length; k >= 1; k--) { // exch(A, 1, k); // sink(A, 1, k - 1); // } // } // // private static void heapify(Comparable[] A) { // for (int k = A.length / 2; k >= 1; k--) // sink(A, k, A.length); // } // // private static void sink(Comparable[] A, int indice, int len) { // int j; // while (indice <= len / 2) { // j = 2 * indice; // if ((j < len) && (less(A, j, j + 1))) // j++; // if (!less(A, indice, j)) // break; // exch(A, indice, j); // indice = j; // } // } // // private static void exch(Comparable[] A, int i, int j) { // i = getArrayIndex(i); // j = getArrayIndex(j); // Comparable k = A[i]; // A[i] = A[j]; // A[j] = k; // } // // private static boolean less(Comparable[] A, int i, int j) { // i = getArrayIndex(i); // j = getArrayIndex(j); // if (A[i].compareTo(A[j]) < 0) // return true; // return false; // } // // private static int getArrayIndex(int indice) { // return --indice; // } // // }
import com.sorting.HeapSort; import junit.framework.TestCase;
package com.test.sorting; public class TestHeapSort extends TestCase{ public void testHeapSort() { String[] A = { "zs", "qw", "qr", "miguel", "rtd", "fgs", "qq", "mk", "slao", "oiu", "vf", "xs", "er", "qw", "bv" }; Integer[] B = { 2, 4, 7, 542, 0, 1, 3, 0, 6, 2, 7, 9, 10, 2, 4, 6, 0, 3, 2, 9, 2, 77, 33, 22, 5, 4, 2, 2, 2 };
// Path: Java-data-Structures/src/main/java/com/sorting/HeapSort.java // public class HeapSort { // // /** // * Use the Heap sort method to sort the given array A // * // * @param A // * Array of Comparable that contains the object to sort // */ // public static void sort(Comparable[] A) { // if (A == null) // return; // heapify(A); // for (int k = A.length; k >= 1; k--) { // exch(A, 1, k); // sink(A, 1, k - 1); // } // } // // private static void heapify(Comparable[] A) { // for (int k = A.length / 2; k >= 1; k--) // sink(A, k, A.length); // } // // private static void sink(Comparable[] A, int indice, int len) { // int j; // while (indice <= len / 2) { // j = 2 * indice; // if ((j < len) && (less(A, j, j + 1))) // j++; // if (!less(A, indice, j)) // break; // exch(A, indice, j); // indice = j; // } // } // // private static void exch(Comparable[] A, int i, int j) { // i = getArrayIndex(i); // j = getArrayIndex(j); // Comparable k = A[i]; // A[i] = A[j]; // A[j] = k; // } // // private static boolean less(Comparable[] A, int i, int j) { // i = getArrayIndex(i); // j = getArrayIndex(j); // if (A[i].compareTo(A[j]) < 0) // return true; // return false; // } // // private static int getArrayIndex(int indice) { // return --indice; // } // // } // Path: Java-data-Structures/src/test/java/com/test/sorting/TestHeapSort.java import com.sorting.HeapSort; import junit.framework.TestCase; package com.test.sorting; public class TestHeapSort extends TestCase{ public void testHeapSort() { String[] A = { "zs", "qw", "qr", "miguel", "rtd", "fgs", "qq", "mk", "slao", "oiu", "vf", "xs", "er", "qw", "bv" }; Integer[] B = { 2, 4, 7, 542, 0, 1, 3, 0, 6, 2, 7, 9, 10, 2, 4, 6, 0, 3, 2, 9, 2, 77, 33, 22, 5, 4, 2, 2, 2 };
HeapSort.sort(A);
MiguelSteph/data-structures-and-algorithm
Java-data-Structures/src/test/java/com/test/sorting/TestBottomUpMergeSort.java
// Path: Java-data-Structures/src/main/java/com/sorting/BottomUpMergeSort.java // public class BottomUpMergeSort { // // /** // * Use the merge sort method to sort the given array A // * // * @param A // * Array of Comparable that contains the object to sort // */ // public static void sort(Comparable[] A) { // if (A == null) // return; // int len = A.length; // int subSize = 1; // int lo, mid, hi; // int maxGap = largestPowerOf2(len) / 2; // while (subSize <= maxGap) { // lo = -2 * subSize; // while (true) { // lo = lo + 2 * subSize; // mid = lo + subSize - 1; // hi = mid + subSize; // // if (mid >= len) // break; // else if (hi >= len) // hi = len - 1; // merge(A, lo, mid, hi); // } // subSize *= 2; // } // } // // private static void merge(Comparable[] A, int lo, int mid, int hi) { // int leftSize = mid - lo + 1; // int rightSize = hi - mid; // Comparable[] left = new Comparable[leftSize]; // Comparable[] right = new Comparable[rightSize]; // // for (int i = 0; i < leftSize; i++) // left[i] = A[lo + i]; // // for (int i = 0; i < rightSize; i++) // right[i] = A[mid + i + 1]; // // int leftPt = 0; // int rightPt = 0; // for (int i = lo; i <= hi; i++) { // if (leftPt >= leftSize) { // A[i] = right[rightPt]; // rightPt++; // } else if (rightPt >= rightSize) { // A[i] = left[leftPt]; // leftPt++; // } else { // if (less(right[rightPt], left[leftPt])) { // A[i] = right[rightPt]; // rightPt++; // } else { // A[i] = left[leftPt]; // leftPt++; // } // } // } // } // // private static int largestPowerOf2(int n) { // int expo = (int) (Math.log(n) / Math.log(2)); // int floorCandidate = (int) (Math.pow(2, expo)); // if (n <= floorCandidate) // return floorCandidate; // return 2 * floorCandidate; // } // // private static boolean less(Comparable a, Comparable b) { // int cmp = a.compareTo(b); // if (cmp < 0) // return true; // return false; // } // // }
import com.sorting.BottomUpMergeSort; import junit.framework.TestCase;
package com.test.sorting; public class TestBottomUpMergeSort extends TestCase{ public void testBottomUpMergeSort() { String[] A = { "zs", "qw", "qr", "miguel", "rtd", "fgs", "qq", "mk", "slao", "oiu", "vf", "xs", "er", "qw", "bv" }; Integer[] B = { 2, 4, 7, 542, 0, 1, 3, 0, 6, 2, 7, 9, 10, 2, 4, 6, 0, 3, 2, 9, 2, 77, 33, 22, 5, 4, 2, 2, 2 };
// Path: Java-data-Structures/src/main/java/com/sorting/BottomUpMergeSort.java // public class BottomUpMergeSort { // // /** // * Use the merge sort method to sort the given array A // * // * @param A // * Array of Comparable that contains the object to sort // */ // public static void sort(Comparable[] A) { // if (A == null) // return; // int len = A.length; // int subSize = 1; // int lo, mid, hi; // int maxGap = largestPowerOf2(len) / 2; // while (subSize <= maxGap) { // lo = -2 * subSize; // while (true) { // lo = lo + 2 * subSize; // mid = lo + subSize - 1; // hi = mid + subSize; // // if (mid >= len) // break; // else if (hi >= len) // hi = len - 1; // merge(A, lo, mid, hi); // } // subSize *= 2; // } // } // // private static void merge(Comparable[] A, int lo, int mid, int hi) { // int leftSize = mid - lo + 1; // int rightSize = hi - mid; // Comparable[] left = new Comparable[leftSize]; // Comparable[] right = new Comparable[rightSize]; // // for (int i = 0; i < leftSize; i++) // left[i] = A[lo + i]; // // for (int i = 0; i < rightSize; i++) // right[i] = A[mid + i + 1]; // // int leftPt = 0; // int rightPt = 0; // for (int i = lo; i <= hi; i++) { // if (leftPt >= leftSize) { // A[i] = right[rightPt]; // rightPt++; // } else if (rightPt >= rightSize) { // A[i] = left[leftPt]; // leftPt++; // } else { // if (less(right[rightPt], left[leftPt])) { // A[i] = right[rightPt]; // rightPt++; // } else { // A[i] = left[leftPt]; // leftPt++; // } // } // } // } // // private static int largestPowerOf2(int n) { // int expo = (int) (Math.log(n) / Math.log(2)); // int floorCandidate = (int) (Math.pow(2, expo)); // if (n <= floorCandidate) // return floorCandidate; // return 2 * floorCandidate; // } // // private static boolean less(Comparable a, Comparable b) { // int cmp = a.compareTo(b); // if (cmp < 0) // return true; // return false; // } // // } // Path: Java-data-Structures/src/test/java/com/test/sorting/TestBottomUpMergeSort.java import com.sorting.BottomUpMergeSort; import junit.framework.TestCase; package com.test.sorting; public class TestBottomUpMergeSort extends TestCase{ public void testBottomUpMergeSort() { String[] A = { "zs", "qw", "qr", "miguel", "rtd", "fgs", "qq", "mk", "slao", "oiu", "vf", "xs", "er", "qw", "bv" }; Integer[] B = { 2, 4, 7, 542, 0, 1, 3, 0, 6, 2, 7, 9, 10, 2, 4, 6, 0, 3, 2, 9, 2, 77, 33, 22, 5, 4, 2, 2, 2 };
BottomUpMergeSort.sort(A);
MiguelSteph/data-structures-and-algorithm
Java-data-Structures/src/test/java/com/test/sorting/TestInsertionSort.java
// Path: Java-data-Structures/src/main/java/com/sorting/InsertionSort.java // public class InsertionSort { // // /** // * Use the insertion sort method to sort the given array A // * // * @param A Array of Comparable that contains the object to sort // */ // public static void sort(Comparable[] A) { // if (A == null) // return; // Comparable curVal; // int j; // for (int i = 1; i < A.length; i++) { // curVal = A[i]; // j = i - 1; // while ((j >= 0) && less(curVal, A[j])) { // A[j + 1] = A[j]; // j--; // } // A[j + 1] = curVal; // } // } // // private static boolean less(Comparable a, Comparable b) { // int cmp = a.compareTo(b); // if (cmp < 0) // return true; // return false; // } // // }
import com.sorting.InsertionSort; import junit.framework.TestCase;
package com.test.sorting; public class TestInsertionSort extends TestCase{ public void testInsertionSort() { String[] A = { "zs", "qw", "qr", "miguel", "rtd", "fgs", "qq", "mk", "slao", "oiu", "vf", "xs", "er", "qw", "bv" }; Integer[] B = { 2, 4, 7, 542, 0, 1, 3, 0, 6, 2, 7, 9, 10, 2, 4, 6, 0, 3, 2, 9, 2, 77, 33, 22, 5, 4, 2, 2, 2 };
// Path: Java-data-Structures/src/main/java/com/sorting/InsertionSort.java // public class InsertionSort { // // /** // * Use the insertion sort method to sort the given array A // * // * @param A Array of Comparable that contains the object to sort // */ // public static void sort(Comparable[] A) { // if (A == null) // return; // Comparable curVal; // int j; // for (int i = 1; i < A.length; i++) { // curVal = A[i]; // j = i - 1; // while ((j >= 0) && less(curVal, A[j])) { // A[j + 1] = A[j]; // j--; // } // A[j + 1] = curVal; // } // } // // private static boolean less(Comparable a, Comparable b) { // int cmp = a.compareTo(b); // if (cmp < 0) // return true; // return false; // } // // } // Path: Java-data-Structures/src/test/java/com/test/sorting/TestInsertionSort.java import com.sorting.InsertionSort; import junit.framework.TestCase; package com.test.sorting; public class TestInsertionSort extends TestCase{ public void testInsertionSort() { String[] A = { "zs", "qw", "qr", "miguel", "rtd", "fgs", "qq", "mk", "slao", "oiu", "vf", "xs", "er", "qw", "bv" }; Integer[] B = { 2, 4, 7, 542, 0, 1, 3, 0, 6, 2, 7, 9, 10, 2, 4, 6, 0, 3, 2, 9, 2, 77, 33, 22, 5, 4, 2, 2, 2 };
InsertionSort.sort(A);
MiguelSteph/data-structures-and-algorithm
Java-data-Structures/src/main/java/com/graphs/ShortestPathWithBellmanFord.java
// Path: Java-data-Structures/src/main/java/com/graphs/GraphEdgeListRepresentation.java // public static class Edge implements Comparable<Edge> { // int u; // int v; // int w; // // public Edge(int begin, int end) { // this.u = begin; // this.v = end; // this.w = 1; // } // // public Edge(int begin, int end, int weight) { // this.u = begin; // this.v = end; // this.w = weight; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + u; // result = prime * result + v; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Edge other = (Edge) obj; // if (u != other.u) // return false; // if (v != other.v) // return false; // return true; // } // // @Override // public String toString() { // return "Edge [u=" + u + ", v=" + v + ", w=" + w + "]"; // } // // @Override // public int compareTo(Edge other) { // if (this.w < other.w) // return -1; // else if (this.w > other.w) // return 1; // else // return 0; // } // }
import java.util.Arrays; import java.util.LinkedList; import com.graphs.GraphEdgeListRepresentation.Edge;
package com.graphs; /** * Given a graph G and a vertex S, we want to find the shortest path from S to * any other vertex. Here we use the Bellman Ford algorithm. * * @author STEPHANE MIGUEL KAKANAKOU (Skakanakou@gmail.com) * */ public class ShortestPathWithBellmanFord { /*** The Source vertex */ private int S; /*** Array that contains the distance from the source to other vertices */ private int[] dist; /*** Array that contains the path from the source to other vertices */ private int[] prev; /** * Constructor that take the graph and the source vertex. * * @param graph * @param S * @exception throw * IllegalArgumentException if the given graph contains * negative edge weight. */ public ShortestPathWithBellmanFord(GraphEdgeListRepresentation graph, int S) { int v_size = graph.getV_Size(); if ((S < 0) || (S >= v_size)) throw new IllegalArgumentException("Invalid Argument"); this.S = S; dist = new int[v_size]; prev = new int[v_size]; Arrays.fill(dist, Integer.MAX_VALUE); Arrays.fill(prev, -1); bellManFord(graph); } /* * Private method that perform the Bellman-Ford algorithm. */ private void bellManFord(GraphEdgeListRepresentation graph) { dist[S] = 0; int v_size = graph.getV_Size(); for (int i = 0; i < v_size - 1; i++) {
// Path: Java-data-Structures/src/main/java/com/graphs/GraphEdgeListRepresentation.java // public static class Edge implements Comparable<Edge> { // int u; // int v; // int w; // // public Edge(int begin, int end) { // this.u = begin; // this.v = end; // this.w = 1; // } // // public Edge(int begin, int end, int weight) { // this.u = begin; // this.v = end; // this.w = weight; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + u; // result = prime * result + v; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Edge other = (Edge) obj; // if (u != other.u) // return false; // if (v != other.v) // return false; // return true; // } // // @Override // public String toString() { // return "Edge [u=" + u + ", v=" + v + ", w=" + w + "]"; // } // // @Override // public int compareTo(Edge other) { // if (this.w < other.w) // return -1; // else if (this.w > other.w) // return 1; // else // return 0; // } // } // Path: Java-data-Structures/src/main/java/com/graphs/ShortestPathWithBellmanFord.java import java.util.Arrays; import java.util.LinkedList; import com.graphs.GraphEdgeListRepresentation.Edge; package com.graphs; /** * Given a graph G and a vertex S, we want to find the shortest path from S to * any other vertex. Here we use the Bellman Ford algorithm. * * @author STEPHANE MIGUEL KAKANAKOU (Skakanakou@gmail.com) * */ public class ShortestPathWithBellmanFord { /*** The Source vertex */ private int S; /*** Array that contains the distance from the source to other vertices */ private int[] dist; /*** Array that contains the path from the source to other vertices */ private int[] prev; /** * Constructor that take the graph and the source vertex. * * @param graph * @param S * @exception throw * IllegalArgumentException if the given graph contains * negative edge weight. */ public ShortestPathWithBellmanFord(GraphEdgeListRepresentation graph, int S) { int v_size = graph.getV_Size(); if ((S < 0) || (S >= v_size)) throw new IllegalArgumentException("Invalid Argument"); this.S = S; dist = new int[v_size]; prev = new int[v_size]; Arrays.fill(dist, Integer.MAX_VALUE); Arrays.fill(prev, -1); bellManFord(graph); } /* * Private method that perform the Bellman-Ford algorithm. */ private void bellManFord(GraphEdgeListRepresentation graph) { dist[S] = 0; int v_size = graph.getV_Size(); for (int i = 0; i < v_size - 1; i++) {
for (Edge edge : graph.getEdgeslist()) {