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
marbl/MHAP
src/main/java/edu/umd/marbl/mhap/align/AlignElementSketch.java
// Path: src/main/java/edu/umd/marbl/mhap/impl/OverlapInfo.java // public final class OverlapInfo // { // public final int a1; // public final int a2; // public final int b1; // public final int b2; // public final double rawScore; // public final double score; // // public static OverlapInfo EMPTY = new OverlapInfo(0.0, 0.0, 0, 0, 0, 0); // // public OverlapInfo(double score, double rawScore, int a1, int a2, int b1, int b2) // { // this.score = score; // this.rawScore = rawScore; // this.a1 = a1; // this.a2 = a2; // this.b1 = b1; // this.b2 = b2; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() // { // return "[score="+this.score+", a1="+this.a1+" a2="+this.a2+", b1="+this.b1+" b2="+this.b2+"]"; // } // // } // // Path: src/main/java/edu/umd/marbl/mhap/sketch/Sketch.java // public interface Sketch<T extends Sketch<T>> extends Serializable // { // double similarity(T sh); // }
import edu.umd.marbl.mhap.impl.OverlapInfo; import edu.umd.marbl.mhap.sketch.Sketch;
/* * MHAP package * * This software is distributed "as is", without any warranty, including * any implied warranty of merchantability or fitness for a particular * use. The authors assume no responsibility for, and shall not be liable * for, any special, indirect, or consequential damages, or any damages * whatsoever, arising out of or in connection with the use of this * software. * * Copyright (c) 2015 by Konstantin Berlin and Sergey Koren * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 edu.umd.marbl.mhap.align; public final class AlignElementSketch<T extends Sketch<T>> implements AlignElement<AlignElementSketch<T>> { private final T[] elements; private final int seqLength; private final int stepSize; public AlignElementSketch(T[] sketchArray, int stepSize, int seqLength) { this.elements = sketchArray; this.stepSize = stepSize; this.seqLength = seqLength; }
// Path: src/main/java/edu/umd/marbl/mhap/impl/OverlapInfo.java // public final class OverlapInfo // { // public final int a1; // public final int a2; // public final int b1; // public final int b2; // public final double rawScore; // public final double score; // // public static OverlapInfo EMPTY = new OverlapInfo(0.0, 0.0, 0, 0, 0, 0); // // public OverlapInfo(double score, double rawScore, int a1, int a2, int b1, int b2) // { // this.score = score; // this.rawScore = rawScore; // this.a1 = a1; // this.a2 = a2; // this.b1 = b1; // this.b2 = b2; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() // { // return "[score="+this.score+", a1="+this.a1+" a2="+this.a2+", b1="+this.b1+" b2="+this.b2+"]"; // } // // } // // Path: src/main/java/edu/umd/marbl/mhap/sketch/Sketch.java // public interface Sketch<T extends Sketch<T>> extends Serializable // { // double similarity(T sh); // } // Path: src/main/java/edu/umd/marbl/mhap/align/AlignElementSketch.java import edu.umd.marbl.mhap.impl.OverlapInfo; import edu.umd.marbl.mhap.sketch.Sketch; /* * MHAP package * * This software is distributed "as is", without any warranty, including * any implied warranty of merchantability or fitness for a particular * use. The authors assume no responsibility for, and shall not be liable * for, any special, indirect, or consequential damages, or any damages * whatsoever, arising out of or in connection with the use of this * software. * * Copyright (c) 2015 by Konstantin Berlin and Sergey Koren * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 edu.umd.marbl.mhap.align; public final class AlignElementSketch<T extends Sketch<T>> implements AlignElement<AlignElementSketch<T>> { private final T[] elements; private final int seqLength; private final int stepSize; public AlignElementSketch(T[] sketchArray, int stepSize, int seqLength) { this.elements = sketchArray; this.stepSize = stepSize; this.seqLength = seqLength; }
public OverlapInfo getOverlapInfo(Aligner<AlignElementSketch<T>> aligner, AlignElementSketch<T> b)
marbl/MHAP
src/main/java/edu/umd/marbl/mhap/align/AlignElementDoubleSketch.java
// Path: src/main/java/edu/umd/marbl/mhap/impl/OverlapInfo.java // public final class OverlapInfo // { // public final int a1; // public final int a2; // public final int b1; // public final int b2; // public final double rawScore; // public final double score; // // public static OverlapInfo EMPTY = new OverlapInfo(0.0, 0.0, 0, 0, 0, 0); // // public OverlapInfo(double score, double rawScore, int a1, int a2, int b1, int b2) // { // this.score = score; // this.rawScore = rawScore; // this.a1 = a1; // this.a2 = a2; // this.b1 = b1; // this.b2 = b2; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() // { // return "[score="+this.score+", a1="+this.a1+" a2="+this.a2+", b1="+this.b1+" b2="+this.b2+"]"; // } // // } // // Path: src/main/java/edu/umd/marbl/mhap/sketch/Sketch.java // public interface Sketch<T extends Sketch<T>> extends Serializable // { // double similarity(T sh); // }
import edu.umd.marbl.mhap.impl.OverlapInfo; import edu.umd.marbl.mhap.sketch.Sketch;
/* * MHAP package * * This software is distributed "as is", without any warranty, including * any implied warranty of merchantability or fitness for a particular * use. The authors assume no responsibility for, and shall not be liable * for, any special, indirect, or consequential damages, or any damages * whatsoever, arising out of or in connection with the use of this * software. * * Copyright (c) 2015 by Konstantin Berlin and Sergey Koren * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 edu.umd.marbl.mhap.align; public final class AlignElementDoubleSketch<T extends Sketch<T>> implements AlignElement<AlignElementDoubleSketch<T>> { private final T[] elements; private final int seqLength; private final int stepSize; public AlignElementDoubleSketch(T[] sketchArray, int stepSize, int seqLength) { this.elements = sketchArray; this.stepSize = stepSize; this.seqLength = seqLength; }
// Path: src/main/java/edu/umd/marbl/mhap/impl/OverlapInfo.java // public final class OverlapInfo // { // public final int a1; // public final int a2; // public final int b1; // public final int b2; // public final double rawScore; // public final double score; // // public static OverlapInfo EMPTY = new OverlapInfo(0.0, 0.0, 0, 0, 0, 0); // // public OverlapInfo(double score, double rawScore, int a1, int a2, int b1, int b2) // { // this.score = score; // this.rawScore = rawScore; // this.a1 = a1; // this.a2 = a2; // this.b1 = b1; // this.b2 = b2; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() // { // return "[score="+this.score+", a1="+this.a1+" a2="+this.a2+", b1="+this.b1+" b2="+this.b2+"]"; // } // // } // // Path: src/main/java/edu/umd/marbl/mhap/sketch/Sketch.java // public interface Sketch<T extends Sketch<T>> extends Serializable // { // double similarity(T sh); // } // Path: src/main/java/edu/umd/marbl/mhap/align/AlignElementDoubleSketch.java import edu.umd.marbl.mhap.impl.OverlapInfo; import edu.umd.marbl.mhap.sketch.Sketch; /* * MHAP package * * This software is distributed "as is", without any warranty, including * any implied warranty of merchantability or fitness for a particular * use. The authors assume no responsibility for, and shall not be liable * for, any special, indirect, or consequential damages, or any damages * whatsoever, arising out of or in connection with the use of this * software. * * Copyright (c) 2015 by Konstantin Berlin and Sergey Koren * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 edu.umd.marbl.mhap.align; public final class AlignElementDoubleSketch<T extends Sketch<T>> implements AlignElement<AlignElementDoubleSketch<T>> { private final T[] elements; private final int seqLength; private final int stepSize; public AlignElementDoubleSketch(T[] sketchArray, int stepSize, int seqLength) { this.elements = sketchArray; this.stepSize = stepSize; this.seqLength = seqLength; }
public OverlapInfo getOverlapInfo(Aligner<AlignElementDoubleSketch<T>> aligner, AlignElementDoubleSketch<T> b)
marbl/MHAP
src/main/java/edu/umd/marbl/mhap/sketch/MinHashSketch.java
// Path: src/main/java/edu/umd/marbl/mhap/utils/HitCounter.java // public final class HitCounter // { // public int count; // // public HitCounter() // { // this.count = 0; // } // // public HitCounter(int count) // { // this.count = count; // } // // public HitCounter addHit() // { // this.count++; // return this; // } // // public void addHits(int counts) // { // this.count+=counts; // } // }
import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Map.Entry; import edu.umd.marbl.mhap.utils.HitCounter; import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap;
/* * MHAP package * * This software is distributed "as is", without any warranty, including * any implied warranty of merchantability or fitness for a particular * use. The authors assume no responsibility for, and shall not be liable * for, any special, indirect, or consequential damages, or any damages * whatsoever, arising out of or in connection with the use of this * software. * * Copyright (c) 2014 by Konstantin Berlin and Sergey Koren * University Of Maryland * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 edu.umd.marbl.mhap.sketch; public final class MinHashSketch implements Sketch<MinHashSketch> { private final int[] minHashes; /** * */ private static final long serialVersionUID = 8846482698636860862L; private final static int[] computeNgramMinHashesWeighted(String seq, final int nGramSize, final int numHashes, FrequencyCounts kmerFilter, boolean doReverseCompliment, double repeatWeight) throws ZeroNGramsFoundException { final int numberNGrams = seq.length() - nGramSize + 1; if (numberNGrams < 1) throw new ZeroNGramsFoundException("N-gram size bigger than string length.", seq); //if (repeatWeight>=1.0) // throw new SketchRuntimeException("repeatWeight cannot be >=1."); // get the kmer hashes final long[] kmerHashes = HashUtils.computeSequenceHashesLong(seq, nGramSize, 0, doReverseCompliment); //now compute the counts of occurance
// Path: src/main/java/edu/umd/marbl/mhap/utils/HitCounter.java // public final class HitCounter // { // public int count; // // public HitCounter() // { // this.count = 0; // } // // public HitCounter(int count) // { // this.count = count; // } // // public HitCounter addHit() // { // this.count++; // return this; // } // // public void addHits(int counts) // { // this.count+=counts; // } // } // Path: src/main/java/edu/umd/marbl/mhap/sketch/MinHashSketch.java import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Map.Entry; import edu.umd.marbl.mhap.utils.HitCounter; import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap; /* * MHAP package * * This software is distributed "as is", without any warranty, including * any implied warranty of merchantability or fitness for a particular * use. The authors assume no responsibility for, and shall not be liable * for, any special, indirect, or consequential damages, or any damages * whatsoever, arising out of or in connection with the use of this * software. * * Copyright (c) 2014 by Konstantin Berlin and Sergey Koren * University Of Maryland * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 edu.umd.marbl.mhap.sketch; public final class MinHashSketch implements Sketch<MinHashSketch> { private final int[] minHashes; /** * */ private static final long serialVersionUID = 8846482698636860862L; private final static int[] computeNgramMinHashesWeighted(String seq, final int nGramSize, final int numHashes, FrequencyCounts kmerFilter, boolean doReverseCompliment, double repeatWeight) throws ZeroNGramsFoundException { final int numberNGrams = seq.length() - nGramSize + 1; if (numberNGrams < 1) throw new ZeroNGramsFoundException("N-gram size bigger than string length.", seq); //if (repeatWeight>=1.0) // throw new SketchRuntimeException("repeatWeight cannot be >=1."); // get the kmer hashes final long[] kmerHashes = HashUtils.computeSequenceHashesLong(seq, nGramSize, 0, doReverseCompliment); //now compute the counts of occurance
Long2ObjectLinkedOpenHashMap<HitCounter> hitMap = new Long2ObjectLinkedOpenHashMap<HitCounter>(kmerHashes.length);
marbl/MHAP
src/main/java/edu/umd/marbl/mhap/align/Aligner.java
// Path: src/main/java/edu/umd/marbl/mhap/align/Alignment.java // public enum Operation // { // MATCH, // INSERT, // DELETE; // }
import edu.umd.marbl.mhap.align.Alignment.Operation; import java.util.ArrayList; import java.util.Collections;
int maxJ = 0; for (int i=1; i<=a.length(); i++) { for (int j=1; j<=b.length(); j++) { P[i][j] = Math.max(D[i-1][j]+this.gapOpen, P[i-1][j]+this.gapExtend); Q[i][j] = Math.max(D[i][j-1]+this.gapOpen, Q[i][j-1]+this.gapExtend); float score = D[i-1][j-1]+(float)a.similarityScore(b, i-1, j-1)+this.scoreOffset; //compute the actual score D[i][j] = Math.max(score, Math.max(P[i][j], Q[i][j])); if (D[i][j] > maxValue) { maxValue = D[i][j]; maxI = i; maxJ = j; } } } float score = maxValue; int a1 = 0; int a2 = Math.max(0, maxI-1); int b1 = 0; int b2 = Math.max(0, maxJ-1); if (storePath) { //figure out the path
// Path: src/main/java/edu/umd/marbl/mhap/align/Alignment.java // public enum Operation // { // MATCH, // INSERT, // DELETE; // } // Path: src/main/java/edu/umd/marbl/mhap/align/Aligner.java import edu.umd.marbl.mhap.align.Alignment.Operation; import java.util.ArrayList; import java.util.Collections; int maxJ = 0; for (int i=1; i<=a.length(); i++) { for (int j=1; j<=b.length(); j++) { P[i][j] = Math.max(D[i-1][j]+this.gapOpen, P[i-1][j]+this.gapExtend); Q[i][j] = Math.max(D[i][j-1]+this.gapOpen, Q[i][j-1]+this.gapExtend); float score = D[i-1][j-1]+(float)a.similarityScore(b, i-1, j-1)+this.scoreOffset; //compute the actual score D[i][j] = Math.max(score, Math.max(P[i][j], Q[i][j])); if (D[i][j] > maxValue) { maxValue = D[i][j]; maxI = i; maxJ = j; } } } float score = maxValue; int a1 = 0; int a2 = Math.max(0, maxI-1); int b1 = 0; int b2 = Math.max(0, maxJ-1); if (storePath) { //figure out the path
ArrayList<Alignment.Operation> backOperations = new ArrayList<>(a.length()+b.length());
marbl/MHAP
src/main/java/edu/umd/marbl/mhap/utils/RandomSequenceGenerator.java
// Path: src/main/java/edu/umd/marbl/mhap/impl/MhapRuntimeException.java // public class MhapRuntimeException extends RuntimeException // { // // /** // * // */ // private static final long serialVersionUID = 56387323839744808L; // // public MhapRuntimeException() // { // super(); // } // // public MhapRuntimeException(String message, Throwable cause) // { // super(message, cause); // } // // public MhapRuntimeException(String message) // { // super(message); // } // // public MhapRuntimeException(Throwable cause) // { // super(cause); // } // // // }
import edu.umd.marbl.mhap.impl.MhapRuntimeException; import java.util.LinkedList; import java.util.ListIterator;
} if (toExclude != null && toExclude.equals(result)) { result = null; } } return result; } public String generateRandomSequence(int length) { StringBuilder str = new StringBuilder(length); for (int iter=0; iter<length; iter++) str.append(getRandomBase(null)); return str.toString(); } //0.1188 0.0183 0.0129 public String addPacBioError(String str) { return addError(str, 0.1188, 0.0183, 0.0129); } public String addError(String str, double insertionRate, double deletionRate, double substitutionRate) { if (insertionRate < 0.0 || deletionRate < 0.0 || substitutionRate < 0.0)
// Path: src/main/java/edu/umd/marbl/mhap/impl/MhapRuntimeException.java // public class MhapRuntimeException extends RuntimeException // { // // /** // * // */ // private static final long serialVersionUID = 56387323839744808L; // // public MhapRuntimeException() // { // super(); // } // // public MhapRuntimeException(String message, Throwable cause) // { // super(message, cause); // } // // public MhapRuntimeException(String message) // { // super(message); // } // // public MhapRuntimeException(Throwable cause) // { // super(cause); // } // // // } // Path: src/main/java/edu/umd/marbl/mhap/utils/RandomSequenceGenerator.java import edu.umd.marbl.mhap.impl.MhapRuntimeException; import java.util.LinkedList; import java.util.ListIterator; } if (toExclude != null && toExclude.equals(result)) { result = null; } } return result; } public String generateRandomSequence(int length) { StringBuilder str = new StringBuilder(length); for (int iter=0; iter<length; iter++) str.append(getRandomBase(null)); return str.toString(); } //0.1188 0.0183 0.0129 public String addPacBioError(String str) { return addError(str, 0.1188, 0.0183, 0.0129); } public String addError(String str, double insertionRate, double deletionRate, double substitutionRate) { if (insertionRate < 0.0 || deletionRate < 0.0 || substitutionRate < 0.0)
throw new MhapRuntimeException("Error rate cannot be negative.");
wso2/carbon-commons
components/logging/org.wso2.carbon.logging.view/src/main/java/org/wso2/carbon/logging/view/internal/CarbonLoggingViewServiceComponent.java
// Path: components/logging/org.wso2.carbon.logging.view/src/main/java/org/wso2/carbon/logging/view/appenders/LoggingAppender.java // public class LoggingAppender implements PaxAppender { // // private CircularBuffer<LogEvent> circularBuffer; // private static String ip; // // static { // try { // InetAddress localHost = InetAddress.getLocalHost(); // ip = localHost.getHostAddress(); // } catch (UnknownHostException var3) { // ip = "127.0.0.1"; // } // } // // public LoggingAppender(CircularBuffer<LogEvent> logBuffer) { // // this.circularBuffer = logBuffer; // } // // public void doAppend(PaxLoggingEvent paxLoggingEvent) { // // LogEvent logEvent = new LogEvent(); // logEvent.setMessage(paxLoggingEvent.getMessage()); // logEvent.setLogger(paxLoggingEvent.getLoggerName()); // logEvent.setPriority(paxLoggingEvent.getLevel().toString()); // SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); // logEvent.setLogTime(simpleDateFormat.format(paxLoggingEvent.getTimeStamp())); // logEvent.setServerName(getServerName()); // logEvent.setTenantId(getTenantId()); // logEvent.setIp(ip); // logEvent.setAppName(getAppName()); // if (paxLoggingEvent.getThrowableStrRep() != null) { // logEvent.setStacktrace(String.join("\n", paxLoggingEvent.getThrowableStrRep())); // } else { // logEvent.setStacktrace(""); // } // circularBuffer.append(logEvent); // } // // private String getServerName() { // // return AccessController.doPrivileged((PrivilegedAction<String>) () -> ServerConfiguration.getInstance().getFirstProperty("ServerKey")); // } // // private String getIp() { // // try { // InetAddress localHost = InetAddress.getLocalHost(); // return localHost.getHostAddress(); // } catch (UnknownHostException var3) { // return "127.0.0.1"; // } // } // // private String getTenantId() { // // int tenantId = // AccessController.doPrivileged((PrivilegedAction<Integer>) () -> CarbonContext.getThreadLocalCarbonContext().getTenantId()); // return String.valueOf(tenantId); // } // // private String getAppName() { // // String appName = CarbonContext.getThreadLocalCarbonContext().getApplicationName(); // return appName != null ? appName : ""; // } // // }
import org.ops4j.pax.logging.spi.PaxAppender; import org.osgi.service.component.ComponentContext; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.wso2.carbon.logging.view.appenders.LoggingAppender; import java.util.Hashtable;
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.logging.view.internal; /** * Log Viewer Service Component. */ @Component(name = "org.wso2.carbon.logging.view.component", immediate = true) public class CarbonLoggingViewServiceComponent { @Activate protected void activate(ComponentContext componentContext) {
// Path: components/logging/org.wso2.carbon.logging.view/src/main/java/org/wso2/carbon/logging/view/appenders/LoggingAppender.java // public class LoggingAppender implements PaxAppender { // // private CircularBuffer<LogEvent> circularBuffer; // private static String ip; // // static { // try { // InetAddress localHost = InetAddress.getLocalHost(); // ip = localHost.getHostAddress(); // } catch (UnknownHostException var3) { // ip = "127.0.0.1"; // } // } // // public LoggingAppender(CircularBuffer<LogEvent> logBuffer) { // // this.circularBuffer = logBuffer; // } // // public void doAppend(PaxLoggingEvent paxLoggingEvent) { // // LogEvent logEvent = new LogEvent(); // logEvent.setMessage(paxLoggingEvent.getMessage()); // logEvent.setLogger(paxLoggingEvent.getLoggerName()); // logEvent.setPriority(paxLoggingEvent.getLevel().toString()); // SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); // logEvent.setLogTime(simpleDateFormat.format(paxLoggingEvent.getTimeStamp())); // logEvent.setServerName(getServerName()); // logEvent.setTenantId(getTenantId()); // logEvent.setIp(ip); // logEvent.setAppName(getAppName()); // if (paxLoggingEvent.getThrowableStrRep() != null) { // logEvent.setStacktrace(String.join("\n", paxLoggingEvent.getThrowableStrRep())); // } else { // logEvent.setStacktrace(""); // } // circularBuffer.append(logEvent); // } // // private String getServerName() { // // return AccessController.doPrivileged((PrivilegedAction<String>) () -> ServerConfiguration.getInstance().getFirstProperty("ServerKey")); // } // // private String getIp() { // // try { // InetAddress localHost = InetAddress.getLocalHost(); // return localHost.getHostAddress(); // } catch (UnknownHostException var3) { // return "127.0.0.1"; // } // } // // private String getTenantId() { // // int tenantId = // AccessController.doPrivileged((PrivilegedAction<Integer>) () -> CarbonContext.getThreadLocalCarbonContext().getTenantId()); // return String.valueOf(tenantId); // } // // private String getAppName() { // // String appName = CarbonContext.getThreadLocalCarbonContext().getApplicationName(); // return appName != null ? appName : ""; // } // // } // Path: components/logging/org.wso2.carbon.logging.view/src/main/java/org/wso2/carbon/logging/view/internal/CarbonLoggingViewServiceComponent.java import org.ops4j.pax.logging.spi.PaxAppender; import org.osgi.service.component.ComponentContext; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.wso2.carbon.logging.view.appenders.LoggingAppender; import java.util.Hashtable; /* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.logging.view.internal; /** * Log Viewer Service Component. */ @Component(name = "org.wso2.carbon.logging.view.component", immediate = true) public class CarbonLoggingViewServiceComponent { @Activate protected void activate(ComponentContext componentContext) {
LoggingAppender loggingAppender = new LoggingAppender(DataHolder.getInstance().getLogBuffer());
wso2/carbon-commons
components/logging/org.wso2.carbon.logging.view.ui/src/main/java/org/wso2/carbon/logging/view/ui/LogFileProvider.java
// Path: components/logging/org.wso2.carbon.logging.view.ui/src/main/java/org/wso2/carbon/logging/view/ui/data/LogFileInfo.java // public class LogFileInfo { // // private String logName; // private String logDate; // private String fileSize; // // public LogFileInfo(String logName, String logDate, String fileSize) { // this.logName = logName; // this.logDate = logDate; // this.fileSize = fileSize; // } // // public String getLogName() { // return logName; // } // // public void setLogName(String logName) { // this.logName = logName; // } // // public String getLogDate() { // return logDate; // } // // public void setLogDate(String logDate) { // this.logDate = logDate; // } // // public String getFileSize() { // return fileSize; // } // // public void setFileSize(String fileSize) { // this.fileSize = fileSize; // } // } // // Path: components/logging/org.wso2.carbon.logging.view.ui/src/main/java/org/wso2/carbon/logging/view/ui/util/LoggingConstants.java // public final class LoggingConstants { // // public static final String URL_SEPARATOR = "/"; // public static final String WSO2_STRATOS_MANAGER = "manager"; // public static final String CONFIG_FILENAME = "cloud-services-desc.xml"; // public static final String MULTITENANCY_CONFIG_FOLDER = "multitenancy"; // // public static final class RegexPatterns { // // public static final String LOCAL_CARBON_LOG_PATTERN = "wso2carbon*.log"; // public static final String LOG_FILE_DATE_SEPARATOR = "wso2carbon-"; // public static final String CURRENT_LOG = "0_Current Log"; // } // }
import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.logging.view.ui.data.LogFileInfo; import org.wso2.carbon.logging.view.ui.util.LoggingConstants; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import java.io.BufferedInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.activation.DataHandler; import javax.mail.util.ByteArrayDataSource;
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.logging.view.ui; /** * This class will handle log file related operations. */ public class LogFileProvider { private static final Log log = LogFactory.getLog(LogFileProvider.class); private static final String SERVER_KEY = "ServerKey"; private static final String APPLICATION_TYPE_ZIP = "application/zip"; /** * This method will return the information of log files in repository/logs. * * @param tenantDomain - Tenant domain eg: t1.com. * @param serverKey Server name. * @return Info list of log files. */
// Path: components/logging/org.wso2.carbon.logging.view.ui/src/main/java/org/wso2/carbon/logging/view/ui/data/LogFileInfo.java // public class LogFileInfo { // // private String logName; // private String logDate; // private String fileSize; // // public LogFileInfo(String logName, String logDate, String fileSize) { // this.logName = logName; // this.logDate = logDate; // this.fileSize = fileSize; // } // // public String getLogName() { // return logName; // } // // public void setLogName(String logName) { // this.logName = logName; // } // // public String getLogDate() { // return logDate; // } // // public void setLogDate(String logDate) { // this.logDate = logDate; // } // // public String getFileSize() { // return fileSize; // } // // public void setFileSize(String fileSize) { // this.fileSize = fileSize; // } // } // // Path: components/logging/org.wso2.carbon.logging.view.ui/src/main/java/org/wso2/carbon/logging/view/ui/util/LoggingConstants.java // public final class LoggingConstants { // // public static final String URL_SEPARATOR = "/"; // public static final String WSO2_STRATOS_MANAGER = "manager"; // public static final String CONFIG_FILENAME = "cloud-services-desc.xml"; // public static final String MULTITENANCY_CONFIG_FOLDER = "multitenancy"; // // public static final class RegexPatterns { // // public static final String LOCAL_CARBON_LOG_PATTERN = "wso2carbon*.log"; // public static final String LOG_FILE_DATE_SEPARATOR = "wso2carbon-"; // public static final String CURRENT_LOG = "0_Current Log"; // } // } // Path: components/logging/org.wso2.carbon.logging.view.ui/src/main/java/org/wso2/carbon/logging/view/ui/LogFileProvider.java import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.logging.view.ui.data.LogFileInfo; import org.wso2.carbon.logging.view.ui.util.LoggingConstants; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import java.io.BufferedInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.activation.DataHandler; import javax.mail.util.ByteArrayDataSource; /* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.logging.view.ui; /** * This class will handle log file related operations. */ public class LogFileProvider { private static final Log log = LogFactory.getLog(LogFileProvider.class); private static final String SERVER_KEY = "ServerKey"; private static final String APPLICATION_TYPE_ZIP = "application/zip"; /** * This method will return the information of log files in repository/logs. * * @param tenantDomain - Tenant domain eg: t1.com. * @param serverKey Server name. * @return Info list of log files. */
public List<LogFileInfo> getLogFileInfoList(String tenantDomain, String serverKey) {
wso2/carbon-commons
components/logging/org.wso2.carbon.logging.view.ui/src/main/java/org/wso2/carbon/logging/view/ui/LogFileProvider.java
// Path: components/logging/org.wso2.carbon.logging.view.ui/src/main/java/org/wso2/carbon/logging/view/ui/data/LogFileInfo.java // public class LogFileInfo { // // private String logName; // private String logDate; // private String fileSize; // // public LogFileInfo(String logName, String logDate, String fileSize) { // this.logName = logName; // this.logDate = logDate; // this.fileSize = fileSize; // } // // public String getLogName() { // return logName; // } // // public void setLogName(String logName) { // this.logName = logName; // } // // public String getLogDate() { // return logDate; // } // // public void setLogDate(String logDate) { // this.logDate = logDate; // } // // public String getFileSize() { // return fileSize; // } // // public void setFileSize(String fileSize) { // this.fileSize = fileSize; // } // } // // Path: components/logging/org.wso2.carbon.logging.view.ui/src/main/java/org/wso2/carbon/logging/view/ui/util/LoggingConstants.java // public final class LoggingConstants { // // public static final String URL_SEPARATOR = "/"; // public static final String WSO2_STRATOS_MANAGER = "manager"; // public static final String CONFIG_FILENAME = "cloud-services-desc.xml"; // public static final String MULTITENANCY_CONFIG_FOLDER = "multitenancy"; // // public static final class RegexPatterns { // // public static final String LOCAL_CARBON_LOG_PATTERN = "wso2carbon*.log"; // public static final String LOG_FILE_DATE_SEPARATOR = "wso2carbon-"; // public static final String CURRENT_LOG = "0_Current Log"; // } // }
import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.logging.view.ui.data.LogFileInfo; import org.wso2.carbon.logging.view.ui.util.LoggingConstants; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import java.io.BufferedInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.activation.DataHandler; import javax.mail.util.ByteArrayDataSource;
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.logging.view.ui; /** * This class will handle log file related operations. */ public class LogFileProvider { private static final Log log = LogFactory.getLog(LogFileProvider.class); private static final String SERVER_KEY = "ServerKey"; private static final String APPLICATION_TYPE_ZIP = "application/zip"; /** * This method will return the information of log files in repository/logs. * * @param tenantDomain - Tenant domain eg: t1.com. * @param serverKey Server name. * @return Info list of log files. */ public List<LogFileInfo> getLogFileInfoList(String tenantDomain, String serverKey) { String folderPath = CarbonUtils.getCarbonLogsPath(); List<LogFileInfo> logs = new ArrayList<>(); LogFileInfo logFileInfo; String currentServerName = getCurrentServerName(); if ((((tenantDomain == null || "".equals(tenantDomain)) && isSuperTenantUser()) || (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME .equalsIgnoreCase(tenantDomain))) && (serverKey == null || "".equals(serverKey) || serverKey.equalsIgnoreCase( currentServerName))) { File folder = new File(folderPath);
// Path: components/logging/org.wso2.carbon.logging.view.ui/src/main/java/org/wso2/carbon/logging/view/ui/data/LogFileInfo.java // public class LogFileInfo { // // private String logName; // private String logDate; // private String fileSize; // // public LogFileInfo(String logName, String logDate, String fileSize) { // this.logName = logName; // this.logDate = logDate; // this.fileSize = fileSize; // } // // public String getLogName() { // return logName; // } // // public void setLogName(String logName) { // this.logName = logName; // } // // public String getLogDate() { // return logDate; // } // // public void setLogDate(String logDate) { // this.logDate = logDate; // } // // public String getFileSize() { // return fileSize; // } // // public void setFileSize(String fileSize) { // this.fileSize = fileSize; // } // } // // Path: components/logging/org.wso2.carbon.logging.view.ui/src/main/java/org/wso2/carbon/logging/view/ui/util/LoggingConstants.java // public final class LoggingConstants { // // public static final String URL_SEPARATOR = "/"; // public static final String WSO2_STRATOS_MANAGER = "manager"; // public static final String CONFIG_FILENAME = "cloud-services-desc.xml"; // public static final String MULTITENANCY_CONFIG_FOLDER = "multitenancy"; // // public static final class RegexPatterns { // // public static final String LOCAL_CARBON_LOG_PATTERN = "wso2carbon*.log"; // public static final String LOG_FILE_DATE_SEPARATOR = "wso2carbon-"; // public static final String CURRENT_LOG = "0_Current Log"; // } // } // Path: components/logging/org.wso2.carbon.logging.view.ui/src/main/java/org/wso2/carbon/logging/view/ui/LogFileProvider.java import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.logging.view.ui.data.LogFileInfo; import org.wso2.carbon.logging.view.ui.util.LoggingConstants; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import java.io.BufferedInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.activation.DataHandler; import javax.mail.util.ByteArrayDataSource; /* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.logging.view.ui; /** * This class will handle log file related operations. */ public class LogFileProvider { private static final Log log = LogFactory.getLog(LogFileProvider.class); private static final String SERVER_KEY = "ServerKey"; private static final String APPLICATION_TYPE_ZIP = "application/zip"; /** * This method will return the information of log files in repository/logs. * * @param tenantDomain - Tenant domain eg: t1.com. * @param serverKey Server name. * @return Info list of log files. */ public List<LogFileInfo> getLogFileInfoList(String tenantDomain, String serverKey) { String folderPath = CarbonUtils.getCarbonLogsPath(); List<LogFileInfo> logs = new ArrayList<>(); LogFileInfo logFileInfo; String currentServerName = getCurrentServerName(); if ((((tenantDomain == null || "".equals(tenantDomain)) && isSuperTenantUser()) || (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME .equalsIgnoreCase(tenantDomain))) && (serverKey == null || "".equals(serverKey) || serverKey.equalsIgnoreCase( currentServerName))) { File folder = new File(folderPath);
FileFilter fileFilter = new WildcardFileFilter(LoggingConstants.RegexPatterns.LOCAL_CARBON_LOG_PATTERN);
wso2/carbon-commons
components/logging/org.wso2.carbon.logging.view/src/main/java/org/wso2/carbon/logging/view/services/LogViewerService.java
// Path: components/logging/org.wso2.carbon.logging.view/src/main/java/org/wso2/carbon/logging/view/data/LogEvent.java // public class LogEvent { // // private String key; // private String tenantId; // private String serverName; // private String appName; // private String logTime; // private String logger; // private String priority; // private String message; // private String ip; // private String stacktrace; // private String instance; // // public LogEvent() { // // } // // public String getKey() { // // return key; // } // // public void setKey(String key) { // // this.key = key; // } // // public String getTenantId() { // // return tenantId; // } // // public void setTenantId(String tenantId) { // // this.tenantId = tenantId; // } // // public String getServerName() { // // return serverName; // } // // public void setServerName(String serverName) { // // this.serverName = serverName; // } // // public String getAppName() { // // return appName; // } // // public void setAppName(String appName) { // // this.appName = appName; // } // // public String getLogTime() { // // return logTime; // } // // public void setLogTime(String logTime) { // // this.logTime = logTime; // } // // public String getLogger() { // // return logger; // } // // public void setLogger(String logger) { // // this.logger = logger; // } // // public String getPriority() { // // return priority; // } // // public void setPriority(String priority) { // // this.priority = priority; // } // // public String getMessage() { // // return message; // } // // public void setMessage(String message) { // // this.message = message; // } // // public String getIp() { // // return ip; // } // // public void setIp(String ip) { // // this.ip = ip; // } // // public String getStacktrace() { // // return stacktrace; // } // // public void setStacktrace(String stacktrace) { // // this.stacktrace = stacktrace; // } // // public String getInstance() { // // return instance; // } // // public void setInstance(String instance) { // // this.instance = instance; // } // } // // Path: components/logging/org.wso2.carbon.logging.view/src/main/java/org/wso2/carbon/logging/view/internal/DataHolder.java // public class DataHolder { // // private CircularBuffer<LogEvent> logBuffer = new CircularBuffer<>(2000); // // private static final DataHolder instance = new DataHolder(); // // private DataHolder() { // // } // // public CircularBuffer<LogEvent> getLogBuffer() { // // return logBuffer; // } // // public static DataHolder getInstance() { // // return instance; // } // }
import java.util.List; import org.wso2.carbon.logging.view.data.LogEvent; import org.wso2.carbon.logging.view.internal.DataHolder;
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.logging.view.services; /** * Log Viewer Service */ public class LogViewerService { /** * Return all logs in system * @return array of {@link LogEvent} */ public LogEvent[] getAllSystemLogs() {
// Path: components/logging/org.wso2.carbon.logging.view/src/main/java/org/wso2/carbon/logging/view/data/LogEvent.java // public class LogEvent { // // private String key; // private String tenantId; // private String serverName; // private String appName; // private String logTime; // private String logger; // private String priority; // private String message; // private String ip; // private String stacktrace; // private String instance; // // public LogEvent() { // // } // // public String getKey() { // // return key; // } // // public void setKey(String key) { // // this.key = key; // } // // public String getTenantId() { // // return tenantId; // } // // public void setTenantId(String tenantId) { // // this.tenantId = tenantId; // } // // public String getServerName() { // // return serverName; // } // // public void setServerName(String serverName) { // // this.serverName = serverName; // } // // public String getAppName() { // // return appName; // } // // public void setAppName(String appName) { // // this.appName = appName; // } // // public String getLogTime() { // // return logTime; // } // // public void setLogTime(String logTime) { // // this.logTime = logTime; // } // // public String getLogger() { // // return logger; // } // // public void setLogger(String logger) { // // this.logger = logger; // } // // public String getPriority() { // // return priority; // } // // public void setPriority(String priority) { // // this.priority = priority; // } // // public String getMessage() { // // return message; // } // // public void setMessage(String message) { // // this.message = message; // } // // public String getIp() { // // return ip; // } // // public void setIp(String ip) { // // this.ip = ip; // } // // public String getStacktrace() { // // return stacktrace; // } // // public void setStacktrace(String stacktrace) { // // this.stacktrace = stacktrace; // } // // public String getInstance() { // // return instance; // } // // public void setInstance(String instance) { // // this.instance = instance; // } // } // // Path: components/logging/org.wso2.carbon.logging.view/src/main/java/org/wso2/carbon/logging/view/internal/DataHolder.java // public class DataHolder { // // private CircularBuffer<LogEvent> logBuffer = new CircularBuffer<>(2000); // // private static final DataHolder instance = new DataHolder(); // // private DataHolder() { // // } // // public CircularBuffer<LogEvent> getLogBuffer() { // // return logBuffer; // } // // public static DataHolder getInstance() { // // return instance; // } // } // Path: components/logging/org.wso2.carbon.logging.view/src/main/java/org/wso2/carbon/logging/view/services/LogViewerService.java import java.util.List; import org.wso2.carbon.logging.view.data.LogEvent; import org.wso2.carbon.logging.view.internal.DataHolder; /* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.logging.view.services; /** * Log Viewer Service */ public class LogViewerService { /** * Return all logs in system * @return array of {@link LogEvent} */ public LogEvent[] getAllSystemLogs() {
List<LogEvent> logEventList = DataHolder.getInstance().getLogBuffer().get(2000);
wso2/carbon-commons
components/ntask/org.wso2.carbon.ntask.core/src/main/java/org/wso2/carbon/ntask/core/service/impl/TaskServiceXMLConfiguration.java
// Path: components/ntask/org.wso2.carbon.ntask.core/src/main/java/org/wso2/carbon/ntask/core/service/TaskService.java // public static enum TaskServerMode { // STANDALONE, CLUSTERED, REMOTE, AUTO // }
import org.wso2.carbon.ntask.core.service.TaskService.TaskServerMode; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlValue;
/** * Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.ntask.core.service.impl; /** * This represents the task service XML based configuration. */ @XmlRootElement(name = "tasks-configuration") public class TaskServiceXMLConfiguration {
// Path: components/ntask/org.wso2.carbon.ntask.core/src/main/java/org/wso2/carbon/ntask/core/service/TaskService.java // public static enum TaskServerMode { // STANDALONE, CLUSTERED, REMOTE, AUTO // } // Path: components/ntask/org.wso2.carbon.ntask.core/src/main/java/org/wso2/carbon/ntask/core/service/impl/TaskServiceXMLConfiguration.java import org.wso2.carbon.ntask.core.service.TaskService.TaskServerMode; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlValue; /** * Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.ntask.core.service.impl; /** * This represents the task service XML based configuration. */ @XmlRootElement(name = "tasks-configuration") public class TaskServiceXMLConfiguration {
private TaskServerMode taskServerMode;
wso2/carbon-commons
components/caching-invalidator/org.wso2.carbon.caching.invalidator/src/main/java/org/wso2/carbon/caching/invalidator/internal/CacheInvalidationServiceComponent.java
// Path: components/caching-invalidator/org.wso2.carbon.caching.invalidator/src/main/java/org/wso2/carbon/caching/invalidator/amqp/ConfigurationManager.java // public class ConfigurationManager { // private static final Log log = LogFactory.getLog(ConfigurationManager.class); // // private static String topicName = null; // private static String providerUrl = null; // private static String providerPort = null; // private static String providerUsername = null; // private static String providerPassword = null; // private static boolean subscribed = false; // // private static List<String> sentMsgBuffer; // // public static boolean init(){ // boolean propertyExists = false; // providerUrl = null; // // String configFilePath = Paths.get(CarbonUtils.getCarbonConfigDirPath(), "cache.xml").toString(); // try{ // StAXOMBuilder stAXOMBuilder = new StAXOMBuilder(new FileInputStream(configFilePath)); // OMElement documentElement = stAXOMBuilder.getDocumentElement(); // Iterator iterator; // // iterator = documentElement.getChildrenWithName(new QName("providerUrl")); // // if(iterator.hasNext()){ // OMElement cache = (OMElement) iterator.next(); // providerUrl = cache.getText(); // } // // iterator = documentElement.getChildrenWithName(new QName("cacheInvalidateTopic")); // // if(iterator.hasNext()){ // OMElement cache = (OMElement) iterator.next(); // topicName = cache.getText(); // } // // iterator = documentElement.getChildrenWithName(new QName("providerPort")); // // if(iterator.hasNext()){ // OMElement cache = (OMElement) iterator.next(); // providerPort = cache.getText(); // } // // if(providerPort == null || providerPort.equals("")){ // providerPort="5672"; //default // } // // iterator = documentElement.getChildrenWithName(new QName("providerUsername")); // // if(iterator.hasNext()){ // OMElement cache = (OMElement) iterator.next(); // providerUsername = cache.getText(); // } // // if(providerUsername == null || providerUsername.equals("")){ // providerUsername="guest"; //default // } // // iterator = documentElement.getChildrenWithName(new QName("providerPassword")); // // if(iterator.hasNext()){ // OMElement cache = (OMElement) iterator.next(); // providerPassword = cache.getText(); // } // // if(providerPassword == null || providerPassword.equals("")){ // providerPassword="guest"; //default // } // // propertyExists = providerUrl != null && !providerUrl.equals(""); // propertyExists &= topicName != null && !topicName.equals(""); // // if(!propertyExists){ // log.info("Global cache invalidation is offline according to cache.xml configurations"); // } // // }catch (Exception e){ // log.info("Global cache invalidation is offline according to cache.xml configurations"); // } // return propertyExists; // } // // public static String getTopicName() { // return topicName; // } // // public static String getProviderUrl() { // return providerUrl; // } // // public static String getProviderPort() { // return providerPort; // } // // public static String getProviderUsername() { // return providerUsername; // } // // public static String getProviderPassword() { // return providerPassword; // } // // public static List<String> getSentMsgBuffer() { // if(sentMsgBuffer == null){ // sentMsgBuffer = new ArrayList<String>(); // } // return sentMsgBuffer; // } // // public static boolean isSubscribed() { // return subscribed; // } // // public static void setSubscribed(boolean subscribed) { // ConfigurationManager.subscribed = subscribed; // } // }
import org.wso2.carbon.utils.ConfigurationContextService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.ComponentContext; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.wso2.carbon.caching.impl.CacheInvalidator; import org.wso2.carbon.caching.invalidator.amqp.CacheInvalidationPublisher; import org.wso2.carbon.caching.invalidator.amqp.CacheInvalidationSubscriber; import org.wso2.carbon.caching.invalidator.amqp.ConfigurationManager; import org.wso2.carbon.core.clustering.api.CoordinatedActivity;
/* * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.caching.invalidator.internal; @Component( name = "org.wso2.carbon.caching.invalidator.internal.CacheInvalidationServiceComponent", immediate = true) public class CacheInvalidationServiceComponent { private static Log log = LogFactory.getLog(CacheInvalidationServiceComponent.class); ServiceRegistration serviceRegistration; CacheInvalidationSubscriber subscriber; CacheInvalidationPublisher publisher; @Activate protected void activate(ComponentContext ctxt) { log.info("Initializing the CacheInvalidationServiceComponent..."); try {
// Path: components/caching-invalidator/org.wso2.carbon.caching.invalidator/src/main/java/org/wso2/carbon/caching/invalidator/amqp/ConfigurationManager.java // public class ConfigurationManager { // private static final Log log = LogFactory.getLog(ConfigurationManager.class); // // private static String topicName = null; // private static String providerUrl = null; // private static String providerPort = null; // private static String providerUsername = null; // private static String providerPassword = null; // private static boolean subscribed = false; // // private static List<String> sentMsgBuffer; // // public static boolean init(){ // boolean propertyExists = false; // providerUrl = null; // // String configFilePath = Paths.get(CarbonUtils.getCarbonConfigDirPath(), "cache.xml").toString(); // try{ // StAXOMBuilder stAXOMBuilder = new StAXOMBuilder(new FileInputStream(configFilePath)); // OMElement documentElement = stAXOMBuilder.getDocumentElement(); // Iterator iterator; // // iterator = documentElement.getChildrenWithName(new QName("providerUrl")); // // if(iterator.hasNext()){ // OMElement cache = (OMElement) iterator.next(); // providerUrl = cache.getText(); // } // // iterator = documentElement.getChildrenWithName(new QName("cacheInvalidateTopic")); // // if(iterator.hasNext()){ // OMElement cache = (OMElement) iterator.next(); // topicName = cache.getText(); // } // // iterator = documentElement.getChildrenWithName(new QName("providerPort")); // // if(iterator.hasNext()){ // OMElement cache = (OMElement) iterator.next(); // providerPort = cache.getText(); // } // // if(providerPort == null || providerPort.equals("")){ // providerPort="5672"; //default // } // // iterator = documentElement.getChildrenWithName(new QName("providerUsername")); // // if(iterator.hasNext()){ // OMElement cache = (OMElement) iterator.next(); // providerUsername = cache.getText(); // } // // if(providerUsername == null || providerUsername.equals("")){ // providerUsername="guest"; //default // } // // iterator = documentElement.getChildrenWithName(new QName("providerPassword")); // // if(iterator.hasNext()){ // OMElement cache = (OMElement) iterator.next(); // providerPassword = cache.getText(); // } // // if(providerPassword == null || providerPassword.equals("")){ // providerPassword="guest"; //default // } // // propertyExists = providerUrl != null && !providerUrl.equals(""); // propertyExists &= topicName != null && !topicName.equals(""); // // if(!propertyExists){ // log.info("Global cache invalidation is offline according to cache.xml configurations"); // } // // }catch (Exception e){ // log.info("Global cache invalidation is offline according to cache.xml configurations"); // } // return propertyExists; // } // // public static String getTopicName() { // return topicName; // } // // public static String getProviderUrl() { // return providerUrl; // } // // public static String getProviderPort() { // return providerPort; // } // // public static String getProviderUsername() { // return providerUsername; // } // // public static String getProviderPassword() { // return providerPassword; // } // // public static List<String> getSentMsgBuffer() { // if(sentMsgBuffer == null){ // sentMsgBuffer = new ArrayList<String>(); // } // return sentMsgBuffer; // } // // public static boolean isSubscribed() { // return subscribed; // } // // public static void setSubscribed(boolean subscribed) { // ConfigurationManager.subscribed = subscribed; // } // } // Path: components/caching-invalidator/org.wso2.carbon.caching.invalidator/src/main/java/org/wso2/carbon/caching/invalidator/internal/CacheInvalidationServiceComponent.java import org.wso2.carbon.utils.ConfigurationContextService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.ComponentContext; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.wso2.carbon.caching.impl.CacheInvalidator; import org.wso2.carbon.caching.invalidator.amqp.CacheInvalidationPublisher; import org.wso2.carbon.caching.invalidator.amqp.CacheInvalidationSubscriber; import org.wso2.carbon.caching.invalidator.amqp.ConfigurationManager; import org.wso2.carbon.core.clustering.api.CoordinatedActivity; /* * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.caching.invalidator.internal; @Component( name = "org.wso2.carbon.caching.invalidator.internal.CacheInvalidationServiceComponent", immediate = true) public class CacheInvalidationServiceComponent { private static Log log = LogFactory.getLog(CacheInvalidationServiceComponent.class); ServiceRegistration serviceRegistration; CacheInvalidationSubscriber subscriber; CacheInvalidationPublisher publisher; @Activate protected void activate(ComponentContext ctxt) { log.info("Initializing the CacheInvalidationServiceComponent..."); try {
if (ConfigurationManager.init()) {
wso2/carbon-commons
components/tenant-mgt-common/org.wso2.carbon.tenant.common/src/main/java/org/wso2/carbon/stratos/common/exception/TenantManagementClientException.java
// Path: components/tenant-mgt-common/org.wso2.carbon.tenant.common/src/main/java/org/wso2/carbon/stratos/common/constants/TenantConstants.java // public class TenantConstants { // // /** // * Enum for error messages. // */ // public enum ErrorMessage { // // ERROR_CODE_EMPTY_EMAIL("TM-60000", // "Provided email is empty."), // ERROR_CODE_ILLEGAL_EMAIL("TM-60001", // "Wrong characters in the email."), // ERROR_CODE_INVALID_EMAIL("TM-60002", // "Invalid email address is provided."), // ERROR_CODE_UNAVAILABLE_DOMAIN("TM-60003", "You can not use a registry reserved word as a tenant domain. " + // "Please choose a different one."), // ERROR_CODE_EMPTY_DOMAIN_NAME("TM-60004", // "Provided domain name is empty."), // ERROR_CODE_EMPTY_EXTENSION("TM-60005", // "You should have an extension to your domain."), // ERROR_CODE_INVALID_DOMAIN("TM-60006", // "Invalid domain. Domain should not start with '.'"), // ERROR_CODE_ILLEGAL_CHARACTERS_IN_DOMAIN("TM-60007", // "The tenant domain %s contains one or more illegal characters. The valid characters are lowercase " + // "letters, numbers, '.', '-' and '_'."), // ERROR_CODE_EXISTING_USER_NAME("TM-60008", // "User name : %s exists in the system. Please pick another user name for tenant Administrator."), // ERROR_CODE_EXISTING_DOMAIN("TM-60009", // "A tenant with same domain %s already exist. Please use a different domain name."), // ERROR_CODE_INVALID_LIMIT("TM-60010", "Limit should not be negative."), // ERROR_CODE_INVALID_OFFSET("TM-60011", "Offset should not be negative."), // ERROR_CODE_OWNER_REQUIRED("TM-60012", "Required parameter owner is not specified."), // ERROR_CODE_MISSING_REQUIRED_PARAMETER("TM-60013", "Required parameter %s is not specified."), // ERROR_CODE_RESOURCE_NOT_FOUND("TM-60014", "Tenant cannot be found for the provided id: %s."), // ERROR_CODE_DOMAIN_NOT_FOUND("TM-60015", "Tenant cannot be found for the provided domain: %s."), // ERROR_CODE_TENANT_DELETION_NOT_ENABLED("TM-60016", "Tenant deletion property Tenant.TenantDelete is not " + // "enabled in carbon.xml file."), // ERROR_CODE_TENANT_DOES_NOT_MATCH_REGEX_PATTERN("TM-60017", "Invalid tenant domain: %s. " + // "Domain should match the regex pattern %s."), // ERROR_CODE_PRE_TENANT_CREATION_FAILED("TM-60018", "Error occurred in tenant pre creation."), // ERROR_CODE_TENANT_LIMIT_REACHED("TM-60019", "Maximum tenant limit reached."); // // private final String code; // private final String message; // // ErrorMessage(String code, String message) { // // this.code = code; // this.message = message; // } // // public String getCode() { // return code; // } // // public String getMessage() { // return message; // } // } // }
import org.wso2.carbon.stratos.common.constants.TenantConstants;
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.stratos.common.exception; /** * A custom Java {@code TenantManagementClientException} class used for the tenant management client error handling. */ public class TenantManagementClientException extends TenantMgtException { public TenantManagementClientException(String errorCode, String errorDescription) { super(errorCode, errorDescription); }
// Path: components/tenant-mgt-common/org.wso2.carbon.tenant.common/src/main/java/org/wso2/carbon/stratos/common/constants/TenantConstants.java // public class TenantConstants { // // /** // * Enum for error messages. // */ // public enum ErrorMessage { // // ERROR_CODE_EMPTY_EMAIL("TM-60000", // "Provided email is empty."), // ERROR_CODE_ILLEGAL_EMAIL("TM-60001", // "Wrong characters in the email."), // ERROR_CODE_INVALID_EMAIL("TM-60002", // "Invalid email address is provided."), // ERROR_CODE_UNAVAILABLE_DOMAIN("TM-60003", "You can not use a registry reserved word as a tenant domain. " + // "Please choose a different one."), // ERROR_CODE_EMPTY_DOMAIN_NAME("TM-60004", // "Provided domain name is empty."), // ERROR_CODE_EMPTY_EXTENSION("TM-60005", // "You should have an extension to your domain."), // ERROR_CODE_INVALID_DOMAIN("TM-60006", // "Invalid domain. Domain should not start with '.'"), // ERROR_CODE_ILLEGAL_CHARACTERS_IN_DOMAIN("TM-60007", // "The tenant domain %s contains one or more illegal characters. The valid characters are lowercase " + // "letters, numbers, '.', '-' and '_'."), // ERROR_CODE_EXISTING_USER_NAME("TM-60008", // "User name : %s exists in the system. Please pick another user name for tenant Administrator."), // ERROR_CODE_EXISTING_DOMAIN("TM-60009", // "A tenant with same domain %s already exist. Please use a different domain name."), // ERROR_CODE_INVALID_LIMIT("TM-60010", "Limit should not be negative."), // ERROR_CODE_INVALID_OFFSET("TM-60011", "Offset should not be negative."), // ERROR_CODE_OWNER_REQUIRED("TM-60012", "Required parameter owner is not specified."), // ERROR_CODE_MISSING_REQUIRED_PARAMETER("TM-60013", "Required parameter %s is not specified."), // ERROR_CODE_RESOURCE_NOT_FOUND("TM-60014", "Tenant cannot be found for the provided id: %s."), // ERROR_CODE_DOMAIN_NOT_FOUND("TM-60015", "Tenant cannot be found for the provided domain: %s."), // ERROR_CODE_TENANT_DELETION_NOT_ENABLED("TM-60016", "Tenant deletion property Tenant.TenantDelete is not " + // "enabled in carbon.xml file."), // ERROR_CODE_TENANT_DOES_NOT_MATCH_REGEX_PATTERN("TM-60017", "Invalid tenant domain: %s. " + // "Domain should match the regex pattern %s."), // ERROR_CODE_PRE_TENANT_CREATION_FAILED("TM-60018", "Error occurred in tenant pre creation."), // ERROR_CODE_TENANT_LIMIT_REACHED("TM-60019", "Maximum tenant limit reached."); // // private final String code; // private final String message; // // ErrorMessage(String code, String message) { // // this.code = code; // this.message = message; // } // // public String getCode() { // return code; // } // // public String getMessage() { // return message; // } // } // } // Path: components/tenant-mgt-common/org.wso2.carbon.tenant.common/src/main/java/org/wso2/carbon/stratos/common/exception/TenantManagementClientException.java import org.wso2.carbon.stratos.common.constants.TenantConstants; /* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.stratos.common.exception; /** * A custom Java {@code TenantManagementClientException} class used for the tenant management client error handling. */ public class TenantManagementClientException extends TenantMgtException { public TenantManagementClientException(String errorCode, String errorDescription) { super(errorCode, errorDescription); }
public TenantManagementClientException(TenantConstants.ErrorMessage error) {
wso2/carbon-commons
components/logging/org.wso2.carbon.logging.updater/src/main/java/org/wso2/carbon/logging/updater/LogConfigUpdater.java
// Path: components/logging/org.wso2.carbon.logging.updater/src/main/java/org/wso2/carbon/logging/updater/internal/DataHolder.java // public class DataHolder { // // private ConfigurationAdmin configurationAdmin; // private ScheduledExecutorService scheduledExecutorService; // private static final DataHolder instance = new DataHolder(); // private FileTime modifiedTime; // // private DataHolder() { // // } // // public ConfigurationAdmin getConfigurationAdmin() { // // return configurationAdmin; // } // // public static DataHolder getInstance() { // // return instance; // } // // public void setConfigurationAdmin(ConfigurationAdmin configurationAdmin) { // // this.configurationAdmin = configurationAdmin; // } // // public void setScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) { // // this.scheduledExecutorService = scheduledExecutorService; // } // // public ScheduledExecutorService getScheduledExecutorService() { // // return scheduledExecutorService; // } // // public FileTime getModifiedTime() { // // return modifiedTime; // } // // public void setModifiedTime(FileTime modifiedTime) { // // this.modifiedTime = modifiedTime; // } // }
import java.io.FileInputStream; import java.io.IOException; import java.nio.file.attribute.FileTime; import java.util.Dictionary; import java.util.Hashtable; import java.util.Properties; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.ops4j.pax.logging.PaxLoggingConstants; import org.osgi.framework.Constants; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.wso2.carbon.logging.updater.internal.DataHolder; import java.io.File;
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.logging.updater; /** * Logging configuration updater implementation to check and update pax-logging configuration realtime. */ public class LogConfigUpdater implements Runnable { static final Log LOG = LogFactory.getLog(LogConfigUpdater.class); private ConfigurationAdmin configurationAdmin; public LogConfigUpdater(ConfigurationAdmin configurationAdmin) { this.configurationAdmin = configurationAdmin; } @Override public void run() { try { FileTime modifiedTime = LoggingUpdaterUtil.readModifiedTime();
// Path: components/logging/org.wso2.carbon.logging.updater/src/main/java/org/wso2/carbon/logging/updater/internal/DataHolder.java // public class DataHolder { // // private ConfigurationAdmin configurationAdmin; // private ScheduledExecutorService scheduledExecutorService; // private static final DataHolder instance = new DataHolder(); // private FileTime modifiedTime; // // private DataHolder() { // // } // // public ConfigurationAdmin getConfigurationAdmin() { // // return configurationAdmin; // } // // public static DataHolder getInstance() { // // return instance; // } // // public void setConfigurationAdmin(ConfigurationAdmin configurationAdmin) { // // this.configurationAdmin = configurationAdmin; // } // // public void setScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) { // // this.scheduledExecutorService = scheduledExecutorService; // } // // public ScheduledExecutorService getScheduledExecutorService() { // // return scheduledExecutorService; // } // // public FileTime getModifiedTime() { // // return modifiedTime; // } // // public void setModifiedTime(FileTime modifiedTime) { // // this.modifiedTime = modifiedTime; // } // } // Path: components/logging/org.wso2.carbon.logging.updater/src/main/java/org/wso2/carbon/logging/updater/LogConfigUpdater.java import java.io.FileInputStream; import java.io.IOException; import java.nio.file.attribute.FileTime; import java.util.Dictionary; import java.util.Hashtable; import java.util.Properties; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.ops4j.pax.logging.PaxLoggingConstants; import org.osgi.framework.Constants; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.wso2.carbon.logging.updater.internal.DataHolder; import java.io.File; /* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.logging.updater; /** * Logging configuration updater implementation to check and update pax-logging configuration realtime. */ public class LogConfigUpdater implements Runnable { static final Log LOG = LogFactory.getLog(LogConfigUpdater.class); private ConfigurationAdmin configurationAdmin; public LogConfigUpdater(ConfigurationAdmin configurationAdmin) { this.configurationAdmin = configurationAdmin; } @Override public void run() { try { FileTime modifiedTime = LoggingUpdaterUtil.readModifiedTime();
FileTime lastModifiedTime = DataHolder.getInstance().getModifiedTime();
wso2/carbon-commons
components/ntask/org.wso2.carbon.ntask.core/src/main/java/org/wso2/carbon/ntask/core/TaskManager.java
// Path: components/ntask/org.wso2.carbon.ntask.core/src/main/java/org/wso2/carbon/ntask/core/impl/LocalTaskActionListener.java // public interface LocalTaskActionListener { // // /** // * Method to notify when a local task is deleted. // * @param taskName // */ // void notifyLocalTaskDeletion(String taskName); // }
import org.wso2.carbon.ntask.common.TaskException; import org.wso2.carbon.ntask.core.impl.LocalTaskActionListener; import java.util.List;
/** * Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.ntask.core; /** * This interface represents the task manager functionalities. */ public interface TaskManager { /** * Initialize the startup tasks. * @throws TaskException */ public void initStartupTasks() throws TaskException; /** * Starts a task with the given name. * @param taskName The name of the task * @throws TaskException */ public void scheduleTask(String taskName) throws TaskException; /** * Reschedules a task with the given name, only the trigger information will be updated in the * reschedule. * @param taskName The task to be rescheduled * @throws TaskException */ public void rescheduleTask(String taskName) throws TaskException; /** * Stops and deletes a task with the given name. * @param taskName The name of the task * @return true if the task was found and deleted * @throws TaskException */ public boolean deleteTask(String taskName) throws TaskException; /** * Pauses a task with the given name. * @param taskName The name of the task * @throws TaskException */ public void pauseTask(String taskName) throws TaskException; /** * Resumes a paused task with the given name. * @param taskName The name of the task * @throws TaskException */ public void resumeTask(String taskName) throws TaskException; /** * Registers a new task or updates if one already exists. * @param taskInfo The task information * @throws TaskException */ public void registerTask(TaskInfo taskInfo) throws TaskException; /** * Gets tasks state information * @param taskName The name of the task * @return State of the task * @throws TaskException */ public TaskState getTaskState(String taskName) throws TaskException; /** * Get task information. * @param taskName The name of the task * @return The task information * @throws TaskException if the task cannot be found */ public TaskInfo getTask(String taskName) throws TaskException; /** * Get all task information. * @return Task information list * @throws TaskException */ public List<TaskInfo> getAllTasks() throws TaskException; /** * Checks if the given task is already scheduled. * @param taskName The task name * @return true if already scheduled * @throws TaskException */ public boolean isTaskScheduled(String taskName) throws TaskException; /** * Task states. */ public enum TaskState { NORMAL, PAUSED, ERROR, FINISHED, NONE, BLOCKED, UNKNOWN } /** * Registers a listener to be notified when an action is performed on a task. * * @param listener the listener to be notified * @param taskName the name of the task for which the listener should be registered */
// Path: components/ntask/org.wso2.carbon.ntask.core/src/main/java/org/wso2/carbon/ntask/core/impl/LocalTaskActionListener.java // public interface LocalTaskActionListener { // // /** // * Method to notify when a local task is deleted. // * @param taskName // */ // void notifyLocalTaskDeletion(String taskName); // } // Path: components/ntask/org.wso2.carbon.ntask.core/src/main/java/org/wso2/carbon/ntask/core/TaskManager.java import org.wso2.carbon.ntask.common.TaskException; import org.wso2.carbon.ntask.core.impl.LocalTaskActionListener; import java.util.List; /** * Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.ntask.core; /** * This interface represents the task manager functionalities. */ public interface TaskManager { /** * Initialize the startup tasks. * @throws TaskException */ public void initStartupTasks() throws TaskException; /** * Starts a task with the given name. * @param taskName The name of the task * @throws TaskException */ public void scheduleTask(String taskName) throws TaskException; /** * Reschedules a task with the given name, only the trigger information will be updated in the * reschedule. * @param taskName The task to be rescheduled * @throws TaskException */ public void rescheduleTask(String taskName) throws TaskException; /** * Stops and deletes a task with the given name. * @param taskName The name of the task * @return true if the task was found and deleted * @throws TaskException */ public boolean deleteTask(String taskName) throws TaskException; /** * Pauses a task with the given name. * @param taskName The name of the task * @throws TaskException */ public void pauseTask(String taskName) throws TaskException; /** * Resumes a paused task with the given name. * @param taskName The name of the task * @throws TaskException */ public void resumeTask(String taskName) throws TaskException; /** * Registers a new task or updates if one already exists. * @param taskInfo The task information * @throws TaskException */ public void registerTask(TaskInfo taskInfo) throws TaskException; /** * Gets tasks state information * @param taskName The name of the task * @return State of the task * @throws TaskException */ public TaskState getTaskState(String taskName) throws TaskException; /** * Get task information. * @param taskName The name of the task * @return The task information * @throws TaskException if the task cannot be found */ public TaskInfo getTask(String taskName) throws TaskException; /** * Get all task information. * @return Task information list * @throws TaskException */ public List<TaskInfo> getAllTasks() throws TaskException; /** * Checks if the given task is already scheduled. * @param taskName The task name * @return true if already scheduled * @throws TaskException */ public boolean isTaskScheduled(String taskName) throws TaskException; /** * Task states. */ public enum TaskState { NORMAL, PAUSED, ERROR, FINISHED, NONE, BLOCKED, UNKNOWN } /** * Registers a listener to be notified when an action is performed on a task. * * @param listener the listener to be notified * @param taskName the name of the task for which the listener should be registered */
void registerLocalTaskActionListener(LocalTaskActionListener listener, String taskName);
wso2/carbon-commons
components/uuid-generator/org.wso2.carbon.uuid.generator/src/main/java/org/wso2/carbon/uuid/generator/TimeBasedUUIDGenerator.java
// Path: components/uuid-generator/org.wso2.carbon.uuid.generator/src/main/java/org/wso2/carbon/uuid/generator/util/UUIDGeneratorConstants.java // public class UUIDGeneratorConstants { // // public final static int CLOCK_SEQUENCE_HI_BYTE_OFFSET_IN_UUID = 8; // public final static int CLOCK_SEQUENCE_LOW_BYTE_OFFSET_IN_UUID = 9; // // } // // Path: components/uuid-generator/org.wso2.carbon.uuid.generator/src/main/java/org/wso2/carbon/uuid/generator/util/Util.java // public class Util { // // public final static long createClockSeqInLong(byte[] buffer, int offset) { // // long hi = ((long) gatherInt(buffer, offset)) << 32; // long lo = (((long) gatherInt(buffer, offset + 4)) << 32) >>> 32; // return hi | lo; // } // // public static long createUUIDSecondHalfInLong(long l2) { // // l2 = ((l2 << 2) >>> 2); // remove 2 MSB // l2 |= (2L << 62); // set 2 MSB to '10' // return l2; // } // // private final static int gatherInt(byte[] buffer, int offset) { // // return (buffer[offset] << 24) | ((buffer[offset + 1] & 0xFF) << 16) // | ((buffer[offset + 2] & 0xFF) << 8) | (buffer[offset + 3] & 0xFF); // } // // }
import org.wso2.carbon.uuid.generator.util.UUIDGeneratorConstants; import org.wso2.carbon.uuid.generator.util.Util; import java.security.SecureRandom; import java.util.Random; import java.util.UUID;
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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. * * NOTE: The logic in this class is copied from https://github.com/cowtowncoder/java-uuid-generator/, all credits * goes to the original authors of the project https://github.com/cowtowncoder/java-uuid-generator/. */ package org.wso2.carbon.uuid.generator; /** * Class responsible for constructing and generating a time based UUID. */ public class TimeBasedUUIDGenerator extends UUIDGenerator { long address; //Last 8 bytes of the UUID (node id + clock sequence) protected final long uuidSecondHalf; protected final UUIDTimeStamp uuidTimeStamp; public TimeBasedUUIDGenerator(UUIDTimeStamp timeStamp) { byte[] timeBaseduuidByteAray = new byte[16]; constructNodeId(); insertToByteArray(timeBaseduuidByteAray, 10); int clockSequence = timeStamp.getClockSequence(); //set clock_seq_hi.The high field of the clock sequence.
// Path: components/uuid-generator/org.wso2.carbon.uuid.generator/src/main/java/org/wso2/carbon/uuid/generator/util/UUIDGeneratorConstants.java // public class UUIDGeneratorConstants { // // public final static int CLOCK_SEQUENCE_HI_BYTE_OFFSET_IN_UUID = 8; // public final static int CLOCK_SEQUENCE_LOW_BYTE_OFFSET_IN_UUID = 9; // // } // // Path: components/uuid-generator/org.wso2.carbon.uuid.generator/src/main/java/org/wso2/carbon/uuid/generator/util/Util.java // public class Util { // // public final static long createClockSeqInLong(byte[] buffer, int offset) { // // long hi = ((long) gatherInt(buffer, offset)) << 32; // long lo = (((long) gatherInt(buffer, offset + 4)) << 32) >>> 32; // return hi | lo; // } // // public static long createUUIDSecondHalfInLong(long l2) { // // l2 = ((l2 << 2) >>> 2); // remove 2 MSB // l2 |= (2L << 62); // set 2 MSB to '10' // return l2; // } // // private final static int gatherInt(byte[] buffer, int offset) { // // return (buffer[offset] << 24) | ((buffer[offset + 1] & 0xFF) << 16) // | ((buffer[offset + 2] & 0xFF) << 8) | (buffer[offset + 3] & 0xFF); // } // // } // Path: components/uuid-generator/org.wso2.carbon.uuid.generator/src/main/java/org/wso2/carbon/uuid/generator/TimeBasedUUIDGenerator.java import org.wso2.carbon.uuid.generator.util.UUIDGeneratorConstants; import org.wso2.carbon.uuid.generator.util.Util; import java.security.SecureRandom; import java.util.Random; import java.util.UUID; /* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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. * * NOTE: The logic in this class is copied from https://github.com/cowtowncoder/java-uuid-generator/, all credits * goes to the original authors of the project https://github.com/cowtowncoder/java-uuid-generator/. */ package org.wso2.carbon.uuid.generator; /** * Class responsible for constructing and generating a time based UUID. */ public class TimeBasedUUIDGenerator extends UUIDGenerator { long address; //Last 8 bytes of the UUID (node id + clock sequence) protected final long uuidSecondHalf; protected final UUIDTimeStamp uuidTimeStamp; public TimeBasedUUIDGenerator(UUIDTimeStamp timeStamp) { byte[] timeBaseduuidByteAray = new byte[16]; constructNodeId(); insertToByteArray(timeBaseduuidByteAray, 10); int clockSequence = timeStamp.getClockSequence(); //set clock_seq_hi.The high field of the clock sequence.
timeBaseduuidByteAray[UUIDGeneratorConstants.CLOCK_SEQUENCE_HI_BYTE_OFFSET_IN_UUID] =
wso2/carbon-commons
components/uuid-generator/org.wso2.carbon.uuid.generator/src/main/java/org/wso2/carbon/uuid/generator/TimeBasedUUIDGenerator.java
// Path: components/uuid-generator/org.wso2.carbon.uuid.generator/src/main/java/org/wso2/carbon/uuid/generator/util/UUIDGeneratorConstants.java // public class UUIDGeneratorConstants { // // public final static int CLOCK_SEQUENCE_HI_BYTE_OFFSET_IN_UUID = 8; // public final static int CLOCK_SEQUENCE_LOW_BYTE_OFFSET_IN_UUID = 9; // // } // // Path: components/uuid-generator/org.wso2.carbon.uuid.generator/src/main/java/org/wso2/carbon/uuid/generator/util/Util.java // public class Util { // // public final static long createClockSeqInLong(byte[] buffer, int offset) { // // long hi = ((long) gatherInt(buffer, offset)) << 32; // long lo = (((long) gatherInt(buffer, offset + 4)) << 32) >>> 32; // return hi | lo; // } // // public static long createUUIDSecondHalfInLong(long l2) { // // l2 = ((l2 << 2) >>> 2); // remove 2 MSB // l2 |= (2L << 62); // set 2 MSB to '10' // return l2; // } // // private final static int gatherInt(byte[] buffer, int offset) { // // return (buffer[offset] << 24) | ((buffer[offset + 1] & 0xFF) << 16) // | ((buffer[offset + 2] & 0xFF) << 8) | (buffer[offset + 3] & 0xFF); // } // // }
import org.wso2.carbon.uuid.generator.util.UUIDGeneratorConstants; import org.wso2.carbon.uuid.generator.util.Util; import java.security.SecureRandom; import java.util.Random; import java.util.UUID;
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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. * * NOTE: The logic in this class is copied from https://github.com/cowtowncoder/java-uuid-generator/, all credits * goes to the original authors of the project https://github.com/cowtowncoder/java-uuid-generator/. */ package org.wso2.carbon.uuid.generator; /** * Class responsible for constructing and generating a time based UUID. */ public class TimeBasedUUIDGenerator extends UUIDGenerator { long address; //Last 8 bytes of the UUID (node id + clock sequence) protected final long uuidSecondHalf; protected final UUIDTimeStamp uuidTimeStamp; public TimeBasedUUIDGenerator(UUIDTimeStamp timeStamp) { byte[] timeBaseduuidByteAray = new byte[16]; constructNodeId(); insertToByteArray(timeBaseduuidByteAray, 10); int clockSequence = timeStamp.getClockSequence(); //set clock_seq_hi.The high field of the clock sequence. timeBaseduuidByteAray[UUIDGeneratorConstants.CLOCK_SEQUENCE_HI_BYTE_OFFSET_IN_UUID] = (byte) (clockSequence >> 8); //set clock_seq_low. timeBaseduuidByteAray[UUIDGeneratorConstants.CLOCK_SEQUENCE_LOW_BYTE_OFFSET_IN_UUID] = (byte) clockSequence;
// Path: components/uuid-generator/org.wso2.carbon.uuid.generator/src/main/java/org/wso2/carbon/uuid/generator/util/UUIDGeneratorConstants.java // public class UUIDGeneratorConstants { // // public final static int CLOCK_SEQUENCE_HI_BYTE_OFFSET_IN_UUID = 8; // public final static int CLOCK_SEQUENCE_LOW_BYTE_OFFSET_IN_UUID = 9; // // } // // Path: components/uuid-generator/org.wso2.carbon.uuid.generator/src/main/java/org/wso2/carbon/uuid/generator/util/Util.java // public class Util { // // public final static long createClockSeqInLong(byte[] buffer, int offset) { // // long hi = ((long) gatherInt(buffer, offset)) << 32; // long lo = (((long) gatherInt(buffer, offset + 4)) << 32) >>> 32; // return hi | lo; // } // // public static long createUUIDSecondHalfInLong(long l2) { // // l2 = ((l2 << 2) >>> 2); // remove 2 MSB // l2 |= (2L << 62); // set 2 MSB to '10' // return l2; // } // // private final static int gatherInt(byte[] buffer, int offset) { // // return (buffer[offset] << 24) | ((buffer[offset + 1] & 0xFF) << 16) // | ((buffer[offset + 2] & 0xFF) << 8) | (buffer[offset + 3] & 0xFF); // } // // } // Path: components/uuid-generator/org.wso2.carbon.uuid.generator/src/main/java/org/wso2/carbon/uuid/generator/TimeBasedUUIDGenerator.java import org.wso2.carbon.uuid.generator.util.UUIDGeneratorConstants; import org.wso2.carbon.uuid.generator.util.Util; import java.security.SecureRandom; import java.util.Random; import java.util.UUID; /* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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. * * NOTE: The logic in this class is copied from https://github.com/cowtowncoder/java-uuid-generator/, all credits * goes to the original authors of the project https://github.com/cowtowncoder/java-uuid-generator/. */ package org.wso2.carbon.uuid.generator; /** * Class responsible for constructing and generating a time based UUID. */ public class TimeBasedUUIDGenerator extends UUIDGenerator { long address; //Last 8 bytes of the UUID (node id + clock sequence) protected final long uuidSecondHalf; protected final UUIDTimeStamp uuidTimeStamp; public TimeBasedUUIDGenerator(UUIDTimeStamp timeStamp) { byte[] timeBaseduuidByteAray = new byte[16]; constructNodeId(); insertToByteArray(timeBaseduuidByteAray, 10); int clockSequence = timeStamp.getClockSequence(); //set clock_seq_hi.The high field of the clock sequence. timeBaseduuidByteAray[UUIDGeneratorConstants.CLOCK_SEQUENCE_HI_BYTE_OFFSET_IN_UUID] = (byte) (clockSequence >> 8); //set clock_seq_low. timeBaseduuidByteAray[UUIDGeneratorConstants.CLOCK_SEQUENCE_LOW_BYTE_OFFSET_IN_UUID] = (byte) clockSequence;
long clockSeqInLong = Util.createClockSeqInLong(timeBaseduuidByteAray, 8);
wso2/carbon-commons
components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/LoggingAdmin.java
// Path: components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/data/LoggerData.java // public class LoggerData { // // private String name; // private String level; // private String componentName; // // public LoggerData() { // } // // public LoggerData(String name, String level, String componentName) { // this.name = name; // this.level = level; // this.componentName = componentName; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getLevel() { // return level; // } // // public void setLevel(String level) { // this.level = level; // } // // public String getComponentName() { // return componentName; // } // // public void setComponentName(String componentName) { // this.componentName = componentName; // } // } // // Path: components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/util/Utils.java // public class Utils { // // /** // * Util method to return the specified property from a properties file. // * // * @param srcFile - The source file which needs to be looked up. // * @param key - Key of the property. // * @return - Value of the property. // */ // public static String getProperty(File srcFile, String key) throws IOException { // // String value; // try (FileInputStream fis = new FileInputStream(srcFile)) { // Properties properties = new Properties(); // properties.load(fis); // value = properties.getProperty(key); // } catch (IOException e) { // throw new IOException("Error occurred while reading the input stream"); // } // return value; // } // }
import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.configuration.PropertiesConfigurationLayout; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.logging.service.data.LoggerData; import org.wso2.carbon.logging.service.util.Utils; import org.wso2.carbon.utils.ServerConstants; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List;
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.logging.service; /** * This is the Admin service used for obtaining Log4J2 information about the system and also used for * managing the system Log4J2 configuration. */ public class LoggingAdmin { private static final Log log = LogFactory.getLog(LoggingAdmin.class); private String filePath = System.getProperty(ServerConstants.CARBON_CONFIG_DIR_PATH) + File.separator + "log4j2.properties"; private File logPropFile = new File(filePath); private PropertiesConfiguration config; private PropertiesConfigurationLayout layout; private static final String LOGGER_PREFIX = "logger."; private static final String LOGGER_LEVEL_SUFFIX = ".level"; private static final String LOGGER_NAME_SUFFIX = ".name"; private static final String LOGGERS_PROPERTY = "loggers"; private static final String ROOT_LOGGER = "rootLogger"; public String getLoggers() throws IOException {
// Path: components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/data/LoggerData.java // public class LoggerData { // // private String name; // private String level; // private String componentName; // // public LoggerData() { // } // // public LoggerData(String name, String level, String componentName) { // this.name = name; // this.level = level; // this.componentName = componentName; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getLevel() { // return level; // } // // public void setLevel(String level) { // this.level = level; // } // // public String getComponentName() { // return componentName; // } // // public void setComponentName(String componentName) { // this.componentName = componentName; // } // } // // Path: components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/util/Utils.java // public class Utils { // // /** // * Util method to return the specified property from a properties file. // * // * @param srcFile - The source file which needs to be looked up. // * @param key - Key of the property. // * @return - Value of the property. // */ // public static String getProperty(File srcFile, String key) throws IOException { // // String value; // try (FileInputStream fis = new FileInputStream(srcFile)) { // Properties properties = new Properties(); // properties.load(fis); // value = properties.getProperty(key); // } catch (IOException e) { // throw new IOException("Error occurred while reading the input stream"); // } // return value; // } // } // Path: components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/LoggingAdmin.java import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.configuration.PropertiesConfigurationLayout; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.logging.service.data.LoggerData; import org.wso2.carbon.logging.service.util.Utils; import org.wso2.carbon.utils.ServerConstants; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; /* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.logging.service; /** * This is the Admin service used for obtaining Log4J2 information about the system and also used for * managing the system Log4J2 configuration. */ public class LoggingAdmin { private static final Log log = LogFactory.getLog(LoggingAdmin.class); private String filePath = System.getProperty(ServerConstants.CARBON_CONFIG_DIR_PATH) + File.separator + "log4j2.properties"; private File logPropFile = new File(filePath); private PropertiesConfiguration config; private PropertiesConfigurationLayout layout; private static final String LOGGER_PREFIX = "logger."; private static final String LOGGER_LEVEL_SUFFIX = ".level"; private static final String LOGGER_NAME_SUFFIX = ".name"; private static final String LOGGERS_PROPERTY = "loggers"; private static final String ROOT_LOGGER = "rootLogger"; public String getLoggers() throws IOException {
return Utils.getProperty(logPropFile, LOGGERS_PROPERTY);
wso2/carbon-commons
components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/LoggingAdmin.java
// Path: components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/data/LoggerData.java // public class LoggerData { // // private String name; // private String level; // private String componentName; // // public LoggerData() { // } // // public LoggerData(String name, String level, String componentName) { // this.name = name; // this.level = level; // this.componentName = componentName; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getLevel() { // return level; // } // // public void setLevel(String level) { // this.level = level; // } // // public String getComponentName() { // return componentName; // } // // public void setComponentName(String componentName) { // this.componentName = componentName; // } // } // // Path: components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/util/Utils.java // public class Utils { // // /** // * Util method to return the specified property from a properties file. // * // * @param srcFile - The source file which needs to be looked up. // * @param key - Key of the property. // * @return - Value of the property. // */ // public static String getProperty(File srcFile, String key) throws IOException { // // String value; // try (FileInputStream fis = new FileInputStream(srcFile)) { // Properties properties = new Properties(); // properties.load(fis); // value = properties.getProperty(key); // } catch (IOException e) { // throw new IOException("Error occurred while reading the input stream"); // } // return value; // } // }
import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.configuration.PropertiesConfigurationLayout; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.logging.service.data.LoggerData; import org.wso2.carbon.logging.service.util.Utils; import org.wso2.carbon.utils.ServerConstants; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List;
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.logging.service; /** * This is the Admin service used for obtaining Log4J2 information about the system and also used for * managing the system Log4J2 configuration. */ public class LoggingAdmin { private static final Log log = LogFactory.getLog(LoggingAdmin.class); private String filePath = System.getProperty(ServerConstants.CARBON_CONFIG_DIR_PATH) + File.separator + "log4j2.properties"; private File logPropFile = new File(filePath); private PropertiesConfiguration config; private PropertiesConfigurationLayout layout; private static final String LOGGER_PREFIX = "logger."; private static final String LOGGER_LEVEL_SUFFIX = ".level"; private static final String LOGGER_NAME_SUFFIX = ".name"; private static final String LOGGERS_PROPERTY = "loggers"; private static final String ROOT_LOGGER = "rootLogger"; public String getLoggers() throws IOException { return Utils.getProperty(logPropFile, LOGGERS_PROPERTY); }
// Path: components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/data/LoggerData.java // public class LoggerData { // // private String name; // private String level; // private String componentName; // // public LoggerData() { // } // // public LoggerData(String name, String level, String componentName) { // this.name = name; // this.level = level; // this.componentName = componentName; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getLevel() { // return level; // } // // public void setLevel(String level) { // this.level = level; // } // // public String getComponentName() { // return componentName; // } // // public void setComponentName(String componentName) { // this.componentName = componentName; // } // } // // Path: components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/util/Utils.java // public class Utils { // // /** // * Util method to return the specified property from a properties file. // * // * @param srcFile - The source file which needs to be looked up. // * @param key - Key of the property. // * @return - Value of the property. // */ // public static String getProperty(File srcFile, String key) throws IOException { // // String value; // try (FileInputStream fis = new FileInputStream(srcFile)) { // Properties properties = new Properties(); // properties.load(fis); // value = properties.getProperty(key); // } catch (IOException e) { // throw new IOException("Error occurred while reading the input stream"); // } // return value; // } // } // Path: components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/LoggingAdmin.java import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.configuration.PropertiesConfigurationLayout; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.logging.service.data.LoggerData; import org.wso2.carbon.logging.service.util.Utils; import org.wso2.carbon.utils.ServerConstants; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; /* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.logging.service; /** * This is the Admin service used for obtaining Log4J2 information about the system and also used for * managing the system Log4J2 configuration. */ public class LoggingAdmin { private static final Log log = LogFactory.getLog(LoggingAdmin.class); private String filePath = System.getProperty(ServerConstants.CARBON_CONFIG_DIR_PATH) + File.separator + "log4j2.properties"; private File logPropFile = new File(filePath); private PropertiesConfiguration config; private PropertiesConfigurationLayout layout; private static final String LOGGER_PREFIX = "logger."; private static final String LOGGER_LEVEL_SUFFIX = ".level"; private static final String LOGGER_NAME_SUFFIX = ".name"; private static final String LOGGERS_PROPERTY = "loggers"; private static final String ROOT_LOGGER = "rootLogger"; public String getLoggers() throws IOException { return Utils.getProperty(logPropFile, LOGGERS_PROPERTY); }
public LoggerData getLoggerData(String loggerName) throws IOException {
wso2/carbon-commons
components/application-mgt/org.wso2.carbon.application.mgt/src/main/java/org/wso2/carbon/application/mgt/ApplicationAdmin.java
// Path: components/application-mgt/org.wso2.carbon.application.mgt/src/main/java/org/wso2/carbon/application/mgt/internal/AppManagementServiceComponent.java // @Component( // name = "application.mgt.dscomponent", // immediate = true) // public class AppManagementServiceComponent { // // private static Log log = LogFactory.getLog(AppManagementServiceComponent.class); // // private static ApplicationManagerService applicationManager; // // @Activate // protected void activate(ComponentContext ctxt) { // // if (log.isDebugEnabled()) { // log.debug("Activated AppManagementServiceComponent"); // } // } // // @Deactivate // protected void deactivate(ComponentContext ctxt) { // // if (log.isDebugEnabled()) { // log.debug("Deactivated AppManagementServiceComponent"); // } // } // // @Reference( // name = "application.manager", // service = org.wso2.carbon.application.deployer.service.ApplicationManagerService.class, // cardinality = ReferenceCardinality.MANDATORY, // policy = ReferencePolicy.DYNAMIC, // unbind = "unsetAppManager") // protected void setAppManager(ApplicationManagerService appManager) { // // applicationManager = appManager; // } // // protected void unsetAppManager(ApplicationManagerService appManager) { // // applicationManager = null; // } // // public static ApplicationManagerService getAppManager() throws Exception { // // if (applicationManager == null) { // String msg = "Before activating App management service bundle, an instance of " + "ApplicationManager " + // "should be in existance"; // log.error(msg); // throw new Exception(msg); // } // return applicationManager; // } // }
import org.apache.axis2.description.AxisService; import org.apache.axis2.description.AxisServiceGroup; import org.apache.axis2.description.Parameter; import org.apache.axis2.engine.AxisConfiguration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonException; import org.wso2.carbon.application.deployer.AppDeployerConstants; import org.wso2.carbon.application.deployer.AppDeployerUtils; import org.wso2.carbon.application.deployer.CarbonApplication; import org.wso2.carbon.application.deployer.config.Artifact; import org.wso2.carbon.application.deployer.config.RegistryConfig; import org.wso2.carbon.application.deployer.handler.DefaultAppDeployer; import org.wso2.carbon.application.deployer.handler.RegistryResourceDeployer; import org.wso2.carbon.application.deployer.persistence.CarbonAppPersistenceManager; import org.wso2.carbon.application.mgt.internal.AppManagementServiceComponent; import org.wso2.carbon.core.AbstractAdmin; import org.wso2.carbon.core.util.SystemFilter; import org.wso2.carbon.utils.ServerConstants; import javax.activation.DataHandler; import javax.activation.FileDataSource; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.util.*;
/* * Copyright 2005-2007 WSO2, Inc. (http://wso2.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.application.mgt; public class ApplicationAdmin extends AbstractAdmin { private static final Log log = LogFactory.getLog(ApplicationAdmin.class); private static final String DS_TYPE = "service/dataservice"; /** * Give the names of all applications in the system * @return - names array * @throws Exception - error on getting carbon app service */ public String[] listAllApplications() throws Exception { String tenantId = AppDeployerUtils.getTenantIdString(getAxisConfig()); ArrayList<CarbonApplication> appList
// Path: components/application-mgt/org.wso2.carbon.application.mgt/src/main/java/org/wso2/carbon/application/mgt/internal/AppManagementServiceComponent.java // @Component( // name = "application.mgt.dscomponent", // immediate = true) // public class AppManagementServiceComponent { // // private static Log log = LogFactory.getLog(AppManagementServiceComponent.class); // // private static ApplicationManagerService applicationManager; // // @Activate // protected void activate(ComponentContext ctxt) { // // if (log.isDebugEnabled()) { // log.debug("Activated AppManagementServiceComponent"); // } // } // // @Deactivate // protected void deactivate(ComponentContext ctxt) { // // if (log.isDebugEnabled()) { // log.debug("Deactivated AppManagementServiceComponent"); // } // } // // @Reference( // name = "application.manager", // service = org.wso2.carbon.application.deployer.service.ApplicationManagerService.class, // cardinality = ReferenceCardinality.MANDATORY, // policy = ReferencePolicy.DYNAMIC, // unbind = "unsetAppManager") // protected void setAppManager(ApplicationManagerService appManager) { // // applicationManager = appManager; // } // // protected void unsetAppManager(ApplicationManagerService appManager) { // // applicationManager = null; // } // // public static ApplicationManagerService getAppManager() throws Exception { // // if (applicationManager == null) { // String msg = "Before activating App management service bundle, an instance of " + "ApplicationManager " + // "should be in existance"; // log.error(msg); // throw new Exception(msg); // } // return applicationManager; // } // } // Path: components/application-mgt/org.wso2.carbon.application.mgt/src/main/java/org/wso2/carbon/application/mgt/ApplicationAdmin.java import org.apache.axis2.description.AxisService; import org.apache.axis2.description.AxisServiceGroup; import org.apache.axis2.description.Parameter; import org.apache.axis2.engine.AxisConfiguration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonException; import org.wso2.carbon.application.deployer.AppDeployerConstants; import org.wso2.carbon.application.deployer.AppDeployerUtils; import org.wso2.carbon.application.deployer.CarbonApplication; import org.wso2.carbon.application.deployer.config.Artifact; import org.wso2.carbon.application.deployer.config.RegistryConfig; import org.wso2.carbon.application.deployer.handler.DefaultAppDeployer; import org.wso2.carbon.application.deployer.handler.RegistryResourceDeployer; import org.wso2.carbon.application.deployer.persistence.CarbonAppPersistenceManager; import org.wso2.carbon.application.mgt.internal.AppManagementServiceComponent; import org.wso2.carbon.core.AbstractAdmin; import org.wso2.carbon.core.util.SystemFilter; import org.wso2.carbon.utils.ServerConstants; import javax.activation.DataHandler; import javax.activation.FileDataSource; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.util.*; /* * Copyright 2005-2007 WSO2, Inc. (http://wso2.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.application.mgt; public class ApplicationAdmin extends AbstractAdmin { private static final Log log = LogFactory.getLog(ApplicationAdmin.class); private static final String DS_TYPE = "service/dataservice"; /** * Give the names of all applications in the system * @return - names array * @throws Exception - error on getting carbon app service */ public String[] listAllApplications() throws Exception { String tenantId = AppDeployerUtils.getTenantIdString(getAxisConfig()); ArrayList<CarbonApplication> appList
= AppManagementServiceComponent.getAppManager().getCarbonApps(tenantId);
gomathi/merkle-tree
test/org/hashtrees/utils/test/FlattenIteratorTest.java
// Path: src/org/hashtrees/util/FlattenIterator.java // @NotThreadSafe // public class FlattenIterator<T> implements Iterator<T> { // // private final Iterator<Iterator<T>> itrs; // private final Queue<Iterator<T>> intQue = new ArrayDeque<>(1); // // public FlattenIterator(Iterator<Iterator<T>> itrs) { // this.itrs = itrs; // } // // @Override // public boolean hasNext() { // loadNextElement(); // return !intQue.isEmpty(); // } // // @Override // public T next() { // if (!hasNext()) // throw new NoSuchElementException( // "No more elements exist to return."); // return intQue.peek().next(); // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // // private void loadNextElement() { // while (intQue.isEmpty() || !intQue.peek().hasNext()) { // intQue.poll(); // if (itrs.hasNext()) // intQue.add(itrs.next()); // else // return; // } // } // // }
import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import junit.framework.Assert; import org.hashtrees.util.FlattenIterator; import org.junit.Test;
package org.hashtrees.utils.test; public class FlattenIteratorTest { @Test public void testFlattenIteratorWithEmptyIterators() { List<Iterator<Integer>> emptyIteratorList = Collections.emptyList(); Iterator<Iterator<Integer>> itrs = emptyIteratorList.iterator();
// Path: src/org/hashtrees/util/FlattenIterator.java // @NotThreadSafe // public class FlattenIterator<T> implements Iterator<T> { // // private final Iterator<Iterator<T>> itrs; // private final Queue<Iterator<T>> intQue = new ArrayDeque<>(1); // // public FlattenIterator(Iterator<Iterator<T>> itrs) { // this.itrs = itrs; // } // // @Override // public boolean hasNext() { // loadNextElement(); // return !intQue.isEmpty(); // } // // @Override // public T next() { // if (!hasNext()) // throw new NoSuchElementException( // "No more elements exist to return."); // return intQue.peek().next(); // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // // private void loadNextElement() { // while (intQue.isEmpty() || !intQue.peek().hasNext()) { // intQue.poll(); // if (itrs.hasNext()) // intQue.add(itrs.next()); // else // return; // } // } // // } // Path: test/org/hashtrees/utils/test/FlattenIteratorTest.java import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import junit.framework.Assert; import org.hashtrees.util.FlattenIterator; import org.junit.Test; package org.hashtrees.utils.test; public class FlattenIteratorTest { @Test public void testFlattenIteratorWithEmptyIterators() { List<Iterator<Integer>> emptyIteratorList = Collections.emptyList(); Iterator<Iterator<Integer>> itrs = emptyIteratorList.iterator();
Assert.assertFalse(new FlattenIterator<>(itrs).hasNext());
gomathi/merkle-tree
test/org/hashtrees/utils/test/NonBlockingQueuingTaskTest.java
// Path: src/org/hashtrees/util/NonBlockingQueuingTask.java // public abstract class NonBlockingQueuingTask<T> extends StoppableTask { // // // A special marker to note down a stop operation has been requested on this // // thread. // private final T stopMarker; // private final BlockingQueue<T> que; // // /** // * @param stopMarker // * specifies a special data which is used for indicating stop // * operation. Subclasses should not use this marker for any // * operation. // * @param queueSize // * how much data can the queue can hold. Should be higher enough // * based on the number of producers, otherwise exception will be // * thrown on adding the elements to the queue. // */ // public NonBlockingQueuingTask(T stopMarker, int queueSize) { // this.stopMarker = stopMarker; // que = new LinkedBlockingQueue<T>(queueSize); // } // // public void enque(T element) { // if (hasStopRequested() && element != stopMarker) { // throw new QueuingTaskIsStoppedException(); // } // boolean status = que.offer(element); // if (!status) // throw new QueueReachedMaxCapacityException(); // } // // @Override // public synchronized void stopAsync() { // super.stopAsync(); // enque(stopMarker); // } // // @Override // public synchronized void stopAsync(final CountDownLatch shutDownLatch) { // super.stopAsync(shutDownLatch); // enque(stopMarker); // } // // @Override // public void runImpl() { // for (;;) { // try { // T data = que.take(); // if (data == stopMarker) // continue; // handleElement(data); // } catch (InterruptedException e) { // throw new RuntimeException( // "Exception occurred while removing the element from the queue", // e); // } finally { // if (hasStopRequested() && que.isEmpty()) { // return; // } // } // } // } // // protected abstract void handleElement(T element); // // public static class QueueReachedMaxCapacityException extends // RuntimeException { // // private static final long serialVersionUID = 1L; // private static final String EXCEPTION_MSG = "Queue is full. Can not add more elements to the queue."; // // public QueueReachedMaxCapacityException() { // super(EXCEPTION_MSG); // } // // public QueueReachedMaxCapacityException(Throwable cause) { // super(EXCEPTION_MSG, cause); // } // } // // public static class QueuingTaskIsStoppedException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final String EXCEPTION_MSG = "Queuing task is stopped. Can not add elements to the queue."; // // public QueuingTaskIsStoppedException() { // super(EXCEPTION_MSG); // } // // public QueuingTaskIsStoppedException(Throwable cause) { // super(EXCEPTION_MSG, cause); // } // } // } // // Path: src/org/hashtrees/util/NonBlockingQueuingTask.java // public static class QueuingTaskIsStoppedException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final String EXCEPTION_MSG = "Queuing task is stopped. Can not add elements to the queue."; // // public QueuingTaskIsStoppedException() { // super(EXCEPTION_MSG); // } // // public QueuingTaskIsStoppedException(Throwable cause) { // super(EXCEPTION_MSG, cause); // } // }
import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import junit.framework.Assert; import org.hashtrees.util.NonBlockingQueuingTask; import org.hashtrees.util.NonBlockingQueuingTask.QueuingTaskIsStoppedException; import org.junit.Test;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.hashtrees.utils.test; public class NonBlockingQueuingTaskTest { @Test public void testEnqueOperations() throws InterruptedException { Integer marker = new Integer(0); final List<Integer> queuedElements = new ArrayList<>();
// Path: src/org/hashtrees/util/NonBlockingQueuingTask.java // public abstract class NonBlockingQueuingTask<T> extends StoppableTask { // // // A special marker to note down a stop operation has been requested on this // // thread. // private final T stopMarker; // private final BlockingQueue<T> que; // // /** // * @param stopMarker // * specifies a special data which is used for indicating stop // * operation. Subclasses should not use this marker for any // * operation. // * @param queueSize // * how much data can the queue can hold. Should be higher enough // * based on the number of producers, otherwise exception will be // * thrown on adding the elements to the queue. // */ // public NonBlockingQueuingTask(T stopMarker, int queueSize) { // this.stopMarker = stopMarker; // que = new LinkedBlockingQueue<T>(queueSize); // } // // public void enque(T element) { // if (hasStopRequested() && element != stopMarker) { // throw new QueuingTaskIsStoppedException(); // } // boolean status = que.offer(element); // if (!status) // throw new QueueReachedMaxCapacityException(); // } // // @Override // public synchronized void stopAsync() { // super.stopAsync(); // enque(stopMarker); // } // // @Override // public synchronized void stopAsync(final CountDownLatch shutDownLatch) { // super.stopAsync(shutDownLatch); // enque(stopMarker); // } // // @Override // public void runImpl() { // for (;;) { // try { // T data = que.take(); // if (data == stopMarker) // continue; // handleElement(data); // } catch (InterruptedException e) { // throw new RuntimeException( // "Exception occurred while removing the element from the queue", // e); // } finally { // if (hasStopRequested() && que.isEmpty()) { // return; // } // } // } // } // // protected abstract void handleElement(T element); // // public static class QueueReachedMaxCapacityException extends // RuntimeException { // // private static final long serialVersionUID = 1L; // private static final String EXCEPTION_MSG = "Queue is full. Can not add more elements to the queue."; // // public QueueReachedMaxCapacityException() { // super(EXCEPTION_MSG); // } // // public QueueReachedMaxCapacityException(Throwable cause) { // super(EXCEPTION_MSG, cause); // } // } // // public static class QueuingTaskIsStoppedException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final String EXCEPTION_MSG = "Queuing task is stopped. Can not add elements to the queue."; // // public QueuingTaskIsStoppedException() { // super(EXCEPTION_MSG); // } // // public QueuingTaskIsStoppedException(Throwable cause) { // super(EXCEPTION_MSG, cause); // } // } // } // // Path: src/org/hashtrees/util/NonBlockingQueuingTask.java // public static class QueuingTaskIsStoppedException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final String EXCEPTION_MSG = "Queuing task is stopped. Can not add elements to the queue."; // // public QueuingTaskIsStoppedException() { // super(EXCEPTION_MSG); // } // // public QueuingTaskIsStoppedException(Throwable cause) { // super(EXCEPTION_MSG, cause); // } // } // Path: test/org/hashtrees/utils/test/NonBlockingQueuingTaskTest.java import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import junit.framework.Assert; import org.hashtrees.util.NonBlockingQueuingTask; import org.hashtrees.util.NonBlockingQueuingTask.QueuingTaskIsStoppedException; import org.junit.Test; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.hashtrees.utils.test; public class NonBlockingQueuingTaskTest { @Test public void testEnqueOperations() throws InterruptedException { Integer marker = new Integer(0); final List<Integer> queuedElements = new ArrayList<>();
NonBlockingQueuingTask<Integer> nbqTask = new NonBlockingQueuingTask<Integer>(
gomathi/merkle-tree
test/org/hashtrees/utils/test/NonBlockingQueuingTaskTest.java
// Path: src/org/hashtrees/util/NonBlockingQueuingTask.java // public abstract class NonBlockingQueuingTask<T> extends StoppableTask { // // // A special marker to note down a stop operation has been requested on this // // thread. // private final T stopMarker; // private final BlockingQueue<T> que; // // /** // * @param stopMarker // * specifies a special data which is used for indicating stop // * operation. Subclasses should not use this marker for any // * operation. // * @param queueSize // * how much data can the queue can hold. Should be higher enough // * based on the number of producers, otherwise exception will be // * thrown on adding the elements to the queue. // */ // public NonBlockingQueuingTask(T stopMarker, int queueSize) { // this.stopMarker = stopMarker; // que = new LinkedBlockingQueue<T>(queueSize); // } // // public void enque(T element) { // if (hasStopRequested() && element != stopMarker) { // throw new QueuingTaskIsStoppedException(); // } // boolean status = que.offer(element); // if (!status) // throw new QueueReachedMaxCapacityException(); // } // // @Override // public synchronized void stopAsync() { // super.stopAsync(); // enque(stopMarker); // } // // @Override // public synchronized void stopAsync(final CountDownLatch shutDownLatch) { // super.stopAsync(shutDownLatch); // enque(stopMarker); // } // // @Override // public void runImpl() { // for (;;) { // try { // T data = que.take(); // if (data == stopMarker) // continue; // handleElement(data); // } catch (InterruptedException e) { // throw new RuntimeException( // "Exception occurred while removing the element from the queue", // e); // } finally { // if (hasStopRequested() && que.isEmpty()) { // return; // } // } // } // } // // protected abstract void handleElement(T element); // // public static class QueueReachedMaxCapacityException extends // RuntimeException { // // private static final long serialVersionUID = 1L; // private static final String EXCEPTION_MSG = "Queue is full. Can not add more elements to the queue."; // // public QueueReachedMaxCapacityException() { // super(EXCEPTION_MSG); // } // // public QueueReachedMaxCapacityException(Throwable cause) { // super(EXCEPTION_MSG, cause); // } // } // // public static class QueuingTaskIsStoppedException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final String EXCEPTION_MSG = "Queuing task is stopped. Can not add elements to the queue."; // // public QueuingTaskIsStoppedException() { // super(EXCEPTION_MSG); // } // // public QueuingTaskIsStoppedException(Throwable cause) { // super(EXCEPTION_MSG, cause); // } // } // } // // Path: src/org/hashtrees/util/NonBlockingQueuingTask.java // public static class QueuingTaskIsStoppedException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final String EXCEPTION_MSG = "Queuing task is stopped. Can not add elements to the queue."; // // public QueuingTaskIsStoppedException() { // super(EXCEPTION_MSG); // } // // public QueuingTaskIsStoppedException(Throwable cause) { // super(EXCEPTION_MSG, cause); // } // }
import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import junit.framework.Assert; import org.hashtrees.util.NonBlockingQueuingTask; import org.hashtrees.util.NonBlockingQueuingTask.QueuingTaskIsStoppedException; import org.junit.Test;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.hashtrees.utils.test; public class NonBlockingQueuingTaskTest { @Test public void testEnqueOperations() throws InterruptedException { Integer marker = new Integer(0); final List<Integer> queuedElements = new ArrayList<>(); NonBlockingQueuingTask<Integer> nbqTask = new NonBlockingQueuingTask<Integer>( marker, 100) { @Override protected void handleElement(Integer element) { queuedElements.add(element); } }; new Thread(nbqTask).start(); for (int i = 0; i < 10; i++) nbqTask.enque(i); CountDownLatch stopLatch = new CountDownLatch(1); nbqTask.stopAsync(stopLatch); stopLatch.await(10000, TimeUnit.MILLISECONDS); Assert.assertEquals(10, queuedElements.size()); for (int i = 0; i < 10; i++) Assert.assertEquals(i, queuedElements.get(i).intValue()); }
// Path: src/org/hashtrees/util/NonBlockingQueuingTask.java // public abstract class NonBlockingQueuingTask<T> extends StoppableTask { // // // A special marker to note down a stop operation has been requested on this // // thread. // private final T stopMarker; // private final BlockingQueue<T> que; // // /** // * @param stopMarker // * specifies a special data which is used for indicating stop // * operation. Subclasses should not use this marker for any // * operation. // * @param queueSize // * how much data can the queue can hold. Should be higher enough // * based on the number of producers, otherwise exception will be // * thrown on adding the elements to the queue. // */ // public NonBlockingQueuingTask(T stopMarker, int queueSize) { // this.stopMarker = stopMarker; // que = new LinkedBlockingQueue<T>(queueSize); // } // // public void enque(T element) { // if (hasStopRequested() && element != stopMarker) { // throw new QueuingTaskIsStoppedException(); // } // boolean status = que.offer(element); // if (!status) // throw new QueueReachedMaxCapacityException(); // } // // @Override // public synchronized void stopAsync() { // super.stopAsync(); // enque(stopMarker); // } // // @Override // public synchronized void stopAsync(final CountDownLatch shutDownLatch) { // super.stopAsync(shutDownLatch); // enque(stopMarker); // } // // @Override // public void runImpl() { // for (;;) { // try { // T data = que.take(); // if (data == stopMarker) // continue; // handleElement(data); // } catch (InterruptedException e) { // throw new RuntimeException( // "Exception occurred while removing the element from the queue", // e); // } finally { // if (hasStopRequested() && que.isEmpty()) { // return; // } // } // } // } // // protected abstract void handleElement(T element); // // public static class QueueReachedMaxCapacityException extends // RuntimeException { // // private static final long serialVersionUID = 1L; // private static final String EXCEPTION_MSG = "Queue is full. Can not add more elements to the queue."; // // public QueueReachedMaxCapacityException() { // super(EXCEPTION_MSG); // } // // public QueueReachedMaxCapacityException(Throwable cause) { // super(EXCEPTION_MSG, cause); // } // } // // public static class QueuingTaskIsStoppedException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final String EXCEPTION_MSG = "Queuing task is stopped. Can not add elements to the queue."; // // public QueuingTaskIsStoppedException() { // super(EXCEPTION_MSG); // } // // public QueuingTaskIsStoppedException(Throwable cause) { // super(EXCEPTION_MSG, cause); // } // } // } // // Path: src/org/hashtrees/util/NonBlockingQueuingTask.java // public static class QueuingTaskIsStoppedException extends RuntimeException { // // private static final long serialVersionUID = 1L; // private static final String EXCEPTION_MSG = "Queuing task is stopped. Can not add elements to the queue."; // // public QueuingTaskIsStoppedException() { // super(EXCEPTION_MSG); // } // // public QueuingTaskIsStoppedException(Throwable cause) { // super(EXCEPTION_MSG, cause); // } // } // Path: test/org/hashtrees/utils/test/NonBlockingQueuingTaskTest.java import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import junit.framework.Assert; import org.hashtrees.util.NonBlockingQueuingTask; import org.hashtrees.util.NonBlockingQueuingTask.QueuingTaskIsStoppedException; import org.junit.Test; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.hashtrees.utils.test; public class NonBlockingQueuingTaskTest { @Test public void testEnqueOperations() throws InterruptedException { Integer marker = new Integer(0); final List<Integer> queuedElements = new ArrayList<>(); NonBlockingQueuingTask<Integer> nbqTask = new NonBlockingQueuingTask<Integer>( marker, 100) { @Override protected void handleElement(Integer element) { queuedElements.add(element); } }; new Thread(nbqTask).start(); for (int i = 0; i < 10; i++) nbqTask.enque(i); CountDownLatch stopLatch = new CountDownLatch(1); nbqTask.stopAsync(stopLatch); stopLatch.await(10000, TimeUnit.MILLISECONDS); Assert.assertEquals(10, queuedElements.size()); for (int i = 0; i < 10; i++) Assert.assertEquals(i, queuedElements.get(i).intValue()); }
@Test(expected = QueuingTaskIsStoppedException.class)
ot4i/perf-harness
AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/BlockingJavaClient.java
// Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/AMQPWorkerThread.java // public static class AMQPException extends Exception { // private static final long serialVersionUID = 1L; // // /** // * @param message // */ // public AMQPException(final String message) { // super(message); // } // // /** // * @param message // * @param cause // */ // public AMQPException(final String message, final Throwable cause) { // super(message, cause); // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/FIFO.java // public static class FIFODelivery extends FIFOAbs { // public FIFODelivery(final String reference) { // super(reference); // } // // /** // * Insert an item into the FIFO // * // * @param delivery // */ // public void put(final Delivery delivery) { // super.put(delivery); // } // // /** // * Removes a delivery message from the FIFO // * // * @return a delivery or null if exception. // * @throws AMQPException // * // */ // public Delivery get() throws AMQPException { // Object item = super.get(); // if (item instanceof Delivery) { // return (Delivery) item; // } // else { // throw new AMQPException("Internal error: expected Delivery but got " + item.getClass().getName()); // } // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/FIFO.java // public static class FIFOHashMap extends FIFOAbs { // public FIFOHashMap(final String reference) { // super(reference); // } // // // /** // * @param hashMap // */ // public void put(final HashMap<String, Object> hashMap) { // super.put(hashMap); // } // // // /* (non-Javadoc) // * @see com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFOAbs#get() // */ // @SuppressWarnings("unchecked") // public HashMap<String, Object> get() throws AMQPException { // Object item = super.get(); // if (item instanceof HashMap) { // return (HashMap<String, Object>) item; // } // else { // throw new AMQPException("Internal error: expected HashMap but got " + item.getClass().getName()); // } // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/MessageContainer.java // public enum MESSAGE_TYPE {STRING, BYTES};
import java.nio.ByteBuffer; import java.util.HashMap; import java.util.logging.Level; import com.ibm.mqlight.api.ClientException; import com.ibm.mqlight.api.ClientOptions; import com.ibm.mqlight.api.ClientState; import com.ibm.mqlight.api.CompletionListener; import com.ibm.mqlight.api.Delivery; import com.ibm.mqlight.api.DestinationAdapter; import com.ibm.mqlight.api.MalformedDelivery; import com.ibm.mqlight.api.NonBlockingClient; import com.ibm.mqlight.api.NonBlockingClientAdapter; import com.ibm.mqlight.api.QOS; import com.ibm.mqlight.api.SendOptions; import com.ibm.mqlight.api.SendOptions.SendOptionsBuilder; import com.ibm.mqlight.api.StringDelivery; import com.ibm.mqlight.api.SubscribeOptions; import com.ibm.mqlight.api.SubscribeOptions.SubscribeOptionsBuilder; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.amqp.AMQPWorkerThread.AMQPException; import com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFODelivery; import com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFOHashMap; import com.ibm.uk.hursley.perfharness.amqp.utils.MessageContainer.MESSAGE_TYPE; import com.ibm.uk.hursley.perfharness.util.TypedPropertyException;
/********************************************************* {COPYRIGHT-TOP} *** * Copyright 2016 IBM Corporation * * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License * which accompanies this distribution, and is available at * http://opensource.org/licenses/MIT ********************************************************** {COPYRIGHT-END} **/ package com.ibm.uk.hursley.perfharness.amqp.utils; /** * @author ElliotGregory * */ public class BlockingJavaClient { private final static Boolean logEnabled = Log.logger.getLevel().intValue() <= Level.FINE.intValue(); private final static int QUEUE_SIZE_WARNING = 20; /** AMQP Client object **/ private final NonBlockingClient client; /** Server address **/ private final String amqpAddress; /** FIFO communication **/
// Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/AMQPWorkerThread.java // public static class AMQPException extends Exception { // private static final long serialVersionUID = 1L; // // /** // * @param message // */ // public AMQPException(final String message) { // super(message); // } // // /** // * @param message // * @param cause // */ // public AMQPException(final String message, final Throwable cause) { // super(message, cause); // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/FIFO.java // public static class FIFODelivery extends FIFOAbs { // public FIFODelivery(final String reference) { // super(reference); // } // // /** // * Insert an item into the FIFO // * // * @param delivery // */ // public void put(final Delivery delivery) { // super.put(delivery); // } // // /** // * Removes a delivery message from the FIFO // * // * @return a delivery or null if exception. // * @throws AMQPException // * // */ // public Delivery get() throws AMQPException { // Object item = super.get(); // if (item instanceof Delivery) { // return (Delivery) item; // } // else { // throw new AMQPException("Internal error: expected Delivery but got " + item.getClass().getName()); // } // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/FIFO.java // public static class FIFOHashMap extends FIFOAbs { // public FIFOHashMap(final String reference) { // super(reference); // } // // // /** // * @param hashMap // */ // public void put(final HashMap<String, Object> hashMap) { // super.put(hashMap); // } // // // /* (non-Javadoc) // * @see com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFOAbs#get() // */ // @SuppressWarnings("unchecked") // public HashMap<String, Object> get() throws AMQPException { // Object item = super.get(); // if (item instanceof HashMap) { // return (HashMap<String, Object>) item; // } // else { // throw new AMQPException("Internal error: expected HashMap but got " + item.getClass().getName()); // } // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/MessageContainer.java // public enum MESSAGE_TYPE {STRING, BYTES}; // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/BlockingJavaClient.java import java.nio.ByteBuffer; import java.util.HashMap; import java.util.logging.Level; import com.ibm.mqlight.api.ClientException; import com.ibm.mqlight.api.ClientOptions; import com.ibm.mqlight.api.ClientState; import com.ibm.mqlight.api.CompletionListener; import com.ibm.mqlight.api.Delivery; import com.ibm.mqlight.api.DestinationAdapter; import com.ibm.mqlight.api.MalformedDelivery; import com.ibm.mqlight.api.NonBlockingClient; import com.ibm.mqlight.api.NonBlockingClientAdapter; import com.ibm.mqlight.api.QOS; import com.ibm.mqlight.api.SendOptions; import com.ibm.mqlight.api.SendOptions.SendOptionsBuilder; import com.ibm.mqlight.api.StringDelivery; import com.ibm.mqlight.api.SubscribeOptions; import com.ibm.mqlight.api.SubscribeOptions.SubscribeOptionsBuilder; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.amqp.AMQPWorkerThread.AMQPException; import com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFODelivery; import com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFOHashMap; import com.ibm.uk.hursley.perfharness.amqp.utils.MessageContainer.MESSAGE_TYPE; import com.ibm.uk.hursley.perfharness.util.TypedPropertyException; /********************************************************* {COPYRIGHT-TOP} *** * Copyright 2016 IBM Corporation * * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License * which accompanies this distribution, and is available at * http://opensource.org/licenses/MIT ********************************************************** {COPYRIGHT-END} **/ package com.ibm.uk.hursley.perfharness.amqp.utils; /** * @author ElliotGregory * */ public class BlockingJavaClient { private final static Boolean logEnabled = Log.logger.getLevel().intValue() <= Level.FINE.intValue(); private final static int QUEUE_SIZE_WARNING = 20; /** AMQP Client object **/ private final NonBlockingClient client; /** Server address **/ private final String amqpAddress; /** FIFO communication **/
private final FIFODelivery fifoDelivery;
ot4i/perf-harness
AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/BlockingJavaClient.java
// Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/AMQPWorkerThread.java // public static class AMQPException extends Exception { // private static final long serialVersionUID = 1L; // // /** // * @param message // */ // public AMQPException(final String message) { // super(message); // } // // /** // * @param message // * @param cause // */ // public AMQPException(final String message, final Throwable cause) { // super(message, cause); // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/FIFO.java // public static class FIFODelivery extends FIFOAbs { // public FIFODelivery(final String reference) { // super(reference); // } // // /** // * Insert an item into the FIFO // * // * @param delivery // */ // public void put(final Delivery delivery) { // super.put(delivery); // } // // /** // * Removes a delivery message from the FIFO // * // * @return a delivery or null if exception. // * @throws AMQPException // * // */ // public Delivery get() throws AMQPException { // Object item = super.get(); // if (item instanceof Delivery) { // return (Delivery) item; // } // else { // throw new AMQPException("Internal error: expected Delivery but got " + item.getClass().getName()); // } // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/FIFO.java // public static class FIFOHashMap extends FIFOAbs { // public FIFOHashMap(final String reference) { // super(reference); // } // // // /** // * @param hashMap // */ // public void put(final HashMap<String, Object> hashMap) { // super.put(hashMap); // } // // // /* (non-Javadoc) // * @see com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFOAbs#get() // */ // @SuppressWarnings("unchecked") // public HashMap<String, Object> get() throws AMQPException { // Object item = super.get(); // if (item instanceof HashMap) { // return (HashMap<String, Object>) item; // } // else { // throw new AMQPException("Internal error: expected HashMap but got " + item.getClass().getName()); // } // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/MessageContainer.java // public enum MESSAGE_TYPE {STRING, BYTES};
import java.nio.ByteBuffer; import java.util.HashMap; import java.util.logging.Level; import com.ibm.mqlight.api.ClientException; import com.ibm.mqlight.api.ClientOptions; import com.ibm.mqlight.api.ClientState; import com.ibm.mqlight.api.CompletionListener; import com.ibm.mqlight.api.Delivery; import com.ibm.mqlight.api.DestinationAdapter; import com.ibm.mqlight.api.MalformedDelivery; import com.ibm.mqlight.api.NonBlockingClient; import com.ibm.mqlight.api.NonBlockingClientAdapter; import com.ibm.mqlight.api.QOS; import com.ibm.mqlight.api.SendOptions; import com.ibm.mqlight.api.SendOptions.SendOptionsBuilder; import com.ibm.mqlight.api.StringDelivery; import com.ibm.mqlight.api.SubscribeOptions; import com.ibm.mqlight.api.SubscribeOptions.SubscribeOptionsBuilder; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.amqp.AMQPWorkerThread.AMQPException; import com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFODelivery; import com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFOHashMap; import com.ibm.uk.hursley.perfharness.amqp.utils.MessageContainer.MESSAGE_TYPE; import com.ibm.uk.hursley.perfharness.util.TypedPropertyException;
blocker.signal(map); } @Override public void onSuccess(NonBlockingClient client, Object context) { if (logEnabled) log("({0}, {1}): Subscribe - Completed",amqpAddress, topicPattern); blocker.signal(null); } }, null); // Wait for completion event HashMap map = blocker.pause(); if (map != null && map.containsKey("exception")) { if (logEnabled) log("({0}, {1}): Subscribe - Exception {2}",amqpAddress, topicPattern, map.get("exception").toString()); throw (Exception)map.get("exception"); } if (logEnabled) log("({0}, {1}): Subscribe - completed", amqpAddress, topicPattern); } /** * @param client * @throws Exception */ public BlockingJavaClient (final String amqpAddress, String clientId) throws Exception { this.amqpAddress = amqpAddress; this.transferParameters = new TransferParameters(); this.fifoDelivery = new FIFODelivery (amqpAddress);
// Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/AMQPWorkerThread.java // public static class AMQPException extends Exception { // private static final long serialVersionUID = 1L; // // /** // * @param message // */ // public AMQPException(final String message) { // super(message); // } // // /** // * @param message // * @param cause // */ // public AMQPException(final String message, final Throwable cause) { // super(message, cause); // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/FIFO.java // public static class FIFODelivery extends FIFOAbs { // public FIFODelivery(final String reference) { // super(reference); // } // // /** // * Insert an item into the FIFO // * // * @param delivery // */ // public void put(final Delivery delivery) { // super.put(delivery); // } // // /** // * Removes a delivery message from the FIFO // * // * @return a delivery or null if exception. // * @throws AMQPException // * // */ // public Delivery get() throws AMQPException { // Object item = super.get(); // if (item instanceof Delivery) { // return (Delivery) item; // } // else { // throw new AMQPException("Internal error: expected Delivery but got " + item.getClass().getName()); // } // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/FIFO.java // public static class FIFOHashMap extends FIFOAbs { // public FIFOHashMap(final String reference) { // super(reference); // } // // // /** // * @param hashMap // */ // public void put(final HashMap<String, Object> hashMap) { // super.put(hashMap); // } // // // /* (non-Javadoc) // * @see com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFOAbs#get() // */ // @SuppressWarnings("unchecked") // public HashMap<String, Object> get() throws AMQPException { // Object item = super.get(); // if (item instanceof HashMap) { // return (HashMap<String, Object>) item; // } // else { // throw new AMQPException("Internal error: expected HashMap but got " + item.getClass().getName()); // } // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/MessageContainer.java // public enum MESSAGE_TYPE {STRING, BYTES}; // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/BlockingJavaClient.java import java.nio.ByteBuffer; import java.util.HashMap; import java.util.logging.Level; import com.ibm.mqlight.api.ClientException; import com.ibm.mqlight.api.ClientOptions; import com.ibm.mqlight.api.ClientState; import com.ibm.mqlight.api.CompletionListener; import com.ibm.mqlight.api.Delivery; import com.ibm.mqlight.api.DestinationAdapter; import com.ibm.mqlight.api.MalformedDelivery; import com.ibm.mqlight.api.NonBlockingClient; import com.ibm.mqlight.api.NonBlockingClientAdapter; import com.ibm.mqlight.api.QOS; import com.ibm.mqlight.api.SendOptions; import com.ibm.mqlight.api.SendOptions.SendOptionsBuilder; import com.ibm.mqlight.api.StringDelivery; import com.ibm.mqlight.api.SubscribeOptions; import com.ibm.mqlight.api.SubscribeOptions.SubscribeOptionsBuilder; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.amqp.AMQPWorkerThread.AMQPException; import com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFODelivery; import com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFOHashMap; import com.ibm.uk.hursley.perfharness.amqp.utils.MessageContainer.MESSAGE_TYPE; import com.ibm.uk.hursley.perfharness.util.TypedPropertyException; blocker.signal(map); } @Override public void onSuccess(NonBlockingClient client, Object context) { if (logEnabled) log("({0}, {1}): Subscribe - Completed",amqpAddress, topicPattern); blocker.signal(null); } }, null); // Wait for completion event HashMap map = blocker.pause(); if (map != null && map.containsKey("exception")) { if (logEnabled) log("({0}, {1}): Subscribe - Exception {2}",amqpAddress, topicPattern, map.get("exception").toString()); throw (Exception)map.get("exception"); } if (logEnabled) log("({0}, {1}): Subscribe - completed", amqpAddress, topicPattern); } /** * @param client * @throws Exception */ public BlockingJavaClient (final String amqpAddress, String clientId) throws Exception { this.amqpAddress = amqpAddress; this.transferParameters = new TransferParameters(); this.fifoDelivery = new FIFODelivery (amqpAddress);
final FIFOHashMap fifoCconnection = new FIFOHashMap(amqpAddress);
ot4i/perf-harness
AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/BlockingJavaClient.java
// Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/AMQPWorkerThread.java // public static class AMQPException extends Exception { // private static final long serialVersionUID = 1L; // // /** // * @param message // */ // public AMQPException(final String message) { // super(message); // } // // /** // * @param message // * @param cause // */ // public AMQPException(final String message, final Throwable cause) { // super(message, cause); // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/FIFO.java // public static class FIFODelivery extends FIFOAbs { // public FIFODelivery(final String reference) { // super(reference); // } // // /** // * Insert an item into the FIFO // * // * @param delivery // */ // public void put(final Delivery delivery) { // super.put(delivery); // } // // /** // * Removes a delivery message from the FIFO // * // * @return a delivery or null if exception. // * @throws AMQPException // * // */ // public Delivery get() throws AMQPException { // Object item = super.get(); // if (item instanceof Delivery) { // return (Delivery) item; // } // else { // throw new AMQPException("Internal error: expected Delivery but got " + item.getClass().getName()); // } // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/FIFO.java // public static class FIFOHashMap extends FIFOAbs { // public FIFOHashMap(final String reference) { // super(reference); // } // // // /** // * @param hashMap // */ // public void put(final HashMap<String, Object> hashMap) { // super.put(hashMap); // } // // // /* (non-Javadoc) // * @see com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFOAbs#get() // */ // @SuppressWarnings("unchecked") // public HashMap<String, Object> get() throws AMQPException { // Object item = super.get(); // if (item instanceof HashMap) { // return (HashMap<String, Object>) item; // } // else { // throw new AMQPException("Internal error: expected HashMap but got " + item.getClass().getName()); // } // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/MessageContainer.java // public enum MESSAGE_TYPE {STRING, BYTES};
import java.nio.ByteBuffer; import java.util.HashMap; import java.util.logging.Level; import com.ibm.mqlight.api.ClientException; import com.ibm.mqlight.api.ClientOptions; import com.ibm.mqlight.api.ClientState; import com.ibm.mqlight.api.CompletionListener; import com.ibm.mqlight.api.Delivery; import com.ibm.mqlight.api.DestinationAdapter; import com.ibm.mqlight.api.MalformedDelivery; import com.ibm.mqlight.api.NonBlockingClient; import com.ibm.mqlight.api.NonBlockingClientAdapter; import com.ibm.mqlight.api.QOS; import com.ibm.mqlight.api.SendOptions; import com.ibm.mqlight.api.SendOptions.SendOptionsBuilder; import com.ibm.mqlight.api.StringDelivery; import com.ibm.mqlight.api.SubscribeOptions; import com.ibm.mqlight.api.SubscribeOptions.SubscribeOptionsBuilder; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.amqp.AMQPWorkerThread.AMQPException; import com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFODelivery; import com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFOHashMap; import com.ibm.uk.hursley.perfharness.amqp.utils.MessageContainer.MESSAGE_TYPE; import com.ibm.uk.hursley.perfharness.util.TypedPropertyException;
fifoCconnection.put (map); Log.logger.info("*** Lost connection with Server ***"); // Report exception to delivery queue which acts as a wake-up if (fifoDelivery != null) fifoDelivery.put(amqpException); } }, null); // Wait for connect complete event. if (logEnabled) log("({0}): Create connection - wait on block", amqpAddress); HashMap<String,Object> map = fifoCconnection.get(); if (map.containsKey("exception")) { if (logEnabled) log("({0}): Create connection - Exception {1}",amqpAddress, map.get("exception").toString()); client.stop(null, null); throw (Exception)map.get("exception"); } if (logEnabled) log("({0}): Create connection - completed", amqpAddress); } /** * @param reference * @param topic * @param message * @throws Exception */ public void sendMessage (final String reference, final String topic, final MessageContainer message) throws Exception {
// Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/AMQPWorkerThread.java // public static class AMQPException extends Exception { // private static final long serialVersionUID = 1L; // // /** // * @param message // */ // public AMQPException(final String message) { // super(message); // } // // /** // * @param message // * @param cause // */ // public AMQPException(final String message, final Throwable cause) { // super(message, cause); // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/FIFO.java // public static class FIFODelivery extends FIFOAbs { // public FIFODelivery(final String reference) { // super(reference); // } // // /** // * Insert an item into the FIFO // * // * @param delivery // */ // public void put(final Delivery delivery) { // super.put(delivery); // } // // /** // * Removes a delivery message from the FIFO // * // * @return a delivery or null if exception. // * @throws AMQPException // * // */ // public Delivery get() throws AMQPException { // Object item = super.get(); // if (item instanceof Delivery) { // return (Delivery) item; // } // else { // throw new AMQPException("Internal error: expected Delivery but got " + item.getClass().getName()); // } // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/FIFO.java // public static class FIFOHashMap extends FIFOAbs { // public FIFOHashMap(final String reference) { // super(reference); // } // // // /** // * @param hashMap // */ // public void put(final HashMap<String, Object> hashMap) { // super.put(hashMap); // } // // // /* (non-Javadoc) // * @see com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFOAbs#get() // */ // @SuppressWarnings("unchecked") // public HashMap<String, Object> get() throws AMQPException { // Object item = super.get(); // if (item instanceof HashMap) { // return (HashMap<String, Object>) item; // } // else { // throw new AMQPException("Internal error: expected HashMap but got " + item.getClass().getName()); // } // } // } // // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/MessageContainer.java // public enum MESSAGE_TYPE {STRING, BYTES}; // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/BlockingJavaClient.java import java.nio.ByteBuffer; import java.util.HashMap; import java.util.logging.Level; import com.ibm.mqlight.api.ClientException; import com.ibm.mqlight.api.ClientOptions; import com.ibm.mqlight.api.ClientState; import com.ibm.mqlight.api.CompletionListener; import com.ibm.mqlight.api.Delivery; import com.ibm.mqlight.api.DestinationAdapter; import com.ibm.mqlight.api.MalformedDelivery; import com.ibm.mqlight.api.NonBlockingClient; import com.ibm.mqlight.api.NonBlockingClientAdapter; import com.ibm.mqlight.api.QOS; import com.ibm.mqlight.api.SendOptions; import com.ibm.mqlight.api.SendOptions.SendOptionsBuilder; import com.ibm.mqlight.api.StringDelivery; import com.ibm.mqlight.api.SubscribeOptions; import com.ibm.mqlight.api.SubscribeOptions.SubscribeOptionsBuilder; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.amqp.AMQPWorkerThread.AMQPException; import com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFODelivery; import com.ibm.uk.hursley.perfharness.amqp.utils.FIFO.FIFOHashMap; import com.ibm.uk.hursley.perfharness.amqp.utils.MessageContainer.MESSAGE_TYPE; import com.ibm.uk.hursley.perfharness.util.TypedPropertyException; fifoCconnection.put (map); Log.logger.info("*** Lost connection with Server ***"); // Report exception to delivery queue which acts as a wake-up if (fifoDelivery != null) fifoDelivery.put(amqpException); } }, null); // Wait for connect complete event. if (logEnabled) log("({0}): Create connection - wait on block", amqpAddress); HashMap<String,Object> map = fifoCconnection.get(); if (map.containsKey("exception")) { if (logEnabled) log("({0}): Create connection - Exception {1}",amqpAddress, map.get("exception").toString()); client.stop(null, null); throw (Exception)map.get("exception"); } if (logEnabled) log("({0}): Create connection - completed", amqpAddress); } /** * @param reference * @param topic * @param message * @throws Exception */ public void sendMessage (final String reference, final String topic, final MessageContainer message) throws Exception {
if (message.getMessageType() == MESSAGE_TYPE.STRING) {
ot4i/perf-harness
JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/r11/Requestor.java
// Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/DestinationWrapper.java // public final class DestinationWrapper<E extends Destination> { // // public E destination; // public String name; // // public DestinationWrapper( String name, E destination ) { // this.destination = destination; // this.name = name; // } // // }
import java.util.logging.Level; import javax.jms.Message; import javax.jms.Queue; import javax.jms.TemporaryQueue; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.WorkerThread; import com.ibm.uk.hursley.perfharness.jms.DestinationWrapper;
// Set correlationID for this thread onto the cached message if (Config.parms.getBoolean("co") ) { correlID = msgFactory.setJMSCorrelationID(this, outMessage); } // Get destination pair if multiple are configured. int destID = destFactory.generateDestinationID(getThreadNum()); String iq = Config.parms.getString("iq"); String oq = Config.parms.getString("oq"); if (destID >= 0) { iq += String.valueOf(destID); oq += String.valueOf(destID); } // Open queues destProducer = jmsProvider.lookupQueue(iq, session).destination; Log.logger.log( Level.FINE, "Creating sender on {0}", getDestinationName(destProducer)); messageProducer = session.createProducer(destProducer); String selector = null; if (correlID != null) { StringBuffer sb = new StringBuffer("JMSCorrelationID='"); sb.append(correlID); sb.append("'"); selector = sb.toString(); } if (!tempQueues) { //Use permanent queues
// Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/DestinationWrapper.java // public final class DestinationWrapper<E extends Destination> { // // public E destination; // public String name; // // public DestinationWrapper( String name, E destination ) { // this.destination = destination; // this.name = name; // } // // } // Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/r11/Requestor.java import java.util.logging.Level; import javax.jms.Message; import javax.jms.Queue; import javax.jms.TemporaryQueue; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.WorkerThread; import com.ibm.uk.hursley.perfharness.jms.DestinationWrapper; // Set correlationID for this thread onto the cached message if (Config.parms.getBoolean("co") ) { correlID = msgFactory.setJMSCorrelationID(this, outMessage); } // Get destination pair if multiple are configured. int destID = destFactory.generateDestinationID(getThreadNum()); String iq = Config.parms.getString("iq"); String oq = Config.parms.getString("oq"); if (destID >= 0) { iq += String.valueOf(destID); oq += String.valueOf(destID); } // Open queues destProducer = jmsProvider.lookupQueue(iq, session).destination; Log.logger.log( Level.FINE, "Creating sender on {0}", getDestinationName(destProducer)); messageProducer = session.createProducer(destProducer); String selector = null; if (correlID != null) { StringBuffer sb = new StringBuffer("JMSCorrelationID='"); sb.append(correlID); sb.append("'"); selector = sb.toString(); } if (!tempQueues) { //Use permanent queues
DestinationWrapper<Queue> consumerDestinationWrapper = jmsProvider.lookupQueue(oq, session);
ot4i/perf-harness
JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/providers/JMSProvider.java
// Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/DestinationWrapper.java // public final class DestinationWrapper<E extends Destination> { // // public E destination; // public String name; // // public DestinationWrapper( String name, E destination ) { // this.destination = destination; // this.name = name; // } // // }
import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSContext; import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.QueueConnectionFactory; import javax.jms.QueueSession; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; import javax.naming.NamingException; import com.ibm.uk.hursley.perfharness.WorkerThread; import com.ibm.uk.hursley.perfharness.jms.DestinationWrapper;
/********************************************************* {COPYRIGHT-TOP} *** * Copyright 2016 IBM Corporation * * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License * which accompanies this distribution, and is available at * http://opensource.org/licenses/MIT ********************************************************** {COPYRIGHT-END} **/ package com.ibm.uk.hursley.perfharness.jms.providers; public interface JMSProvider { public TopicConnectionFactory lookupTopicConnectionFactory(String name) throws JMSException, NamingException; public QueueConnectionFactory lookupQueueConnectionFactory(String name) throws JMSException, NamingException; public ConnectionFactory lookupConnectionFactory(String name) throws JMSException, NamingException;
// Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/DestinationWrapper.java // public final class DestinationWrapper<E extends Destination> { // // public E destination; // public String name; // // public DestinationWrapper( String name, E destination ) { // this.destination = destination; // this.name = name; // } // // } // Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/providers/JMSProvider.java import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSContext; import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.QueueConnectionFactory; import javax.jms.QueueSession; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; import javax.naming.NamingException; import com.ibm.uk.hursley.perfharness.WorkerThread; import com.ibm.uk.hursley.perfharness.jms.DestinationWrapper; /********************************************************* {COPYRIGHT-TOP} *** * Copyright 2016 IBM Corporation * * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License * which accompanies this distribution, and is available at * http://opensource.org/licenses/MIT ********************************************************** {COPYRIGHT-END} **/ package com.ibm.uk.hursley.perfharness.jms.providers; public interface JMSProvider { public TopicConnectionFactory lookupTopicConnectionFactory(String name) throws JMSException, NamingException; public QueueConnectionFactory lookupQueueConnectionFactory(String name) throws JMSException, NamingException; public ConnectionFactory lookupConnectionFactory(String name) throws JMSException, NamingException;
public DestinationWrapper<Queue> lookupQueue(String queue, QueueSession session)
ot4i/perf-harness
AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/FIFO.java
// Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/AMQPWorkerThread.java // public static class AMQPException extends Exception { // private static final long serialVersionUID = 1L; // // /** // * @param message // */ // public AMQPException(final String message) { // super(message); // } // // /** // * @param message // * @param cause // */ // public AMQPException(final String message, final Throwable cause) { // super(message, cause); // } // }
import java.util.HashMap; import java.util.concurrent.LinkedBlockingDeque; import com.ibm.mqlight.api.Delivery; import com.ibm.uk.hursley.perfharness.amqp.AMQPWorkerThread.AMQPException;
/********************************************************* {COPYRIGHT-TOP} *** * Copyright 2016 IBM Corporation * * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License * which accompanies this distribution, and is available at * http://opensource.org/licenses/MIT ********************************************************** {COPYRIGHT-END} **/ package com.ibm.uk.hursley.perfharness.amqp.utils; /** * @author ElliotGregory * * Outer class to contain the various sub classes for the FIFO facility. * */ public class FIFO { /** * @author ElliotGregory * */ public static class FIFODelivery extends FIFOAbs { public FIFODelivery(final String reference) { super(reference); } /** * Insert an item into the FIFO * * @param delivery */ public void put(final Delivery delivery) { super.put(delivery); } /** * Removes a delivery message from the FIFO * * @return a delivery or null if exception. * @throws AMQPException * */
// Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/AMQPWorkerThread.java // public static class AMQPException extends Exception { // private static final long serialVersionUID = 1L; // // /** // * @param message // */ // public AMQPException(final String message) { // super(message); // } // // /** // * @param message // * @param cause // */ // public AMQPException(final String message, final Throwable cause) { // super(message, cause); // } // } // Path: AMQPPerfHarness/src/com/ibm/uk/hursley/perfharness/amqp/utils/FIFO.java import java.util.HashMap; import java.util.concurrent.LinkedBlockingDeque; import com.ibm.mqlight.api.Delivery; import com.ibm.uk.hursley.perfharness.amqp.AMQPWorkerThread.AMQPException; /********************************************************* {COPYRIGHT-TOP} *** * Copyright 2016 IBM Corporation * * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License * which accompanies this distribution, and is available at * http://opensource.org/licenses/MIT ********************************************************** {COPYRIGHT-END} **/ package com.ibm.uk.hursley.perfharness.amqp.utils; /** * @author ElliotGregory * * Outer class to contain the various sub classes for the FIFO facility. * */ public class FIFO { /** * @author ElliotGregory * */ public static class FIFODelivery extends FIFOAbs { public FIFODelivery(final String reference) { super(reference); } /** * Insert an item into the FIFO * * @param delivery */ public void put(final Delivery delivery) { super.put(delivery); } /** * Removes a delivery message from the FIFO * * @return a delivery or null if exception. * @throws AMQPException * */
public Delivery get() throws AMQPException {
ot4i/perf-harness
JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/providers/WMB.java
// Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/DestinationWrapper.java // public final class DestinationWrapper<E extends Destination> { // // public E destination; // public String name; // // public DestinationWrapper( String name, E destination ) { // this.destination = destination; // this.name = name; // } // // }
import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; import javax.naming.NamingException; import com.ibm.mq.jms.MQConnectionFactory; import com.ibm.mq.jms.MQTopic; import com.ibm.mq.jms.MQTopicConnectionFactory; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.jms.DestinationWrapper; import com.ibm.msg.client.wmq.WMQConstants;
return topic; } public synchronized ConnectionFactory lookupConnectionFactory(String name) throws JMSException, NamingException { ConnectionFactory cf; if ( usingJNDI ) { //call the super method which will get the cf from JNDI and return just that return super.lookupConnectionFactory(name); } else if (usingMQ) { //call the super method which will set most of the MQ stuff but we will call our method as well to override/set anything for MB. cf = super.lookupConnectionFactory(name); configureWBIMBConnectionFactory( (MQConnectionFactory)cf ); } else { //we must be using IP or MC, lets create and setup the cf ourselves... cf = new MQConnectionFactory(); configureWBIMBConnectionFactory( (MQConnectionFactory)cf ); return cf; } // end if cf==null return cf; }
// Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/DestinationWrapper.java // public final class DestinationWrapper<E extends Destination> { // // public E destination; // public String name; // // public DestinationWrapper( String name, E destination ) { // this.destination = destination; // this.name = name; // } // // } // Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/providers/WMB.java import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; import javax.naming.NamingException; import com.ibm.mq.jms.MQConnectionFactory; import com.ibm.mq.jms.MQTopic; import com.ibm.mq.jms.MQTopicConnectionFactory; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.jms.DestinationWrapper; import com.ibm.msg.client.wmq.WMQConstants; return topic; } public synchronized ConnectionFactory lookupConnectionFactory(String name) throws JMSException, NamingException { ConnectionFactory cf; if ( usingJNDI ) { //call the super method which will get the cf from JNDI and return just that return super.lookupConnectionFactory(name); } else if (usingMQ) { //call the super method which will set most of the MQ stuff but we will call our method as well to override/set anything for MB. cf = super.lookupConnectionFactory(name); configureWBIMBConnectionFactory( (MQConnectionFactory)cf ); } else { //we must be using IP or MC, lets create and setup the cf ourselves... cf = new MQConnectionFactory(); configureWBIMBConnectionFactory( (MQConnectionFactory)cf ); return cf; } // end if cf==null return cf; }
public DestinationWrapper<Topic> lookupTopic( String topic, Session session ) throws JMSException, NamingException {
ot4i/perf-harness
JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/r20/Requestor.java
// Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/DestinationWrapper.java // public final class DestinationWrapper<E extends Destination> { // // public E destination; // public String name; // // public DestinationWrapper( String name, E destination ) { // this.destination = destination; // this.name = name; // } // // }
import java.util.logging.Level; import javax.jms.Message; import javax.jms.Queue; import javax.jms.TemporaryQueue; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.WorkerThread; import com.ibm.uk.hursley.perfharness.jms.DestinationWrapper;
/********************************************************* {COPYRIGHT-TOP} *** * Licensed Materials - Property of IBM * * IBM Performance Harness for Java Message Service * * (C) Copyright IBM Corp. 2005, 2007 All Rights Reserved. * * US Government Users Restricted Rights - Use, duplication, or * disclosure restricted by GSA ADP Schedule Contract with IBM Corp. ********************************************************** {COPYRIGHT-END} **/ /* * $Id: Requestor.java 548 2012-11-19 13:44:43Z gezagel $ * JMSPerfHarness $Name$ */ package com.ibm.uk.hursley.perfharness.jms.r20; //import javax.jms.Destination; /** * Puts a message to a queue then waits for a reply on another permanent or temporary queue. Currently * the only use of correlation identifiers is to keep using the same id for every * request (ie NOT to use the sent messageId of each request). This is much faster * for JMS applications. * * @author smassey@uk.ibm.com */ public final class Requestor extends JMS20WorkerThread implements WorkerThread.Paceable { @SuppressWarnings("unused") private static final String c = com.ibm.uk.hursley.perfharness.Copyright.COPYRIGHT; // IGNORE compiler warning protected Message inMessage = null; protected Message outMessage = null; protected String correlID = null; private static boolean tempQueues; private static boolean tempQueuePerMessage; public static void registerConfig() { Config.registerSelf(Requestor.class); //Use temporary queues if output queue (from application perspective) is not set tempQueues = Config.parms.getString("oq").length() == 0; //The current default is to use a temp queue per message //Its more performant to cache a temporary queue per thread/session tempQueuePerMessage = Config.parms.getBoolean("tqpm"); } /** * Constructor for JMSClientThread. * @param name */ public Requestor(String name) { super(name); } protected void buildJMSResources() throws Exception { super.buildJMSResources(); // Create message outMessage = msgFactory.createMessage(context); // Set correlationID for this thread onto the cached message if ( Config.parms.getBoolean("co") ) { correlID = msgFactory.setJMSCorrelationID(this, outMessage); } // Get destination pair if multiple are configured. int destID = destFactory.generateDestinationID(getThreadNum()); String iq = Config.parms.getString("iq"); String oq = Config.parms.getString("oq"); if (destID >= 0) { iq += String.valueOf(destID); oq += String.valueOf(destID); } // Open queues
// Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/DestinationWrapper.java // public final class DestinationWrapper<E extends Destination> { // // public E destination; // public String name; // // public DestinationWrapper( String name, E destination ) { // this.destination = destination; // this.name = name; // } // // } // Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/r20/Requestor.java import java.util.logging.Level; import javax.jms.Message; import javax.jms.Queue; import javax.jms.TemporaryQueue; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.WorkerThread; import com.ibm.uk.hursley.perfharness.jms.DestinationWrapper; /********************************************************* {COPYRIGHT-TOP} *** * Licensed Materials - Property of IBM * * IBM Performance Harness for Java Message Service * * (C) Copyright IBM Corp. 2005, 2007 All Rights Reserved. * * US Government Users Restricted Rights - Use, duplication, or * disclosure restricted by GSA ADP Schedule Contract with IBM Corp. ********************************************************** {COPYRIGHT-END} **/ /* * $Id: Requestor.java 548 2012-11-19 13:44:43Z gezagel $ * JMSPerfHarness $Name$ */ package com.ibm.uk.hursley.perfharness.jms.r20; //import javax.jms.Destination; /** * Puts a message to a queue then waits for a reply on another permanent or temporary queue. Currently * the only use of correlation identifiers is to keep using the same id for every * request (ie NOT to use the sent messageId of each request). This is much faster * for JMS applications. * * @author smassey@uk.ibm.com */ public final class Requestor extends JMS20WorkerThread implements WorkerThread.Paceable { @SuppressWarnings("unused") private static final String c = com.ibm.uk.hursley.perfharness.Copyright.COPYRIGHT; // IGNORE compiler warning protected Message inMessage = null; protected Message outMessage = null; protected String correlID = null; private static boolean tempQueues; private static boolean tempQueuePerMessage; public static void registerConfig() { Config.registerSelf(Requestor.class); //Use temporary queues if output queue (from application perspective) is not set tempQueues = Config.parms.getString("oq").length() == 0; //The current default is to use a temp queue per message //Its more performant to cache a temporary queue per thread/session tempQueuePerMessage = Config.parms.getBoolean("tqpm"); } /** * Constructor for JMSClientThread. * @param name */ public Requestor(String name) { super(name); } protected void buildJMSResources() throws Exception { super.buildJMSResources(); // Create message outMessage = msgFactory.createMessage(context); // Set correlationID for this thread onto the cached message if ( Config.parms.getBoolean("co") ) { correlID = msgFactory.setJMSCorrelationID(this, outMessage); } // Get destination pair if multiple are configured. int destID = destFactory.generateDestinationID(getThreadNum()); String iq = Config.parms.getString("iq"); String oq = Config.parms.getString("oq"); if (destID >= 0) { iq += String.valueOf(destID); oq += String.valueOf(destID); } // Open queues
DestinationWrapper<Queue> producerDestinationWrapper = jmsProvider.lookupQueue(iq, context);
ot4i/perf-harness
JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/r20/PutGet.java
// Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/DestinationWrapper.java // public final class DestinationWrapper<E extends Destination> { // // public E destination; // public String name; // // public DestinationWrapper( String name, E destination ) { // this.destination = destination; // this.name = name; // } // // }
import java.util.Random; import java.util.logging.Level; import javax.jms.Message; import javax.jms.Queue; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.WorkerThread; import com.ibm.uk.hursley.perfharness.jms.DestinationWrapper;
/********************************************************* {COPYRIGHT-TOP} *** * Licensed Materials - Property of IBM * * IBM Performance Harness for Java Message Service * * (C) Copyright IBM Corp. 2005, 2007 All Rights Reserved. * * US Government Users Restricted Rights - Use, duplication, or * disclosure restricted by GSA ADP Schedule Contract with IBM Corp. ********************************************************** {COPYRIGHT-END} **/ /* * $Id: PutGet.java 516 2010-12-20 10:28:14Z fentono $ * JMSPerfHarness $Name$ */ package com.ibm.uk.hursley.perfharness.jms.r20; /** * Sends a message then receives one from the same queue. Normal use is with * correlation identifier to ensure the same message is received. * @author smassey@uk.ibm.com */ public final class PutGet extends JMS20WorkerThread implements WorkerThread.Paceable { @SuppressWarnings("unused") private static final String c = com.ibm.uk.hursley.perfharness.Copyright.COPYRIGHT; // IGNORE compiler warning Message inMessage = null; Message outMessage = null; String correlID = null; public static void registerConfig() { Config.registerSelf(PutGet.class); } /** * Constructor for JMSClientThread. * @param name */ public PutGet(String name) { super(name); } protected void buildJMSResources() throws Exception { super.buildJMSResources(); // Open queues
// Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/DestinationWrapper.java // public final class DestinationWrapper<E extends Destination> { // // public E destination; // public String name; // // public DestinationWrapper( String name, E destination ) { // this.destination = destination; // this.name = name; // } // // } // Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/r20/PutGet.java import java.util.Random; import java.util.logging.Level; import javax.jms.Message; import javax.jms.Queue; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.WorkerThread; import com.ibm.uk.hursley.perfharness.jms.DestinationWrapper; /********************************************************* {COPYRIGHT-TOP} *** * Licensed Materials - Property of IBM * * IBM Performance Harness for Java Message Service * * (C) Copyright IBM Corp. 2005, 2007 All Rights Reserved. * * US Government Users Restricted Rights - Use, duplication, or * disclosure restricted by GSA ADP Schedule Contract with IBM Corp. ********************************************************** {COPYRIGHT-END} **/ /* * $Id: PutGet.java 516 2010-12-20 10:28:14Z fentono $ * JMSPerfHarness $Name$ */ package com.ibm.uk.hursley.perfharness.jms.r20; /** * Sends a message then receives one from the same queue. Normal use is with * correlation identifier to ensure the same message is received. * @author smassey@uk.ibm.com */ public final class PutGet extends JMS20WorkerThread implements WorkerThread.Paceable { @SuppressWarnings("unused") private static final String c = com.ibm.uk.hursley.perfharness.Copyright.COPYRIGHT; // IGNORE compiler warning Message inMessage = null; Message outMessage = null; String correlID = null; public static void registerConfig() { Config.registerSelf(PutGet.class); } /** * Constructor for JMSClientThread. * @param name */ public PutGet(String name) { super(name); } protected void buildJMSResources() throws Exception { super.buildJMSResources(); // Open queues
DestinationWrapper<Queue> producerDestinationWrapper = jmsProvider.lookupQueue(destFactory.generateDestination(getThreadNum()), context);
ot4i/perf-harness
JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/r20/Responder.java
// Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/DestinationWrapper.java // public final class DestinationWrapper<E extends Destination> { // // public E destination; // public String name; // // public DestinationWrapper( String name, E destination ) { // this.destination = destination; // this.name = name; // } // // }
import java.util.logging.Level; import javax.jms.Destination; import javax.jms.Message; import javax.jms.Queue; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.WorkerThread; import com.ibm.uk.hursley.perfharness.jms.DestinationWrapper;
/********************************************************* {COPYRIGHT-TOP} *** * Licensed Materials - Property of IBM * * IBM Performance Harness for Java Message Service * * (C) Copyright IBM Corp. 2005, 2007 All Rights Reserved. * * US Government Users Restricted Rights - Use, duplication, or * disclosure restricted by GSA ADP Schedule Contract with IBM Corp. ********************************************************** {COPYRIGHT-END} **/ /* * $Id: Responder.java 556 2013-09-27 15:17:24Z smassey $ * JMSPerfHarness $Name$ */ package com.ibm.uk.hursley.perfharness.jms.r20; /** * Takes messages off the request queue and places the same message on the reply queue. * Does not currently have an option to change the CorrelationId (in keeping with the * Requestor class). * @author smassey@uk.ibm.com */ public final class Responder extends JMS20WorkerThread implements WorkerThread.Paceable { @SuppressWarnings("unused") private static final String c = com.ibm.uk.hursley.perfharness.Copyright.COPYRIGHT; // IGNORE compiler warning Message inMessage = null; Message outMessage = null; //Use temporary reply queues private final boolean tempQueues = Config.parms.getString("oq").length() == 0; //Use input message for output message, else crete new output message private final boolean copyReplyFromRequest = Config.parms.getBoolean("cr"); //This is horrible using the same flag as requestor to mean different behaviour in the responder // -co requester - Use correlationID scheme // -co responder - Copy MsgID from input message to CorrelationID if set, else copy CorrelationID from input message private final boolean correlIDFromMsgID = Config.parms.getBoolean("co"); //Use fixed reply queues, avoids extraction of replyTo and costly destination comparison private final boolean fixedReplyQ = Config.parms.getBoolean("jfq"); public static void registerConfig() { Config.registerSelf(Responder.class); } /** * Constructor for JMSClientThread. * @param name */ public Responder(String name) { super(name); } protected void buildJMSResources() throws Exception { super.buildJMSResources(); // Get destination pair if multiple are configured. int destID = destFactory.generateDestinationID(getThreadNum()); String iq = Config.parms.getString("iq"); String oq = Config.parms.getString("oq"); if (destID >= 0) { iq += String.valueOf(destID); oq += String.valueOf(destID); }
// Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/DestinationWrapper.java // public final class DestinationWrapper<E extends Destination> { // // public E destination; // public String name; // // public DestinationWrapper( String name, E destination ) { // this.destination = destination; // this.name = name; // } // // } // Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/r20/Responder.java import java.util.logging.Level; import javax.jms.Destination; import javax.jms.Message; import javax.jms.Queue; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.WorkerThread; import com.ibm.uk.hursley.perfharness.jms.DestinationWrapper; /********************************************************* {COPYRIGHT-TOP} *** * Licensed Materials - Property of IBM * * IBM Performance Harness for Java Message Service * * (C) Copyright IBM Corp. 2005, 2007 All Rights Reserved. * * US Government Users Restricted Rights - Use, duplication, or * disclosure restricted by GSA ADP Schedule Contract with IBM Corp. ********************************************************** {COPYRIGHT-END} **/ /* * $Id: Responder.java 556 2013-09-27 15:17:24Z smassey $ * JMSPerfHarness $Name$ */ package com.ibm.uk.hursley.perfharness.jms.r20; /** * Takes messages off the request queue and places the same message on the reply queue. * Does not currently have an option to change the CorrelationId (in keeping with the * Requestor class). * @author smassey@uk.ibm.com */ public final class Responder extends JMS20WorkerThread implements WorkerThread.Paceable { @SuppressWarnings("unused") private static final String c = com.ibm.uk.hursley.perfharness.Copyright.COPYRIGHT; // IGNORE compiler warning Message inMessage = null; Message outMessage = null; //Use temporary reply queues private final boolean tempQueues = Config.parms.getString("oq").length() == 0; //Use input message for output message, else crete new output message private final boolean copyReplyFromRequest = Config.parms.getBoolean("cr"); //This is horrible using the same flag as requestor to mean different behaviour in the responder // -co requester - Use correlationID scheme // -co responder - Copy MsgID from input message to CorrelationID if set, else copy CorrelationID from input message private final boolean correlIDFromMsgID = Config.parms.getBoolean("co"); //Use fixed reply queues, avoids extraction of replyTo and costly destination comparison private final boolean fixedReplyQ = Config.parms.getBoolean("jfq"); public static void registerConfig() { Config.registerSelf(Responder.class); } /** * Constructor for JMSClientThread. * @param name */ public Responder(String name) { super(name); } protected void buildJMSResources() throws Exception { super.buildJMSResources(); // Get destination pair if multiple are configured. int destID = destFactory.generateDestinationID(getThreadNum()); String iq = Config.parms.getString("iq"); String oq = Config.parms.getString("oq"); if (destID >= 0) { iq += String.valueOf(destID); oq += String.valueOf(destID); }
DestinationWrapper<Queue> consumerDestinationWrapper = jmsProvider.lookupQueue(iq, context);
ot4i/perf-harness
JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/providers/JNDI.java
// Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/DestinationWrapper.java // public final class DestinationWrapper<E extends Destination> { // // public E destination; // public String name; // // public DestinationWrapper( String name, E destination ) { // this.destination = destination; // this.name = name; // } // // }
import java.io.File; import java.io.InputStream; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.logging.Level; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSContext; import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.QueueConnectionFactory; import javax.jms.QueueSession; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NameNotFoundException; import javax.naming.NamingException; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.jms.DestinationWrapper;
/********************************************************* {COPYRIGHT-TOP} *** * Copyright 2016 IBM Corporation * * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License * which accompanies this distribution, and is available at * http://opensource.org/licenses/MIT ********************************************************** {COPYRIGHT-END} **/ package com.ibm.uk.hursley.perfharness.jms.providers; /** * Provider independent access to JMS resources. All destination names will be * interpreted as the lookup name rather than the absolute name. * <p>This class also provides a base on which to build vendor-specific JMSProvider * implementations which may also use JNDI. */ public class JNDI extends AbstractJMSProvider { @SuppressWarnings("unused") private static final String c = com.ibm.uk.hursley.perfharness.Copyright.COPYRIGHT; // IGNORE compiler warning public static final String PSMODE = "PUBSUBMODE"; public static final String PSMODE_PUB = "PUB"; public static final String PSMODE_SUB = "SUB"; protected static boolean usingJNDI; /** * Validate parameters. The contents of <code>-ii</code> and <code>-iu</code> are not checked at this stage. */ public static void registerConfig() { Config.registerSelf( JNDI.class ); usingJNDI = ! "".equals( Config.parms.getString("cf") ) || Config.parms.getString("pc").equalsIgnoreCase("jndi"); } protected InitialContext initialContext = null; // // JMS 1.0.2 Methods // /** * Return a Queue object from JNDI */
// Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/DestinationWrapper.java // public final class DestinationWrapper<E extends Destination> { // // public E destination; // public String name; // // public DestinationWrapper( String name, E destination ) { // this.destination = destination; // this.name = name; // } // // } // Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/providers/JNDI.java import java.io.File; import java.io.InputStream; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.logging.Level; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSContext; import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.QueueConnectionFactory; import javax.jms.QueueSession; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NameNotFoundException; import javax.naming.NamingException; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.jms.DestinationWrapper; /********************************************************* {COPYRIGHT-TOP} *** * Copyright 2016 IBM Corporation * * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License * which accompanies this distribution, and is available at * http://opensource.org/licenses/MIT ********************************************************** {COPYRIGHT-END} **/ package com.ibm.uk.hursley.perfharness.jms.providers; /** * Provider independent access to JMS resources. All destination names will be * interpreted as the lookup name rather than the absolute name. * <p>This class also provides a base on which to build vendor-specific JMSProvider * implementations which may also use JNDI. */ public class JNDI extends AbstractJMSProvider { @SuppressWarnings("unused") private static final String c = com.ibm.uk.hursley.perfharness.Copyright.COPYRIGHT; // IGNORE compiler warning public static final String PSMODE = "PUBSUBMODE"; public static final String PSMODE_PUB = "PUB"; public static final String PSMODE_SUB = "SUB"; protected static boolean usingJNDI; /** * Validate parameters. The contents of <code>-ii</code> and <code>-iu</code> are not checked at this stage. */ public static void registerConfig() { Config.registerSelf( JNDI.class ); usingJNDI = ! "".equals( Config.parms.getString("cf") ) || Config.parms.getString("pc").equalsIgnoreCase("jndi"); } protected InitialContext initialContext = null; // // JMS 1.0.2 Methods // /** * Return a Queue object from JNDI */
protected DestinationWrapper<Queue> lookupQueueFromJNDI(String uri) throws NamingException {
ot4i/perf-harness
JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/providers/WebSphereMQ.java
// Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/DestinationWrapper.java // public final class DestinationWrapper<E extends Destination> { // // public E destination; // public String name; // // public DestinationWrapper( String name, E destination ) { // this.destination = destination; // this.name = name; // } // // }
import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.logging.Level; import javax.jms.ConnectionFactory; import javax.jms.JMSContext; import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.QueueConnectionFactory; import javax.jms.QueueSession; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; import javax.naming.NameAlreadyBoundException; import javax.naming.NamingException; import com.ibm.mq.jms.JMSC; import com.ibm.mq.constants.CMQC; import com.ibm.mq.jms.MQConnectionFactory; import com.ibm.mq.jms.MQDestination; import com.ibm.mq.jms.MQQueue; import com.ibm.mq.jms.MQQueueConnectionFactory; import com.ibm.mq.jms.MQTopic; import com.ibm.mq.jms.MQTopicConnectionFactory; import com.ibm.mq.pcf.CMQCFC; import com.ibm.mq.pcf.PCFMessage; import com.ibm.mq.pcf.PCFMessageAgent; import com.ibm.msg.client.wmq.WMQConstants; import com.ibm.msg.client.wmq.common.CommonConstants; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.jms.DestinationWrapper;
/** * Create a new vendor-specific ConnectionFactory (or delegate to JNDI if that is has been selected). */ public TopicConnectionFactory lookupTopicConnectionFactory(String name) throws JMSException,NamingException { if ( usingJNDI ) { return super.lookupTopicConnectionFactory(name); } else { MQTopicConnectionFactory tcf = new MQTopicConnectionFactory(); configureMQConnectionFactory(tcf); return tcf; } // end if tcf==null } /** * Create a new vendor-specific ConnectionFactory (or delegate to JNDI if that is has been selected). */ public synchronized QueueConnectionFactory lookupQueueConnectionFactory(String name) throws JMSException,NamingException { if ( usingJNDI ) { return super.lookupQueueConnectionFactory(name); } else { MQQueueConnectionFactory qcf = new MQQueueConnectionFactory(); configureMQConnectionFactory(qcf); return qcf; } // end if qcf==null }
// Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/DestinationWrapper.java // public final class DestinationWrapper<E extends Destination> { // // public E destination; // public String name; // // public DestinationWrapper( String name, E destination ) { // this.destination = destination; // this.name = name; // } // // } // Path: JMSPerfHarness/src/com/ibm/uk/hursley/perfharness/jms/providers/WebSphereMQ.java import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.logging.Level; import javax.jms.ConnectionFactory; import javax.jms.JMSContext; import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.QueueConnectionFactory; import javax.jms.QueueSession; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; import javax.naming.NameAlreadyBoundException; import javax.naming.NamingException; import com.ibm.mq.jms.JMSC; import com.ibm.mq.constants.CMQC; import com.ibm.mq.jms.MQConnectionFactory; import com.ibm.mq.jms.MQDestination; import com.ibm.mq.jms.MQQueue; import com.ibm.mq.jms.MQQueueConnectionFactory; import com.ibm.mq.jms.MQTopic; import com.ibm.mq.jms.MQTopicConnectionFactory; import com.ibm.mq.pcf.CMQCFC; import com.ibm.mq.pcf.PCFMessage; import com.ibm.mq.pcf.PCFMessageAgent; import com.ibm.msg.client.wmq.WMQConstants; import com.ibm.msg.client.wmq.common.CommonConstants; import com.ibm.uk.hursley.perfharness.Config; import com.ibm.uk.hursley.perfharness.Log; import com.ibm.uk.hursley.perfharness.jms.DestinationWrapper; /** * Create a new vendor-specific ConnectionFactory (or delegate to JNDI if that is has been selected). */ public TopicConnectionFactory lookupTopicConnectionFactory(String name) throws JMSException,NamingException { if ( usingJNDI ) { return super.lookupTopicConnectionFactory(name); } else { MQTopicConnectionFactory tcf = new MQTopicConnectionFactory(); configureMQConnectionFactory(tcf); return tcf; } // end if tcf==null } /** * Create a new vendor-specific ConnectionFactory (or delegate to JNDI if that is has been selected). */ public synchronized QueueConnectionFactory lookupQueueConnectionFactory(String name) throws JMSException,NamingException { if ( usingJNDI ) { return super.lookupQueueConnectionFactory(name); } else { MQQueueConnectionFactory qcf = new MQQueueConnectionFactory(); configureMQConnectionFactory(qcf); return qcf; } // end if qcf==null }
public DestinationWrapper<Queue> lookupQueue( String queue, QueueSession session ) throws JMSException, NamingException {
rhritz/kyberia-haiku
app/controllers/Application.java
// Path: app/models/actions/Action.java // public abstract class Action { // // private static Map<String,Action> actions = Maps.newHashMap(); // private String name; // // public abstract Boolean apply( // Request request, // User user, // Map<String, String> params // ); // // public static Boolean doAction(String acName, // Request request, // User user, // Map<String, String> params) { // Action action = actions.get(acName.toLowerCase()); // if (action == null) { // Logger.info("No Action found for action string:" + acName); // return Boolean.FALSE; // } else { // Logger.info("Action found for action string:" + acName); // return action.apply(request, user, params); // } // } // // // instantiate all Actions // public static void start() { // for (Class c : // Collections2.filter(MongoEntity.getClasses("models.actions"), // new Predicate<Class>() { // public boolean apply(Class t) { // return ! "models.actions.Action".equals(t.getName()); // } // }) // ) // actions.put(c.getSimpleName().toLowerCase(), getByName(c.getName())); // } // // private static <T extends Action> T getByName(String name) { // Logger.info("Action.getByName::" + name); // T le = null; // try { // Class<T> fu = (Class<T>) Class.forName(name); // le = fu.newInstance(); // } catch (Exception ex) { // Logger.info("Action.getByName::" + name + ex.toString()); // } // return le; // } // // protected String getName() { // return name; // } // // private void setName(String newName) { // name = newName; // } // // } // // Path: app/models/MongoEntity.java // public static ObjectId toId(String x) { // ObjectId bubu = null; // try { bubu = new ObjectId(x);} catch (Exception e ) {}; // return bubu; // }
import models.actions.Action; import java.util.Map; import org.bson.types.ObjectId; import java.io.File; import play.mvc.*; import play.Logger; import models.*; import play.cache.Cache; import play.mvc.Controller; import static models.MongoEntity.toId;
/* Kyberia Haiku - advanced community web application Copyright (C) 2010 Robert Hritz This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package controllers; @With(Secure.class) public class Application extends Controller { @Before static void setConnectedUser() { renderArgs.put("reqstart", System.currentTimeMillis()); String uid; if(Security.isConnected()) { uid = session.get(User.ID); renderArgs.put("user", session.get(User.USERNAME)); renderArgs.put("userid", uid); renderArgs.put("uid", uid);
// Path: app/models/actions/Action.java // public abstract class Action { // // private static Map<String,Action> actions = Maps.newHashMap(); // private String name; // // public abstract Boolean apply( // Request request, // User user, // Map<String, String> params // ); // // public static Boolean doAction(String acName, // Request request, // User user, // Map<String, String> params) { // Action action = actions.get(acName.toLowerCase()); // if (action == null) { // Logger.info("No Action found for action string:" + acName); // return Boolean.FALSE; // } else { // Logger.info("Action found for action string:" + acName); // return action.apply(request, user, params); // } // } // // // instantiate all Actions // public static void start() { // for (Class c : // Collections2.filter(MongoEntity.getClasses("models.actions"), // new Predicate<Class>() { // public boolean apply(Class t) { // return ! "models.actions.Action".equals(t.getName()); // } // }) // ) // actions.put(c.getSimpleName().toLowerCase(), getByName(c.getName())); // } // // private static <T extends Action> T getByName(String name) { // Logger.info("Action.getByName::" + name); // T le = null; // try { // Class<T> fu = (Class<T>) Class.forName(name); // le = fu.newInstance(); // } catch (Exception ex) { // Logger.info("Action.getByName::" + name + ex.toString()); // } // return le; // } // // protected String getName() { // return name; // } // // private void setName(String newName) { // name = newName; // } // // } // // Path: app/models/MongoEntity.java // public static ObjectId toId(String x) { // ObjectId bubu = null; // try { bubu = new ObjectId(x);} catch (Exception e ) {}; // return bubu; // } // Path: app/controllers/Application.java import models.actions.Action; import java.util.Map; import org.bson.types.ObjectId; import java.io.File; import play.mvc.*; import play.Logger; import models.*; import play.cache.Cache; import play.mvc.Controller; import static models.MongoEntity.toId; /* Kyberia Haiku - advanced community web application Copyright (C) 2010 Robert Hritz This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package controllers; @With(Secure.class) public class Application extends Controller { @Before static void setConnectedUser() { renderArgs.put("reqstart", System.currentTimeMillis()); String uid; if(Security.isConnected()) { uid = session.get(User.ID); renderArgs.put("user", session.get(User.USERNAME)); renderArgs.put("userid", uid); renderArgs.put("uid", uid);
renderArgs.put("newMail", MessageThread.getUnreadMailNotif(toId(uid)));
rhritz/kyberia-haiku
app/controllers/Application.java
// Path: app/models/actions/Action.java // public abstract class Action { // // private static Map<String,Action> actions = Maps.newHashMap(); // private String name; // // public abstract Boolean apply( // Request request, // User user, // Map<String, String> params // ); // // public static Boolean doAction(String acName, // Request request, // User user, // Map<String, String> params) { // Action action = actions.get(acName.toLowerCase()); // if (action == null) { // Logger.info("No Action found for action string:" + acName); // return Boolean.FALSE; // } else { // Logger.info("Action found for action string:" + acName); // return action.apply(request, user, params); // } // } // // // instantiate all Actions // public static void start() { // for (Class c : // Collections2.filter(MongoEntity.getClasses("models.actions"), // new Predicate<Class>() { // public boolean apply(Class t) { // return ! "models.actions.Action".equals(t.getName()); // } // }) // ) // actions.put(c.getSimpleName().toLowerCase(), getByName(c.getName())); // } // // private static <T extends Action> T getByName(String name) { // Logger.info("Action.getByName::" + name); // T le = null; // try { // Class<T> fu = (Class<T>) Class.forName(name); // le = fu.newInstance(); // } catch (Exception ex) { // Logger.info("Action.getByName::" + name + ex.toString()); // } // return le; // } // // protected String getName() { // return name; // } // // private void setName(String newName) { // name = newName; // } // // } // // Path: app/models/MongoEntity.java // public static ObjectId toId(String x) { // ObjectId bubu = null; // try { bubu = new ObjectId(x);} catch (Exception e ) {}; // return bubu; // }
import models.actions.Action; import java.util.Map; import org.bson.types.ObjectId; import java.io.File; import play.mvc.*; import play.Logger; import models.*; import play.cache.Cache; import play.mvc.Controller; import static models.MongoEntity.toId;
p = "Node"; } // .. somehow somewhere throw an error } // TODO apply ViewTemplate too Page page = Page.loadByName(p); if (page != null) { request.args.put("app-page", page); } } @After static void measureTime() { Long start = renderArgs.get("reqstart", Long.class); Long duration = System.currentTimeMillis() - start; Logger.info("Request duration " + duration); } public static void index() { viewPage("main"); } // Actions for view (get) -> Page // # whatever1:action : edit(showEditNode), new(viewNodeUpdates), '' -> viewNode // # pars: page, p (pageNum), ..? public static void getNode(String id) { String ac = params.get("action"); // or rs if (ac != null) { // or something else is wrong
// Path: app/models/actions/Action.java // public abstract class Action { // // private static Map<String,Action> actions = Maps.newHashMap(); // private String name; // // public abstract Boolean apply( // Request request, // User user, // Map<String, String> params // ); // // public static Boolean doAction(String acName, // Request request, // User user, // Map<String, String> params) { // Action action = actions.get(acName.toLowerCase()); // if (action == null) { // Logger.info("No Action found for action string:" + acName); // return Boolean.FALSE; // } else { // Logger.info("Action found for action string:" + acName); // return action.apply(request, user, params); // } // } // // // instantiate all Actions // public static void start() { // for (Class c : // Collections2.filter(MongoEntity.getClasses("models.actions"), // new Predicate<Class>() { // public boolean apply(Class t) { // return ! "models.actions.Action".equals(t.getName()); // } // }) // ) // actions.put(c.getSimpleName().toLowerCase(), getByName(c.getName())); // } // // private static <T extends Action> T getByName(String name) { // Logger.info("Action.getByName::" + name); // T le = null; // try { // Class<T> fu = (Class<T>) Class.forName(name); // le = fu.newInstance(); // } catch (Exception ex) { // Logger.info("Action.getByName::" + name + ex.toString()); // } // return le; // } // // protected String getName() { // return name; // } // // private void setName(String newName) { // name = newName; // } // // } // // Path: app/models/MongoEntity.java // public static ObjectId toId(String x) { // ObjectId bubu = null; // try { bubu = new ObjectId(x);} catch (Exception e ) {}; // return bubu; // } // Path: app/controllers/Application.java import models.actions.Action; import java.util.Map; import org.bson.types.ObjectId; import java.io.File; import play.mvc.*; import play.Logger; import models.*; import play.cache.Cache; import play.mvc.Controller; import static models.MongoEntity.toId; p = "Node"; } // .. somehow somewhere throw an error } // TODO apply ViewTemplate too Page page = Page.loadByName(p); if (page != null) { request.args.put("app-page", page); } } @After static void measureTime() { Long start = renderArgs.get("reqstart", Long.class); Long duration = System.currentTimeMillis() - start; Logger.info("Request duration " + duration); } public static void index() { viewPage("main"); } // Actions for view (get) -> Page // # whatever1:action : edit(showEditNode), new(viewNodeUpdates), '' -> viewNode // # pars: page, p (pageNum), ..? public static void getNode(String id) { String ac = params.get("action"); // or rs if (ac != null) { // or something else is wrong
Action.doAction(ac, request, getUser(), params.allSimple());
rhritz/kyberia-haiku
app/plugins/MongoDB.java
// Path: app/models/MongoEntity.java // public static ObjectId toId(String x) { // ObjectId bubu = null; // try { bubu = new ObjectId(x);} catch (Exception e ) {}; // return bubu; // }
import models.*; import play.Logger; import play.Play; import static models.MongoEntity.toId; import com.mongodb.Mongo; import com.mongodb.DB; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.google.code.morphia.Morphia; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import java.util.LinkedList; import java.util.List; import org.bson.types.ObjectId;
public static DB getDB() { return db; } protected static Mongo getMongo() { return mongo; } public static void shutdown() { Logger.info("Mongo stopping"); } public static Morphia getMorphia() { return morphia; } public static void save(MongoEntity m) { m.getCollection().insert(morphia.toDBObject(m)); } public static void update(MongoEntity m) { m.getCollection().save(morphia.toDBObject(m)); } public static void delete(MongoEntity m) { m.getCollection().remove(morphia.toDBObject(m)); } public static <T> T load(String id, String col, Class<T> entityClass) {
// Path: app/models/MongoEntity.java // public static ObjectId toId(String x) { // ObjectId bubu = null; // try { bubu = new ObjectId(x);} catch (Exception e ) {}; // return bubu; // } // Path: app/plugins/MongoDB.java import models.*; import play.Logger; import play.Play; import static models.MongoEntity.toId; import com.mongodb.Mongo; import com.mongodb.DB; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.google.code.morphia.Morphia; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import java.util.LinkedList; import java.util.List; import org.bson.types.ObjectId; public static DB getDB() { return db; } protected static Mongo getMongo() { return mongo; } public static void shutdown() { Logger.info("Mongo stopping"); } public static Morphia getMorphia() { return morphia; } public static void save(MongoEntity m) { m.getCollection().insert(morphia.toDBObject(m)); } public static void update(MongoEntity m) { m.getCollection().save(morphia.toDBObject(m)); } public static void delete(MongoEntity m) { m.getCollection().remove(morphia.toDBObject(m)); } public static <T> T load(String id, String col, Class<T> entityClass) {
return load(toId(id), col, entityClass);
policeman-tools/forbidden-apis
src/test/java/de/thetaphi/forbiddenapis/AsmUtilsTest.java
// Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static Pattern glob2Pattern(String... globs) { // final StringBuilder regex = new StringBuilder(); // boolean needOr = false; // for (String glob : globs) { // if (needOr) { // regex.append('|'); // } // int i = 0, len = glob.length(); // while (i < len) { // char c = glob.charAt(i++); // switch (c) { // case '*': // if (i < len && glob.charAt(i) == '*') { // // crosses package boundaries // regex.append(".*"); // i++; // } else { // // do not cross package boundaries // regex.append("[^.]*"); // } // break; // // case '?': // // do not cross package boundaries // regex.append("[^.]"); // break; // // default: // if (isRegexMeta(c)) { // regex.append('\\'); // } // regex.append(c); // } // } // needOr = true; // } // return Pattern.compile(regex.toString(), 0); // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isGlob(String s) { // return s.indexOf('*') >= 0 || s.indexOf('?') >= 0; // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isPortableRuntimeClass(String className) { // return PORTABLE_RUNTIME_PACKAGE_PATTERN.matcher(className).matches(); // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isRuntimeModule(String module) { // return module != null && RUNTIME_MODULES_PATTERN.matcher(module).matches(); // }
import static de.thetaphi.forbiddenapis.AsmUtils.glob2Pattern; import static de.thetaphi.forbiddenapis.AsmUtils.isGlob; import static de.thetaphi.forbiddenapis.AsmUtils.isPortableRuntimeClass; import static de.thetaphi.forbiddenapis.AsmUtils.isRuntimeModule; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.regex.Pattern; import org.junit.Test;
/* * (C) Copyright Uwe Schindler (Generics Policeman) and others. * * 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 de.thetaphi.forbiddenapis; public final class AsmUtilsTest { @Test public void testIsGlob() {
// Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static Pattern glob2Pattern(String... globs) { // final StringBuilder regex = new StringBuilder(); // boolean needOr = false; // for (String glob : globs) { // if (needOr) { // regex.append('|'); // } // int i = 0, len = glob.length(); // while (i < len) { // char c = glob.charAt(i++); // switch (c) { // case '*': // if (i < len && glob.charAt(i) == '*') { // // crosses package boundaries // regex.append(".*"); // i++; // } else { // // do not cross package boundaries // regex.append("[^.]*"); // } // break; // // case '?': // // do not cross package boundaries // regex.append("[^.]"); // break; // // default: // if (isRegexMeta(c)) { // regex.append('\\'); // } // regex.append(c); // } // } // needOr = true; // } // return Pattern.compile(regex.toString(), 0); // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isGlob(String s) { // return s.indexOf('*') >= 0 || s.indexOf('?') >= 0; // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isPortableRuntimeClass(String className) { // return PORTABLE_RUNTIME_PACKAGE_PATTERN.matcher(className).matches(); // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isRuntimeModule(String module) { // return module != null && RUNTIME_MODULES_PATTERN.matcher(module).matches(); // } // Path: src/test/java/de/thetaphi/forbiddenapis/AsmUtilsTest.java import static de.thetaphi.forbiddenapis.AsmUtils.glob2Pattern; import static de.thetaphi.forbiddenapis.AsmUtils.isGlob; import static de.thetaphi.forbiddenapis.AsmUtils.isPortableRuntimeClass; import static de.thetaphi.forbiddenapis.AsmUtils.isRuntimeModule; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.regex.Pattern; import org.junit.Test; /* * (C) Copyright Uwe Schindler (Generics Policeman) and others. * * 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 de.thetaphi.forbiddenapis; public final class AsmUtilsTest { @Test public void testIsGlob() {
assertTrue(isGlob("a.b.c.*"));
policeman-tools/forbidden-apis
src/test/java/de/thetaphi/forbiddenapis/AsmUtilsTest.java
// Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static Pattern glob2Pattern(String... globs) { // final StringBuilder regex = new StringBuilder(); // boolean needOr = false; // for (String glob : globs) { // if (needOr) { // regex.append('|'); // } // int i = 0, len = glob.length(); // while (i < len) { // char c = glob.charAt(i++); // switch (c) { // case '*': // if (i < len && glob.charAt(i) == '*') { // // crosses package boundaries // regex.append(".*"); // i++; // } else { // // do not cross package boundaries // regex.append("[^.]*"); // } // break; // // case '?': // // do not cross package boundaries // regex.append("[^.]"); // break; // // default: // if (isRegexMeta(c)) { // regex.append('\\'); // } // regex.append(c); // } // } // needOr = true; // } // return Pattern.compile(regex.toString(), 0); // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isGlob(String s) { // return s.indexOf('*') >= 0 || s.indexOf('?') >= 0; // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isPortableRuntimeClass(String className) { // return PORTABLE_RUNTIME_PACKAGE_PATTERN.matcher(className).matches(); // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isRuntimeModule(String module) { // return module != null && RUNTIME_MODULES_PATTERN.matcher(module).matches(); // }
import static de.thetaphi.forbiddenapis.AsmUtils.glob2Pattern; import static de.thetaphi.forbiddenapis.AsmUtils.isGlob; import static de.thetaphi.forbiddenapis.AsmUtils.isPortableRuntimeClass; import static de.thetaphi.forbiddenapis.AsmUtils.isRuntimeModule; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.regex.Pattern; import org.junit.Test;
/* * (C) Copyright Uwe Schindler (Generics Policeman) and others. * * 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 de.thetaphi.forbiddenapis; public final class AsmUtilsTest { @Test public void testIsGlob() { assertTrue(isGlob("a.b.c.*")); assertTrue(isGlob("sun.**")); assertTrue(isGlob("a?bc.x")); assertFalse(isGlob(Object.class.getName())); assertFalse(isGlob(getClass().getName())); assertFalse(isGlob("sun.misc.Unsafe$1")); } @Test public void testGlob() {
// Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static Pattern glob2Pattern(String... globs) { // final StringBuilder regex = new StringBuilder(); // boolean needOr = false; // for (String glob : globs) { // if (needOr) { // regex.append('|'); // } // int i = 0, len = glob.length(); // while (i < len) { // char c = glob.charAt(i++); // switch (c) { // case '*': // if (i < len && glob.charAt(i) == '*') { // // crosses package boundaries // regex.append(".*"); // i++; // } else { // // do not cross package boundaries // regex.append("[^.]*"); // } // break; // // case '?': // // do not cross package boundaries // regex.append("[^.]"); // break; // // default: // if (isRegexMeta(c)) { // regex.append('\\'); // } // regex.append(c); // } // } // needOr = true; // } // return Pattern.compile(regex.toString(), 0); // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isGlob(String s) { // return s.indexOf('*') >= 0 || s.indexOf('?') >= 0; // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isPortableRuntimeClass(String className) { // return PORTABLE_RUNTIME_PACKAGE_PATTERN.matcher(className).matches(); // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isRuntimeModule(String module) { // return module != null && RUNTIME_MODULES_PATTERN.matcher(module).matches(); // } // Path: src/test/java/de/thetaphi/forbiddenapis/AsmUtilsTest.java import static de.thetaphi.forbiddenapis.AsmUtils.glob2Pattern; import static de.thetaphi.forbiddenapis.AsmUtils.isGlob; import static de.thetaphi.forbiddenapis.AsmUtils.isPortableRuntimeClass; import static de.thetaphi.forbiddenapis.AsmUtils.isRuntimeModule; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.regex.Pattern; import org.junit.Test; /* * (C) Copyright Uwe Schindler (Generics Policeman) and others. * * 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 de.thetaphi.forbiddenapis; public final class AsmUtilsTest { @Test public void testIsGlob() { assertTrue(isGlob("a.b.c.*")); assertTrue(isGlob("sun.**")); assertTrue(isGlob("a?bc.x")); assertFalse(isGlob(Object.class.getName())); assertFalse(isGlob(getClass().getName())); assertFalse(isGlob("sun.misc.Unsafe$1")); } @Test public void testGlob() {
Pattern pat = glob2Pattern("a.b.c.*");
policeman-tools/forbidden-apis
src/test/java/de/thetaphi/forbiddenapis/AsmUtilsTest.java
// Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static Pattern glob2Pattern(String... globs) { // final StringBuilder regex = new StringBuilder(); // boolean needOr = false; // for (String glob : globs) { // if (needOr) { // regex.append('|'); // } // int i = 0, len = glob.length(); // while (i < len) { // char c = glob.charAt(i++); // switch (c) { // case '*': // if (i < len && glob.charAt(i) == '*') { // // crosses package boundaries // regex.append(".*"); // i++; // } else { // // do not cross package boundaries // regex.append("[^.]*"); // } // break; // // case '?': // // do not cross package boundaries // regex.append("[^.]"); // break; // // default: // if (isRegexMeta(c)) { // regex.append('\\'); // } // regex.append(c); // } // } // needOr = true; // } // return Pattern.compile(regex.toString(), 0); // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isGlob(String s) { // return s.indexOf('*') >= 0 || s.indexOf('?') >= 0; // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isPortableRuntimeClass(String className) { // return PORTABLE_RUNTIME_PACKAGE_PATTERN.matcher(className).matches(); // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isRuntimeModule(String module) { // return module != null && RUNTIME_MODULES_PATTERN.matcher(module).matches(); // }
import static de.thetaphi.forbiddenapis.AsmUtils.glob2Pattern; import static de.thetaphi.forbiddenapis.AsmUtils.isGlob; import static de.thetaphi.forbiddenapis.AsmUtils.isPortableRuntimeClass; import static de.thetaphi.forbiddenapis.AsmUtils.isRuntimeModule; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.regex.Pattern; import org.junit.Test;
assertFalse(pat.matcher("a.b.c.d.e").matches()); pat = glob2Pattern("a.b.c.**"); assertTrue(pat.matcher("a.b.c.d").matches()); assertTrue(pat.matcher("a.b.c.def").matches()); assertTrue(pat.matcher("a.b.c.d.e").matches()); assertTrue(pat.matcher("a.b.c.d.e.f").matches()); pat = glob2Pattern("sun.*.*"); assertTrue(pat.matcher("sun.misc.Unsafe").matches()); assertTrue(pat.matcher("sun.misc.Unsafe$1").matches()); assertFalse(pat.matcher("sun.misc.Unsafe.xy").matches()); pat = glob2Pattern("java.**.Array?"); assertTrue(pat.matcher("java.util.Arrays").matches()); assertFalse(pat.matcher("java.util.ArrayList").matches()); assertFalse(pat.matcher("java.util.Array").matches()); assertTrue(pat.matcher("java.lang.reflect.Arrays").matches()); } @Test public void testCrazyPatterns() { // those should not cause havoc: assertEquals("java\\.\\{.*\\}\\.Array", glob2Pattern("java.{**}.Array").pattern()); assertEquals("java\\./.*<>\\.Array\\$1", glob2Pattern("java./**<>.Array$1").pattern()); assertEquals("\\+\\^\\$", glob2Pattern("+^$").pattern()); } @Test public void testPortableRuntime() {
// Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static Pattern glob2Pattern(String... globs) { // final StringBuilder regex = new StringBuilder(); // boolean needOr = false; // for (String glob : globs) { // if (needOr) { // regex.append('|'); // } // int i = 0, len = glob.length(); // while (i < len) { // char c = glob.charAt(i++); // switch (c) { // case '*': // if (i < len && glob.charAt(i) == '*') { // // crosses package boundaries // regex.append(".*"); // i++; // } else { // // do not cross package boundaries // regex.append("[^.]*"); // } // break; // // case '?': // // do not cross package boundaries // regex.append("[^.]"); // break; // // default: // if (isRegexMeta(c)) { // regex.append('\\'); // } // regex.append(c); // } // } // needOr = true; // } // return Pattern.compile(regex.toString(), 0); // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isGlob(String s) { // return s.indexOf('*') >= 0 || s.indexOf('?') >= 0; // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isPortableRuntimeClass(String className) { // return PORTABLE_RUNTIME_PACKAGE_PATTERN.matcher(className).matches(); // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isRuntimeModule(String module) { // return module != null && RUNTIME_MODULES_PATTERN.matcher(module).matches(); // } // Path: src/test/java/de/thetaphi/forbiddenapis/AsmUtilsTest.java import static de.thetaphi.forbiddenapis.AsmUtils.glob2Pattern; import static de.thetaphi.forbiddenapis.AsmUtils.isGlob; import static de.thetaphi.forbiddenapis.AsmUtils.isPortableRuntimeClass; import static de.thetaphi.forbiddenapis.AsmUtils.isRuntimeModule; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.regex.Pattern; import org.junit.Test; assertFalse(pat.matcher("a.b.c.d.e").matches()); pat = glob2Pattern("a.b.c.**"); assertTrue(pat.matcher("a.b.c.d").matches()); assertTrue(pat.matcher("a.b.c.def").matches()); assertTrue(pat.matcher("a.b.c.d.e").matches()); assertTrue(pat.matcher("a.b.c.d.e.f").matches()); pat = glob2Pattern("sun.*.*"); assertTrue(pat.matcher("sun.misc.Unsafe").matches()); assertTrue(pat.matcher("sun.misc.Unsafe$1").matches()); assertFalse(pat.matcher("sun.misc.Unsafe.xy").matches()); pat = glob2Pattern("java.**.Array?"); assertTrue(pat.matcher("java.util.Arrays").matches()); assertFalse(pat.matcher("java.util.ArrayList").matches()); assertFalse(pat.matcher("java.util.Array").matches()); assertTrue(pat.matcher("java.lang.reflect.Arrays").matches()); } @Test public void testCrazyPatterns() { // those should not cause havoc: assertEquals("java\\.\\{.*\\}\\.Array", glob2Pattern("java.{**}.Array").pattern()); assertEquals("java\\./.*<>\\.Array\\$1", glob2Pattern("java./**<>.Array$1").pattern()); assertEquals("\\+\\^\\$", glob2Pattern("+^$").pattern()); } @Test public void testPortableRuntime() {
assertFalse(isPortableRuntimeClass("sun.misc.Unsafe"));
policeman-tools/forbidden-apis
src/test/java/de/thetaphi/forbiddenapis/AsmUtilsTest.java
// Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static Pattern glob2Pattern(String... globs) { // final StringBuilder regex = new StringBuilder(); // boolean needOr = false; // for (String glob : globs) { // if (needOr) { // regex.append('|'); // } // int i = 0, len = glob.length(); // while (i < len) { // char c = glob.charAt(i++); // switch (c) { // case '*': // if (i < len && glob.charAt(i) == '*') { // // crosses package boundaries // regex.append(".*"); // i++; // } else { // // do not cross package boundaries // regex.append("[^.]*"); // } // break; // // case '?': // // do not cross package boundaries // regex.append("[^.]"); // break; // // default: // if (isRegexMeta(c)) { // regex.append('\\'); // } // regex.append(c); // } // } // needOr = true; // } // return Pattern.compile(regex.toString(), 0); // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isGlob(String s) { // return s.indexOf('*') >= 0 || s.indexOf('?') >= 0; // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isPortableRuntimeClass(String className) { // return PORTABLE_RUNTIME_PACKAGE_PATTERN.matcher(className).matches(); // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isRuntimeModule(String module) { // return module != null && RUNTIME_MODULES_PATTERN.matcher(module).matches(); // }
import static de.thetaphi.forbiddenapis.AsmUtils.glob2Pattern; import static de.thetaphi.forbiddenapis.AsmUtils.isGlob; import static de.thetaphi.forbiddenapis.AsmUtils.isPortableRuntimeClass; import static de.thetaphi.forbiddenapis.AsmUtils.isRuntimeModule; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.regex.Pattern; import org.junit.Test;
assertFalse(pat.matcher("sun.misc.Unsafe.xy").matches()); pat = glob2Pattern("java.**.Array?"); assertTrue(pat.matcher("java.util.Arrays").matches()); assertFalse(pat.matcher("java.util.ArrayList").matches()); assertFalse(pat.matcher("java.util.Array").matches()); assertTrue(pat.matcher("java.lang.reflect.Arrays").matches()); } @Test public void testCrazyPatterns() { // those should not cause havoc: assertEquals("java\\.\\{.*\\}\\.Array", glob2Pattern("java.{**}.Array").pattern()); assertEquals("java\\./.*<>\\.Array\\$1", glob2Pattern("java./**<>.Array$1").pattern()); assertEquals("\\+\\^\\$", glob2Pattern("+^$").pattern()); } @Test public void testPortableRuntime() { assertFalse(isPortableRuntimeClass("sun.misc.Unsafe")); assertFalse(isPortableRuntimeClass("jdk.internal.Asm")); assertFalse(isPortableRuntimeClass("sun.misc.Unsafe$1")); assertTrue(isPortableRuntimeClass(Object.class.getName())); assertTrue(isPortableRuntimeClass(ArrayList.class.getName())); assertTrue(isPortableRuntimeClass("org.w3c.dom.Document")); assertFalse(isPortableRuntimeClass(getClass().getName())); } @Test public void testRuntimeModule() {
// Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static Pattern glob2Pattern(String... globs) { // final StringBuilder regex = new StringBuilder(); // boolean needOr = false; // for (String glob : globs) { // if (needOr) { // regex.append('|'); // } // int i = 0, len = glob.length(); // while (i < len) { // char c = glob.charAt(i++); // switch (c) { // case '*': // if (i < len && glob.charAt(i) == '*') { // // crosses package boundaries // regex.append(".*"); // i++; // } else { // // do not cross package boundaries // regex.append("[^.]*"); // } // break; // // case '?': // // do not cross package boundaries // regex.append("[^.]"); // break; // // default: // if (isRegexMeta(c)) { // regex.append('\\'); // } // regex.append(c); // } // } // needOr = true; // } // return Pattern.compile(regex.toString(), 0); // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isGlob(String s) { // return s.indexOf('*') >= 0 || s.indexOf('?') >= 0; // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isPortableRuntimeClass(String className) { // return PORTABLE_RUNTIME_PACKAGE_PATTERN.matcher(className).matches(); // } // // Path: src/main/java/de/thetaphi/forbiddenapis/AsmUtils.java // public static boolean isRuntimeModule(String module) { // return module != null && RUNTIME_MODULES_PATTERN.matcher(module).matches(); // } // Path: src/test/java/de/thetaphi/forbiddenapis/AsmUtilsTest.java import static de.thetaphi.forbiddenapis.AsmUtils.glob2Pattern; import static de.thetaphi.forbiddenapis.AsmUtils.isGlob; import static de.thetaphi.forbiddenapis.AsmUtils.isPortableRuntimeClass; import static de.thetaphi.forbiddenapis.AsmUtils.isRuntimeModule; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.regex.Pattern; import org.junit.Test; assertFalse(pat.matcher("sun.misc.Unsafe.xy").matches()); pat = glob2Pattern("java.**.Array?"); assertTrue(pat.matcher("java.util.Arrays").matches()); assertFalse(pat.matcher("java.util.ArrayList").matches()); assertFalse(pat.matcher("java.util.Array").matches()); assertTrue(pat.matcher("java.lang.reflect.Arrays").matches()); } @Test public void testCrazyPatterns() { // those should not cause havoc: assertEquals("java\\.\\{.*\\}\\.Array", glob2Pattern("java.{**}.Array").pattern()); assertEquals("java\\./.*<>\\.Array\\$1", glob2Pattern("java./**<>.Array$1").pattern()); assertEquals("\\+\\^\\$", glob2Pattern("+^$").pattern()); } @Test public void testPortableRuntime() { assertFalse(isPortableRuntimeClass("sun.misc.Unsafe")); assertFalse(isPortableRuntimeClass("jdk.internal.Asm")); assertFalse(isPortableRuntimeClass("sun.misc.Unsafe$1")); assertTrue(isPortableRuntimeClass(Object.class.getName())); assertTrue(isPortableRuntimeClass(ArrayList.class.getName())); assertTrue(isPortableRuntimeClass("org.w3c.dom.Document")); assertFalse(isPortableRuntimeClass(getClass().getName())); } @Test public void testRuntimeModule() {
assertTrue(isRuntimeModule("java.base"));
policeman-tools/forbidden-apis
src/main/java/de/thetaphi/forbiddenapis/Signatures.java
// Path: src/main/java/de/thetaphi/forbiddenapis/Checker.java // public static enum Option { // FAIL_ON_MISSING_CLASSES, // FAIL_ON_VIOLATION, // FAIL_ON_UNRESOLVABLE_SIGNATURES, // IGNORE_SIGNATURES_OF_MISSING_CLASSES, // DISABLE_CLASSLOADING_CACHE // }
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.objectweb.asm.Type; import org.objectweb.asm.commons.Method; import de.thetaphi.forbiddenapis.Checker.Option;
}; private UnresolvableReporting(boolean reportClassNotFound) { this.reportClassNotFound = reportClassNotFound; } public final boolean reportClassNotFound; public abstract void parseFailed(Logger logger, String message, String signature) throws ParseException; } private final RelatedClassLookup lookup; private final Logger logger; private final boolean failOnUnresolvableSignatures, ignoreSignaturesOfMissingClasses; /** Key is used to lookup forbidden signature in following formats. Keys are generated by the corresponding * {@link #getKey(String)} (classes), {@link #getKey(String, Method)} (methods), * {@link #getKey(String, String)} (fields) call. */ final Map<String,String> signatures = new HashMap<>(); /** set of patterns of forbidden classes */ final Set<ClassPatternRule> classPatterns = new LinkedHashSet<>(); /** if enabled, the bundled signature to enable heuristics for detection of non-portable runtime calls is used */ private boolean forbidNonPortableRuntime = false; /** number of files that were interpreted as signatures file. If 0, no (bundled) signatures files were added at all */ private int numberOfFiles = 0; public Signatures(Checker checker) {
// Path: src/main/java/de/thetaphi/forbiddenapis/Checker.java // public static enum Option { // FAIL_ON_MISSING_CLASSES, // FAIL_ON_VIOLATION, // FAIL_ON_UNRESOLVABLE_SIGNATURES, // IGNORE_SIGNATURES_OF_MISSING_CLASSES, // DISABLE_CLASSLOADING_CACHE // } // Path: src/main/java/de/thetaphi/forbiddenapis/Signatures.java import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.objectweb.asm.Type; import org.objectweb.asm.commons.Method; import de.thetaphi.forbiddenapis.Checker.Option; }; private UnresolvableReporting(boolean reportClassNotFound) { this.reportClassNotFound = reportClassNotFound; } public final boolean reportClassNotFound; public abstract void parseFailed(Logger logger, String message, String signature) throws ParseException; } private final RelatedClassLookup lookup; private final Logger logger; private final boolean failOnUnresolvableSignatures, ignoreSignaturesOfMissingClasses; /** Key is used to lookup forbidden signature in following formats. Keys are generated by the corresponding * {@link #getKey(String)} (classes), {@link #getKey(String, Method)} (methods), * {@link #getKey(String, String)} (fields) call. */ final Map<String,String> signatures = new HashMap<>(); /** set of patterns of forbidden classes */ final Set<ClassPatternRule> classPatterns = new LinkedHashSet<>(); /** if enabled, the bundled signature to enable heuristics for detection of non-portable runtime calls is used */ private boolean forbidNonPortableRuntime = false; /** number of files that were interpreted as signatures file. If 0, no (bundled) signatures files were added at all */ private int numberOfFiles = 0; public Signatures(Checker checker) {
this(checker, checker.logger, checker.options.contains(Option.IGNORE_SIGNATURES_OF_MISSING_CLASSES), checker.options.contains(Option.FAIL_ON_UNRESOLVABLE_SIGNATURES));
policeman-tools/forbidden-apis
src/test/java/de/thetaphi/forbiddenapis/CheckerSetupTest.java
// Path: src/main/java/de/thetaphi/forbiddenapis/Checker.java // public static enum Option { // FAIL_ON_MISSING_CLASSES, // FAIL_ON_VIOLATION, // FAIL_ON_UNRESOLVABLE_SIGNATURES, // IGNORE_SIGNATURES_OF_MISSING_CLASSES, // DISABLE_CLASSLOADING_CACHE // }
import static de.thetaphi.forbiddenapis.Checker.Option.*; import static org.junit.Assert.*; import static org.junit.Assume.assumeTrue; import static org.junit.Assume.assumeNoException; import java.util.Collections; import java.util.EnumSet; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.commons.Method;
assertTrue(forbiddenSignatures.signatures.containsKey(Signatures.getKey("java/lang/String", new Method("copyValueOf", "([CII)Ljava/lang/String;")))); assertEquals(Collections.emptySet(), forbiddenSignatures.classPatterns); assertFalse(checker.hasNoSignatures()); assertFalse(checker.noSignaturesFilesParsed()); } @Test public void testWildcardMethodSignatureNoArgs() throws Exception { checker.parseSignaturesString("java.lang.Object#toString(**) @ Foobar"); assertEquals(Collections.singletonMap(Signatures.getKey("java/lang/Object", new Method("toString", "()Ljava/lang/String;")), "java.lang.Object#toString(**) [Foobar]"), forbiddenSignatures.signatures); assertEquals(Collections.emptySet(), forbiddenSignatures.classPatterns); assertFalse(checker.hasNoSignatures()); assertFalse(checker.noSignaturesFilesParsed()); } @Test public void testWildcardMethodSignatureNotExist() throws Exception { try { checker.parseSignaturesString("java.lang.Object#foobarNotExist(**) @ Foobar"); fail("Should fail to parse because method does not exist"); } catch (ParseException pe) { assertEquals("Method not found while parsing signature: java.lang.Object#foobarNotExist(**)", pe.getMessage()); } } @Test public void testEmptyCtor() throws Exception { Checker chk = new Checker(StdIoLogger.INSTANCE, ClassLoader.getSystemClassLoader());
// Path: src/main/java/de/thetaphi/forbiddenapis/Checker.java // public static enum Option { // FAIL_ON_MISSING_CLASSES, // FAIL_ON_VIOLATION, // FAIL_ON_UNRESOLVABLE_SIGNATURES, // IGNORE_SIGNATURES_OF_MISSING_CLASSES, // DISABLE_CLASSLOADING_CACHE // } // Path: src/test/java/de/thetaphi/forbiddenapis/CheckerSetupTest.java import static de.thetaphi.forbiddenapis.Checker.Option.*; import static org.junit.Assert.*; import static org.junit.Assume.assumeTrue; import static org.junit.Assume.assumeNoException; import java.util.Collections; import java.util.EnumSet; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.commons.Method; assertTrue(forbiddenSignatures.signatures.containsKey(Signatures.getKey("java/lang/String", new Method("copyValueOf", "([CII)Ljava/lang/String;")))); assertEquals(Collections.emptySet(), forbiddenSignatures.classPatterns); assertFalse(checker.hasNoSignatures()); assertFalse(checker.noSignaturesFilesParsed()); } @Test public void testWildcardMethodSignatureNoArgs() throws Exception { checker.parseSignaturesString("java.lang.Object#toString(**) @ Foobar"); assertEquals(Collections.singletonMap(Signatures.getKey("java/lang/Object", new Method("toString", "()Ljava/lang/String;")), "java.lang.Object#toString(**) [Foobar]"), forbiddenSignatures.signatures); assertEquals(Collections.emptySet(), forbiddenSignatures.classPatterns); assertFalse(checker.hasNoSignatures()); assertFalse(checker.noSignaturesFilesParsed()); } @Test public void testWildcardMethodSignatureNotExist() throws Exception { try { checker.parseSignaturesString("java.lang.Object#foobarNotExist(**) @ Foobar"); fail("Should fail to parse because method does not exist"); } catch (ParseException pe) { assertEquals("Method not found while parsing signature: java.lang.Object#foobarNotExist(**)", pe.getMessage()); } } @Test public void testEmptyCtor() throws Exception { Checker chk = new Checker(StdIoLogger.INSTANCE, ClassLoader.getSystemClassLoader());
assertEquals(EnumSet.noneOf(Checker.Option.class), chk.options);
yeloapp/yelo-android
app/src/main/java/red/yelo/ui/Animation/FloatKeyframeSet.java
// Path: app/src/main/java/red/yelo/ui/Animation/Keyframe.java // static class FloatKeyframe extends Keyframe { // // float mValue; // // FloatKeyframe(float fraction, float value) { // mFraction = fraction; // mValue = value; // mValueType = float.class; // mHasValue = true; // } // // FloatKeyframe(float fraction) { // mFraction = fraction; // mValueType = float.class; // } // // public float getFloatValue() { // return mValue; // } // // public Object getValue() { // return mValue; // } // // public void setValue(Object value) { // if (value != null && value.getClass() == Float.class) { // mValue = (Float) value; // mHasValue = true; // } // } // // @Override // public FloatKeyframe clone() { // FloatKeyframe kfClone = mHasValue ? new FloatKeyframe(getFraction(), mValue) : new FloatKeyframe(getFraction()); // kfClone.setInterpolator(getInterpolator()); // return kfClone; // } // }
import java.util.ArrayList; import red.yelo.ui.Animation.Keyframe.FloatKeyframe; import android.view.animation.Interpolator;
/* * * * Copyright (C) 2015 yelo.red * * * * 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 red.yelo.ui.Animation; class FloatKeyframeSet extends KeyframeSet { private float firstValue; private float lastValue; private float deltaValue; private boolean firstTime = true;
// Path: app/src/main/java/red/yelo/ui/Animation/Keyframe.java // static class FloatKeyframe extends Keyframe { // // float mValue; // // FloatKeyframe(float fraction, float value) { // mFraction = fraction; // mValue = value; // mValueType = float.class; // mHasValue = true; // } // // FloatKeyframe(float fraction) { // mFraction = fraction; // mValueType = float.class; // } // // public float getFloatValue() { // return mValue; // } // // public Object getValue() { // return mValue; // } // // public void setValue(Object value) { // if (value != null && value.getClass() == Float.class) { // mValue = (Float) value; // mHasValue = true; // } // } // // @Override // public FloatKeyframe clone() { // FloatKeyframe kfClone = mHasValue ? new FloatKeyframe(getFraction(), mValue) : new FloatKeyframe(getFraction()); // kfClone.setInterpolator(getInterpolator()); // return kfClone; // } // } // Path: app/src/main/java/red/yelo/ui/Animation/FloatKeyframeSet.java import java.util.ArrayList; import red.yelo.ui.Animation.Keyframe.FloatKeyframe; import android.view.animation.Interpolator; /* * * * Copyright (C) 2015 yelo.red * * * * 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 red.yelo.ui.Animation; class FloatKeyframeSet extends KeyframeSet { private float firstValue; private float lastValue; private float deltaValue; private boolean firstTime = true;
public FloatKeyframeSet(FloatKeyframe... keyframes) {
AlbinoDrought/party-reader
app/src/main/java/party/minge/reddit/treeview/CommentNodeViewHolder.java
// Path: app/src/main/java/party/minge/reddit/CommentItemView.java // @EViewGroup(R.layout.comment_item) // public class CommentItemView extends LinearLayout { // static final int MAX_DEPTH = 15; // // protected CommentNode commentNode; // // @DimensionPixelSizeRes(R.dimen.comment_bar_size) // protected int commentBarSize; // // @IntArrayRes // protected int[] colorsDepth; // // @ViewById // protected View vBar; // // @ViewById // protected LinearLayout grpMain; // // @ViewById // protected TextView txtCommentAuthor; // // @ViewById // protected TextView txtCommentScore; // // @ViewById // protected TextView txtCommentTime; // // @ViewById // protected TextView txtCommentText; // // @ViewById // protected IconButton btnUpvote; // // @ViewById // protected IconButton btnDownvote; // // @ViewById // protected IconButton btnReply; // // @Bean // protected Upvoter<Comment> upvoter; // // @Bean // protected Replier<Comment> replier; // // @ColorRes(R.color.colorUpvote) // protected int colorUpvote; // // @ColorRes(R.color.colorDownvote) // protected int colorDownvote; // // @ColorRes(R.color.colorNoVote) // protected int colorNoVote; // // private int colorScore; // // @Bean // protected MarkdownParser markdownParser; // // public CommentItemView(Context context) { // super(context); // } // // @AfterViews // protected void init() { // this.colorScore = this.txtCommentScore.getCurrentTextColor(); // // this.upvoter.setVoteChangeListener(new VoteChangeListener() { // @Override // public void onVoteChanged(VoteDirection voteDirection) { // CommentItemView.this.setVoteDirection(voteDirection); // } // }); // // this.replier.setReplyListener(new DialogReplyListener(this.getContext(), "Error replying to comment") { // @Override // public void onSuccess(String id) { // String submissionId = CommentItemView.this.commentNode.getComment().getSubmissionId(); // SubmissionDetailActivity_.intent(CommentItemView.this.getContext()) // .submissionId(submissionId) // .start(); // } // }); // // this.btnUpvote.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View view) { // CommentItemView.this.upvoter.performVote(VoteDirection.UPVOTE); // } // }); // // this.btnDownvote.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View view) { // CommentItemView.this.upvoter.performVote(VoteDirection.DOWNVOTE); // } // }); // // this.btnReply.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View view) { // Comment comment = CommentItemView.this.commentNode.getComment(); // CommentItemView.this.replier.replyTo(comment); // } // }); // // this.txtCommentText.setMovementMethod(LinkMovementMethod.getInstance()); // } // // @UiThread // protected void setVoteDirection(VoteDirection direction) { // int dvColor = this.colorNoVote; // int uvColor = this.colorNoVote; // int gColor = this.colorScore; // // switch (direction) { // case UPVOTE: // uvColor = this.colorUpvote; // gColor = this.colorUpvote; // break; // case DOWNVOTE: // dvColor = this.colorDownvote; // gColor = this.colorDownvote; // break; // } // // this.btnDownvote.setTextColor(dvColor); // this.btnUpvote.setTextColor(uvColor); // this.txtCommentScore.setTextColor(gColor); // } // // public void bind(CommentNode commentNode) { // this.commentNode = commentNode; // // Comment c = commentNode.getComment(); // // // no comment node is actually at 0 depth. that is the depth of the root node. // // so, inset our comment depth by 1. // int commentDepth = commentNode.getDepth() - 1; // this.grpMain.setPadding( // Math.min(commentDepth, MAX_DEPTH) * this.commentBarSize, // this.getPaddingTop(), // this.getPaddingRight(), // this.getPaddingBottom() // ); // // if (commentDepth > 0) { // this.vBar.setVisibility(VISIBLE); // this.vBar.setBackgroundColor(this.getColorForDepth(commentDepth)); // } else { // this.vBar.setVisibility(GONE); // } // // this.txtCommentAuthor.setText(c.getAuthor()); // this.txtCommentScore.setText(c.getScore() + " points"); // this.txtCommentTime.setText(DateUtils.getRelativeTimeSpanString(c.getCreated().getTime())); // // this.txtCommentText.setText(this.markdownParser.parseMarkdown(c.getBody())); // // this.upvoter.setUpvotable(c); // } // // private int getColorForDepth(int depth) { // int modded = depth % this.colorsDepth.length; // // return this.colorsDepth[modded]; // } // }
import android.content.Context; import android.view.View; import com.unnamed.b.atv.model.TreeNode; import net.dean.jraw.models.CommentNode; import party.minge.reddit.CommentItemView; import party.minge.reddit.CommentItemView_;
package party.minge.reddit.treeview; public class CommentNodeViewHolder extends TreeNode.BaseNodeViewHolder<CommentNode> { public CommentNodeViewHolder(Context context) { super(context); } @Override public View createNodeView(TreeNode node, CommentNode value) {
// Path: app/src/main/java/party/minge/reddit/CommentItemView.java // @EViewGroup(R.layout.comment_item) // public class CommentItemView extends LinearLayout { // static final int MAX_DEPTH = 15; // // protected CommentNode commentNode; // // @DimensionPixelSizeRes(R.dimen.comment_bar_size) // protected int commentBarSize; // // @IntArrayRes // protected int[] colorsDepth; // // @ViewById // protected View vBar; // // @ViewById // protected LinearLayout grpMain; // // @ViewById // protected TextView txtCommentAuthor; // // @ViewById // protected TextView txtCommentScore; // // @ViewById // protected TextView txtCommentTime; // // @ViewById // protected TextView txtCommentText; // // @ViewById // protected IconButton btnUpvote; // // @ViewById // protected IconButton btnDownvote; // // @ViewById // protected IconButton btnReply; // // @Bean // protected Upvoter<Comment> upvoter; // // @Bean // protected Replier<Comment> replier; // // @ColorRes(R.color.colorUpvote) // protected int colorUpvote; // // @ColorRes(R.color.colorDownvote) // protected int colorDownvote; // // @ColorRes(R.color.colorNoVote) // protected int colorNoVote; // // private int colorScore; // // @Bean // protected MarkdownParser markdownParser; // // public CommentItemView(Context context) { // super(context); // } // // @AfterViews // protected void init() { // this.colorScore = this.txtCommentScore.getCurrentTextColor(); // // this.upvoter.setVoteChangeListener(new VoteChangeListener() { // @Override // public void onVoteChanged(VoteDirection voteDirection) { // CommentItemView.this.setVoteDirection(voteDirection); // } // }); // // this.replier.setReplyListener(new DialogReplyListener(this.getContext(), "Error replying to comment") { // @Override // public void onSuccess(String id) { // String submissionId = CommentItemView.this.commentNode.getComment().getSubmissionId(); // SubmissionDetailActivity_.intent(CommentItemView.this.getContext()) // .submissionId(submissionId) // .start(); // } // }); // // this.btnUpvote.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View view) { // CommentItemView.this.upvoter.performVote(VoteDirection.UPVOTE); // } // }); // // this.btnDownvote.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View view) { // CommentItemView.this.upvoter.performVote(VoteDirection.DOWNVOTE); // } // }); // // this.btnReply.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View view) { // Comment comment = CommentItemView.this.commentNode.getComment(); // CommentItemView.this.replier.replyTo(comment); // } // }); // // this.txtCommentText.setMovementMethod(LinkMovementMethod.getInstance()); // } // // @UiThread // protected void setVoteDirection(VoteDirection direction) { // int dvColor = this.colorNoVote; // int uvColor = this.colorNoVote; // int gColor = this.colorScore; // // switch (direction) { // case UPVOTE: // uvColor = this.colorUpvote; // gColor = this.colorUpvote; // break; // case DOWNVOTE: // dvColor = this.colorDownvote; // gColor = this.colorDownvote; // break; // } // // this.btnDownvote.setTextColor(dvColor); // this.btnUpvote.setTextColor(uvColor); // this.txtCommentScore.setTextColor(gColor); // } // // public void bind(CommentNode commentNode) { // this.commentNode = commentNode; // // Comment c = commentNode.getComment(); // // // no comment node is actually at 0 depth. that is the depth of the root node. // // so, inset our comment depth by 1. // int commentDepth = commentNode.getDepth() - 1; // this.grpMain.setPadding( // Math.min(commentDepth, MAX_DEPTH) * this.commentBarSize, // this.getPaddingTop(), // this.getPaddingRight(), // this.getPaddingBottom() // ); // // if (commentDepth > 0) { // this.vBar.setVisibility(VISIBLE); // this.vBar.setBackgroundColor(this.getColorForDepth(commentDepth)); // } else { // this.vBar.setVisibility(GONE); // } // // this.txtCommentAuthor.setText(c.getAuthor()); // this.txtCommentScore.setText(c.getScore() + " points"); // this.txtCommentTime.setText(DateUtils.getRelativeTimeSpanString(c.getCreated().getTime())); // // this.txtCommentText.setText(this.markdownParser.parseMarkdown(c.getBody())); // // this.upvoter.setUpvotable(c); // } // // private int getColorForDepth(int depth) { // int modded = depth % this.colorsDepth.length; // // return this.colorsDepth[modded]; // } // } // Path: app/src/main/java/party/minge/reddit/treeview/CommentNodeViewHolder.java import android.content.Context; import android.view.View; import com.unnamed.b.atv.model.TreeNode; import net.dean.jraw.models.CommentNode; import party.minge.reddit.CommentItemView; import party.minge.reddit.CommentItemView_; package party.minge.reddit.treeview; public class CommentNodeViewHolder extends TreeNode.BaseNodeViewHolder<CommentNode> { public CommentNodeViewHolder(Context context) { super(context); } @Override public View createNodeView(TreeNode node, CommentNode value) {
CommentItemView view = CommentItemView_.build(this.context);
AlbinoDrought/party-reader
app/src/main/java/party/minge/reddit/menu/items/Logout.java
// Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // } // // Path: app/src/main/java/party/minge/reddit/menu/MenuItem.java // public interface MenuItem { // String getText(); // String getIcon(); // int getId(); // // void onClick(); // }
import net.dean.jraw.http.oauth.OAuthHelper; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import party.minge.reddit.client.Manager; import party.minge.reddit.menu.MenuItem;
package party.minge.reddit.menu.items; @EBean public class Logout implements MenuItem { @Bean
// Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // } // // Path: app/src/main/java/party/minge/reddit/menu/MenuItem.java // public interface MenuItem { // String getText(); // String getIcon(); // int getId(); // // void onClick(); // } // Path: app/src/main/java/party/minge/reddit/menu/items/Logout.java import net.dean.jraw.http.oauth.OAuthHelper; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import party.minge.reddit.client.Manager; import party.minge.reddit.menu.MenuItem; package party.minge.reddit.menu.items; @EBean public class Logout implements MenuItem { @Bean
protected Manager manager;
AlbinoDrought/party-reader
app/src/main/java/party/minge/reddit/menu/items/About.java
// Path: app/src/main/java/party/minge/reddit/client/MarkdownParser.java // @EBean(scope = EBean.Scope.Singleton) // public class MarkdownParser { // @RootContext // protected Context rootContext; // // protected Bypass bypass; // // @AfterInject // protected void init() { // this.bypass = new Bypass(this.rootContext); // } // // public CharSequence parseMarkdown(String markdown) { // return this.bypass.markdownToSpannable(markdown); // } // } // // Path: app/src/main/java/party/minge/reddit/menu/MenuItem.java // public interface MenuItem { // String getText(); // String getIcon(); // int getId(); // // void onClick(); // }
import android.app.AlertDialog; import android.content.Context; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.RootContext; import org.androidannotations.annotations.res.StringRes; import party.minge.reddit.client.MarkdownParser; import party.minge.reddit.menu.MenuItem;
package party.minge.reddit.menu.items; @EBean public class About implements MenuItem { @RootContext protected Context rootContext; @StringRes protected String about; @Bean
// Path: app/src/main/java/party/minge/reddit/client/MarkdownParser.java // @EBean(scope = EBean.Scope.Singleton) // public class MarkdownParser { // @RootContext // protected Context rootContext; // // protected Bypass bypass; // // @AfterInject // protected void init() { // this.bypass = new Bypass(this.rootContext); // } // // public CharSequence parseMarkdown(String markdown) { // return this.bypass.markdownToSpannable(markdown); // } // } // // Path: app/src/main/java/party/minge/reddit/menu/MenuItem.java // public interface MenuItem { // String getText(); // String getIcon(); // int getId(); // // void onClick(); // } // Path: app/src/main/java/party/minge/reddit/menu/items/About.java import android.app.AlertDialog; import android.content.Context; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.RootContext; import org.androidannotations.annotations.res.StringRes; import party.minge.reddit.client.MarkdownParser; import party.minge.reddit.menu.MenuItem; package party.minge.reddit.menu.items; @EBean public class About implements MenuItem { @RootContext protected Context rootContext; @StringRes protected String about; @Bean
protected MarkdownParser markdownParser;
AlbinoDrought/party-reader
app/src/main/java/party/minge/reddit/LoginActivity.java
// Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // }
import android.app.Activity; import android.graphics.Bitmap; import android.util.Log; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import net.dean.jraw.http.oauth.Credentials; import net.dean.jraw.http.oauth.OAuthData; import net.dean.jraw.http.oauth.OAuthException; import net.dean.jraw.http.oauth.OAuthHelper; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import java.net.URL; import party.minge.reddit.client.Manager;
package party.minge.reddit; @EActivity(R.layout.activity_login) public class LoginActivity extends Activity { @ViewById protected WebView webviewLogin; @Bean
// Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // } // Path: app/src/main/java/party/minge/reddit/LoginActivity.java import android.app.Activity; import android.graphics.Bitmap; import android.util.Log; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import net.dean.jraw.http.oauth.Credentials; import net.dean.jraw.http.oauth.OAuthData; import net.dean.jraw.http.oauth.OAuthException; import net.dean.jraw.http.oauth.OAuthHelper; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import java.net.URL; import party.minge.reddit.client.Manager; package party.minge.reddit; @EActivity(R.layout.activity_login) public class LoginActivity extends Activity { @ViewById protected WebView webviewLogin; @Bean
protected Manager manager;
AlbinoDrought/party-reader
app/src/main/java/party/minge/reddit/SubredditActivity.java
// Path: app/src/main/java/party/minge/reddit/client/AuthenticationCallback.java // public interface AuthenticationCallback { // void onSuccessfulAuthentication(); // void onFailedAuthentication(Exception e); // } // // Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // } // // Path: app/src/main/java/party/minge/reddit/menu/SidebarMenuAdapter.java // @EBean // public class SidebarMenuAdapter extends BaseAdapter { // @Bean // protected SidebarMenuItemRepository repository; // // @RootContext // protected Context rootContext; // // @Override // public int getCount() { // return this.repository.getLength(); // } // // @Override // public MenuItem getItem(int i) { // return this.repository.getMenuItems()[i]; // } // // @Override // public long getItemId(int i) { // return this.repository.getMenuItems()[i].getId(); // } // // @Override // public View getView(int i, View view, ViewGroup viewGroup) { // if (view == null) { // view = MenuItemView_.build(this.rootContext); // } // // ((MenuItemView)view).bind(this.getItem(i)); // // return view; // } // }
import android.app.Activity; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import net.dean.jraw.models.Submission; import net.dean.jraw.paginators.SubredditPaginator; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.Extra; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import party.minge.reddit.client.AuthenticationCallback; import party.minge.reddit.client.Manager; import party.minge.reddit.menu.SidebarMenuAdapter; import static android.view.View.GONE;
package party.minge.reddit; @EActivity(R.layout.activity_subreddit) public class SubredditActivity extends Activity { @Extra protected String subreddit; @Bean
// Path: app/src/main/java/party/minge/reddit/client/AuthenticationCallback.java // public interface AuthenticationCallback { // void onSuccessfulAuthentication(); // void onFailedAuthentication(Exception e); // } // // Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // } // // Path: app/src/main/java/party/minge/reddit/menu/SidebarMenuAdapter.java // @EBean // public class SidebarMenuAdapter extends BaseAdapter { // @Bean // protected SidebarMenuItemRepository repository; // // @RootContext // protected Context rootContext; // // @Override // public int getCount() { // return this.repository.getLength(); // } // // @Override // public MenuItem getItem(int i) { // return this.repository.getMenuItems()[i]; // } // // @Override // public long getItemId(int i) { // return this.repository.getMenuItems()[i].getId(); // } // // @Override // public View getView(int i, View view, ViewGroup viewGroup) { // if (view == null) { // view = MenuItemView_.build(this.rootContext); // } // // ((MenuItemView)view).bind(this.getItem(i)); // // return view; // } // } // Path: app/src/main/java/party/minge/reddit/SubredditActivity.java import android.app.Activity; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import net.dean.jraw.models.Submission; import net.dean.jraw.paginators.SubredditPaginator; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.Extra; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import party.minge.reddit.client.AuthenticationCallback; import party.minge.reddit.client.Manager; import party.minge.reddit.menu.SidebarMenuAdapter; import static android.view.View.GONE; package party.minge.reddit; @EActivity(R.layout.activity_subreddit) public class SubredditActivity extends Activity { @Extra protected String subreddit; @Bean
protected Manager manager;
AlbinoDrought/party-reader
app/src/main/java/party/minge/reddit/SubredditActivity.java
// Path: app/src/main/java/party/minge/reddit/client/AuthenticationCallback.java // public interface AuthenticationCallback { // void onSuccessfulAuthentication(); // void onFailedAuthentication(Exception e); // } // // Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // } // // Path: app/src/main/java/party/minge/reddit/menu/SidebarMenuAdapter.java // @EBean // public class SidebarMenuAdapter extends BaseAdapter { // @Bean // protected SidebarMenuItemRepository repository; // // @RootContext // protected Context rootContext; // // @Override // public int getCount() { // return this.repository.getLength(); // } // // @Override // public MenuItem getItem(int i) { // return this.repository.getMenuItems()[i]; // } // // @Override // public long getItemId(int i) { // return this.repository.getMenuItems()[i].getId(); // } // // @Override // public View getView(int i, View view, ViewGroup viewGroup) { // if (view == null) { // view = MenuItemView_.build(this.rootContext); // } // // ((MenuItemView)view).bind(this.getItem(i)); // // return view; // } // }
import android.app.Activity; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import net.dean.jraw.models.Submission; import net.dean.jraw.paginators.SubredditPaginator; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.Extra; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import party.minge.reddit.client.AuthenticationCallback; import party.minge.reddit.client.Manager; import party.minge.reddit.menu.SidebarMenuAdapter; import static android.view.View.GONE;
package party.minge.reddit; @EActivity(R.layout.activity_subreddit) public class SubredditActivity extends Activity { @Extra protected String subreddit; @Bean protected Manager manager; protected SubredditPaginator paginator; @Bean protected PostListAdapter postListAdapter; @ViewById protected ListView lvSubredditPosts; @ViewById protected DrawerLayout layoutDrawer; protected ActionBarDrawerToggle drawerListener; @ViewById protected ListView lvDrawer; @ViewById protected ProgressBar loader; @Bean
// Path: app/src/main/java/party/minge/reddit/client/AuthenticationCallback.java // public interface AuthenticationCallback { // void onSuccessfulAuthentication(); // void onFailedAuthentication(Exception e); // } // // Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // } // // Path: app/src/main/java/party/minge/reddit/menu/SidebarMenuAdapter.java // @EBean // public class SidebarMenuAdapter extends BaseAdapter { // @Bean // protected SidebarMenuItemRepository repository; // // @RootContext // protected Context rootContext; // // @Override // public int getCount() { // return this.repository.getLength(); // } // // @Override // public MenuItem getItem(int i) { // return this.repository.getMenuItems()[i]; // } // // @Override // public long getItemId(int i) { // return this.repository.getMenuItems()[i].getId(); // } // // @Override // public View getView(int i, View view, ViewGroup viewGroup) { // if (view == null) { // view = MenuItemView_.build(this.rootContext); // } // // ((MenuItemView)view).bind(this.getItem(i)); // // return view; // } // } // Path: app/src/main/java/party/minge/reddit/SubredditActivity.java import android.app.Activity; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import net.dean.jraw.models.Submission; import net.dean.jraw.paginators.SubredditPaginator; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.Extra; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import party.minge.reddit.client.AuthenticationCallback; import party.minge.reddit.client.Manager; import party.minge.reddit.menu.SidebarMenuAdapter; import static android.view.View.GONE; package party.minge.reddit; @EActivity(R.layout.activity_subreddit) public class SubredditActivity extends Activity { @Extra protected String subreddit; @Bean protected Manager manager; protected SubredditPaginator paginator; @Bean protected PostListAdapter postListAdapter; @ViewById protected ListView lvSubredditPosts; @ViewById protected DrawerLayout layoutDrawer; protected ActionBarDrawerToggle drawerListener; @ViewById protected ListView lvDrawer; @ViewById protected ProgressBar loader; @Bean
protected SidebarMenuAdapter sidebarMenuAdapter;
AlbinoDrought/party-reader
app/src/main/java/party/minge/reddit/SubredditActivity.java
// Path: app/src/main/java/party/minge/reddit/client/AuthenticationCallback.java // public interface AuthenticationCallback { // void onSuccessfulAuthentication(); // void onFailedAuthentication(Exception e); // } // // Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // } // // Path: app/src/main/java/party/minge/reddit/menu/SidebarMenuAdapter.java // @EBean // public class SidebarMenuAdapter extends BaseAdapter { // @Bean // protected SidebarMenuItemRepository repository; // // @RootContext // protected Context rootContext; // // @Override // public int getCount() { // return this.repository.getLength(); // } // // @Override // public MenuItem getItem(int i) { // return this.repository.getMenuItems()[i]; // } // // @Override // public long getItemId(int i) { // return this.repository.getMenuItems()[i].getId(); // } // // @Override // public View getView(int i, View view, ViewGroup viewGroup) { // if (view == null) { // view = MenuItemView_.build(this.rootContext); // } // // ((MenuItemView)view).bind(this.getItem(i)); // // return view; // } // }
import android.app.Activity; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import net.dean.jraw.models.Submission; import net.dean.jraw.paginators.SubredditPaginator; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.Extra; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import party.minge.reddit.client.AuthenticationCallback; import party.minge.reddit.client.Manager; import party.minge.reddit.menu.SidebarMenuAdapter; import static android.view.View.GONE;
} @Override public void onDrawerClosed(View drawerView) { SubredditActivity.this.sidebarMenuAdapter.notifyDataSetChanged(); } }; this.layoutDrawer.setDrawerListener(this.drawerListener); this.grpSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { SubredditActivity.this.fetchPosts(); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (this.drawerListener.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } @AfterViews @Background protected void authenticateIfRequired() {
// Path: app/src/main/java/party/minge/reddit/client/AuthenticationCallback.java // public interface AuthenticationCallback { // void onSuccessfulAuthentication(); // void onFailedAuthentication(Exception e); // } // // Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // } // // Path: app/src/main/java/party/minge/reddit/menu/SidebarMenuAdapter.java // @EBean // public class SidebarMenuAdapter extends BaseAdapter { // @Bean // protected SidebarMenuItemRepository repository; // // @RootContext // protected Context rootContext; // // @Override // public int getCount() { // return this.repository.getLength(); // } // // @Override // public MenuItem getItem(int i) { // return this.repository.getMenuItems()[i]; // } // // @Override // public long getItemId(int i) { // return this.repository.getMenuItems()[i].getId(); // } // // @Override // public View getView(int i, View view, ViewGroup viewGroup) { // if (view == null) { // view = MenuItemView_.build(this.rootContext); // } // // ((MenuItemView)view).bind(this.getItem(i)); // // return view; // } // } // Path: app/src/main/java/party/minge/reddit/SubredditActivity.java import android.app.Activity; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import net.dean.jraw.models.Submission; import net.dean.jraw.paginators.SubredditPaginator; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.Extra; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import party.minge.reddit.client.AuthenticationCallback; import party.minge.reddit.client.Manager; import party.minge.reddit.menu.SidebarMenuAdapter; import static android.view.View.GONE; } @Override public void onDrawerClosed(View drawerView) { SubredditActivity.this.sidebarMenuAdapter.notifyDataSetChanged(); } }; this.layoutDrawer.setDrawerListener(this.drawerListener); this.grpSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { SubredditActivity.this.fetchPosts(); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (this.drawerListener.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } @AfterViews @Background protected void authenticateIfRequired() {
this.manager.authenticateIfRequired(new AuthenticationCallback() {
AlbinoDrought/party-reader
app/src/main/java/party/minge/reddit/PostItemView.java
// Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // } // // Path: app/src/main/java/party/minge/reddit/client/Upvoter.java // @EBean // public class Upvoter<T extends Thing & Votable> { // @Bean // protected Manager manager; // // private T upvotable; // // private VoteChangeListener voteChangeListener; // // private VoteDirection currentVoteDirection = VoteDirection.NO_VOTE; // // private boolean currentlyVoting = false; // // public void setUpvotable(T thing) { // this.upvotable = thing; // // this.setVoteDirection(thing.getVote()); // } // // protected void setVoteDirection(VoteDirection voteDirection) { // this.currentVoteDirection = voteDirection; // // if (this.voteChangeListener != null) { // this.voteChangeListener.onVoteChanged(voteDirection); // } // } // // public void setVoteChangeListener(VoteChangeListener voteChangeListener) { // this.voteChangeListener = voteChangeListener; // } // // @Background // public void performVote(VoteDirection voteDirection) { // if (this.currentlyVoting) { // return; // } // // this.currentlyVoting = true; // // VoteDirection oldDirection = this.currentVoteDirection; // // if (voteDirection == oldDirection) { // voteDirection = VoteDirection.NO_VOTE; // } // // // update vote on ui instantly, reverting if it fails // this.setVoteDirection(voteDirection); // // try { // this.manager.getAccountManager().vote(this.upvotable, voteDirection); // } catch (ApiException ex) { // Log.e("vote", ex.toString()); // this.setVoteDirection(oldDirection); // } // // this.currentlyVoting = false; // } // } // // Path: app/src/main/java/party/minge/reddit/client/VoteChangeListener.java // public interface VoteChangeListener { // void onVoteChanged(VoteDirection voteDirection); // }
import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.text.format.DateUtils; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.Target; import com.joanzapata.iconify.widget.IconTextView; import net.dean.jraw.ApiException; import net.dean.jraw.models.OEmbed; import net.dean.jraw.models.Submission; import net.dean.jraw.models.Thumbnails; import net.dean.jraw.models.VoteDirection; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EViewGroup; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import org.androidannotations.annotations.res.ColorRes; import java.util.Locale; import party.minge.reddit.client.Manager; import party.minge.reddit.client.Upvoter; import party.minge.reddit.client.VoteChangeListener;
package party.minge.reddit; @EViewGroup(R.layout.post_item) public class PostItemView extends LinearLayout { @Bean
// Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // } // // Path: app/src/main/java/party/minge/reddit/client/Upvoter.java // @EBean // public class Upvoter<T extends Thing & Votable> { // @Bean // protected Manager manager; // // private T upvotable; // // private VoteChangeListener voteChangeListener; // // private VoteDirection currentVoteDirection = VoteDirection.NO_VOTE; // // private boolean currentlyVoting = false; // // public void setUpvotable(T thing) { // this.upvotable = thing; // // this.setVoteDirection(thing.getVote()); // } // // protected void setVoteDirection(VoteDirection voteDirection) { // this.currentVoteDirection = voteDirection; // // if (this.voteChangeListener != null) { // this.voteChangeListener.onVoteChanged(voteDirection); // } // } // // public void setVoteChangeListener(VoteChangeListener voteChangeListener) { // this.voteChangeListener = voteChangeListener; // } // // @Background // public void performVote(VoteDirection voteDirection) { // if (this.currentlyVoting) { // return; // } // // this.currentlyVoting = true; // // VoteDirection oldDirection = this.currentVoteDirection; // // if (voteDirection == oldDirection) { // voteDirection = VoteDirection.NO_VOTE; // } // // // update vote on ui instantly, reverting if it fails // this.setVoteDirection(voteDirection); // // try { // this.manager.getAccountManager().vote(this.upvotable, voteDirection); // } catch (ApiException ex) { // Log.e("vote", ex.toString()); // this.setVoteDirection(oldDirection); // } // // this.currentlyVoting = false; // } // } // // Path: app/src/main/java/party/minge/reddit/client/VoteChangeListener.java // public interface VoteChangeListener { // void onVoteChanged(VoteDirection voteDirection); // } // Path: app/src/main/java/party/minge/reddit/PostItemView.java import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.text.format.DateUtils; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.Target; import com.joanzapata.iconify.widget.IconTextView; import net.dean.jraw.ApiException; import net.dean.jraw.models.OEmbed; import net.dean.jraw.models.Submission; import net.dean.jraw.models.Thumbnails; import net.dean.jraw.models.VoteDirection; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EViewGroup; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import org.androidannotations.annotations.res.ColorRes; import java.util.Locale; import party.minge.reddit.client.Manager; import party.minge.reddit.client.Upvoter; import party.minge.reddit.client.VoteChangeListener; package party.minge.reddit; @EViewGroup(R.layout.post_item) public class PostItemView extends LinearLayout { @Bean
protected Manager manager;
AlbinoDrought/party-reader
app/src/main/java/party/minge/reddit/SubmissionDetailActivity.java
// Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // } // // Path: app/src/main/java/party/minge/reddit/treeview/SubmissionTreeNodeAdapter.java // @EBean // public class SubmissionTreeNodeAdapter { // @RootContext // protected Context context; // // @Bean // protected CommentTreeNodeAdapter commentTreeNodeAdapter; // // public TreeNode fromSubmission(Submission submission) // { // TreeNode rootNode = new TreeNode(null); // // TreeNode postNode = new TreeNode(submission); // // postNode.setViewHolder(new SubmissionNodeViewHolder(this.context)); // // rootNode.addChild(postNode); // // List<CommentNode> comments = submission.getComments().getChildren(); // // for (CommentNode comment : comments) { // rootNode.addChild(this.commentTreeNodeAdapter.fromCommentNode(comment)); // } // // return rootNode; // } // }
import android.app.Activity; import android.content.Context; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import com.unnamed.b.atv.model.TreeNode; import com.unnamed.b.atv.view.AndroidTreeView; import net.dean.jraw.models.CommentNode; import net.dean.jraw.models.Submission; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.Extra; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import party.minge.reddit.client.Manager; import party.minge.reddit.treeview.SubmissionTreeNodeAdapter;
package party.minge.reddit; @EActivity(R.layout.activity_submission_detail) public class SubmissionDetailActivity extends Activity { @Extra protected String submissionId; protected Submission submission; @Bean
// Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // } // // Path: app/src/main/java/party/minge/reddit/treeview/SubmissionTreeNodeAdapter.java // @EBean // public class SubmissionTreeNodeAdapter { // @RootContext // protected Context context; // // @Bean // protected CommentTreeNodeAdapter commentTreeNodeAdapter; // // public TreeNode fromSubmission(Submission submission) // { // TreeNode rootNode = new TreeNode(null); // // TreeNode postNode = new TreeNode(submission); // // postNode.setViewHolder(new SubmissionNodeViewHolder(this.context)); // // rootNode.addChild(postNode); // // List<CommentNode> comments = submission.getComments().getChildren(); // // for (CommentNode comment : comments) { // rootNode.addChild(this.commentTreeNodeAdapter.fromCommentNode(comment)); // } // // return rootNode; // } // } // Path: app/src/main/java/party/minge/reddit/SubmissionDetailActivity.java import android.app.Activity; import android.content.Context; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import com.unnamed.b.atv.model.TreeNode; import com.unnamed.b.atv.view.AndroidTreeView; import net.dean.jraw.models.CommentNode; import net.dean.jraw.models.Submission; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.Extra; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import party.minge.reddit.client.Manager; import party.minge.reddit.treeview.SubmissionTreeNodeAdapter; package party.minge.reddit; @EActivity(R.layout.activity_submission_detail) public class SubmissionDetailActivity extends Activity { @Extra protected String submissionId; protected Submission submission; @Bean
protected Manager manager;
AlbinoDrought/party-reader
app/src/main/java/party/minge/reddit/SubmissionDetailActivity.java
// Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // } // // Path: app/src/main/java/party/minge/reddit/treeview/SubmissionTreeNodeAdapter.java // @EBean // public class SubmissionTreeNodeAdapter { // @RootContext // protected Context context; // // @Bean // protected CommentTreeNodeAdapter commentTreeNodeAdapter; // // public TreeNode fromSubmission(Submission submission) // { // TreeNode rootNode = new TreeNode(null); // // TreeNode postNode = new TreeNode(submission); // // postNode.setViewHolder(new SubmissionNodeViewHolder(this.context)); // // rootNode.addChild(postNode); // // List<CommentNode> comments = submission.getComments().getChildren(); // // for (CommentNode comment : comments) { // rootNode.addChild(this.commentTreeNodeAdapter.fromCommentNode(comment)); // } // // return rootNode; // } // }
import android.app.Activity; import android.content.Context; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import com.unnamed.b.atv.model.TreeNode; import com.unnamed.b.atv.view.AndroidTreeView; import net.dean.jraw.models.CommentNode; import net.dean.jraw.models.Submission; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.Extra; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import party.minge.reddit.client.Manager; import party.minge.reddit.treeview.SubmissionTreeNodeAdapter;
package party.minge.reddit; @EActivity(R.layout.activity_submission_detail) public class SubmissionDetailActivity extends Activity { @Extra protected String submissionId; protected Submission submission; @Bean protected Manager manager; @Bean
// Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // } // // Path: app/src/main/java/party/minge/reddit/treeview/SubmissionTreeNodeAdapter.java // @EBean // public class SubmissionTreeNodeAdapter { // @RootContext // protected Context context; // // @Bean // protected CommentTreeNodeAdapter commentTreeNodeAdapter; // // public TreeNode fromSubmission(Submission submission) // { // TreeNode rootNode = new TreeNode(null); // // TreeNode postNode = new TreeNode(submission); // // postNode.setViewHolder(new SubmissionNodeViewHolder(this.context)); // // rootNode.addChild(postNode); // // List<CommentNode> comments = submission.getComments().getChildren(); // // for (CommentNode comment : comments) { // rootNode.addChild(this.commentTreeNodeAdapter.fromCommentNode(comment)); // } // // return rootNode; // } // } // Path: app/src/main/java/party/minge/reddit/SubmissionDetailActivity.java import android.app.Activity; import android.content.Context; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import com.unnamed.b.atv.model.TreeNode; import com.unnamed.b.atv.view.AndroidTreeView; import net.dean.jraw.models.CommentNode; import net.dean.jraw.models.Submission; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.Extra; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import party.minge.reddit.client.Manager; import party.minge.reddit.treeview.SubmissionTreeNodeAdapter; package party.minge.reddit; @EActivity(R.layout.activity_submission_detail) public class SubmissionDetailActivity extends Activity { @Extra protected String submissionId; protected Submission submission; @Bean protected Manager manager; @Bean
protected SubmissionTreeNodeAdapter adapter;
AlbinoDrought/party-reader
app/src/main/java/party/minge/reddit/menu/SidebarMenuItemRepository.java
// Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // }
import android.content.Context; import net.dean.jraw.http.AuthenticationMethod; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.RootContext; import java.util.ArrayList; import party.minge.reddit.client.Manager; import party.minge.reddit.menu.items.About_; import party.minge.reddit.menu.items.Login_; import party.minge.reddit.menu.items.Logout_; import party.minge.reddit.menu.items.ViewSubreddit_;
package party.minge.reddit.menu; @EBean public class SidebarMenuItemRepository { @RootContext protected Context rootContext; @Bean
// Path: app/src/main/java/party/minge/reddit/client/Manager.java // @EBean(scope = EBean.Scope.Singleton) // public class Manager { // @Bean(ResFactory.class) // protected UserAgentFactory userAgentFactory; // // @Bean(ResFactory.class) // protected CredentialFactory credentialFactory; // // @Bean(UserlessCredentialFactory.class) // protected CredentialFactory anonymousCredentialFactory; // // protected RedditClient redditClient; // // protected AuthenticationManager authenticationManager; // // protected AccountManager accountManager; // // @Bean(PreferenceTokenStore.class) // protected TokenStore tokenStore; // // @AfterInject // public void afterInject() { // this.redditClient = new RedditClient(this.userAgentFactory.getUserAgent()); // this.authenticationManager = AuthenticationManager.get(); // this.authenticationManager.init(this.redditClient, new RefreshTokenHandler(this.tokenStore, this.redditClient)); // this.accountManager = new AccountManager(this.redditClient); // } // // /** // * Anonymously authenticates if required. // * If already authenticated, does not re-authenticate. // * // * @param authenticationCallback Methods to call on success or failure. // */ // public void authenticateIfRequired(AuthenticationCallback authenticationCallback) { // AuthenticationState state = AuthenticationManager.get().checkAuthState(); // // if (state == AuthenticationState.READY) { // authenticationCallback.onSuccessfulAuthentication(); // return; // } // // if (state == AuthenticationState.NEED_REFRESH) { // try { // this.authenticationManager.refreshAccessToken(this.getCredentials()); // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // // return; // } // // try { // OAuthData authData = this.getClient().getOAuthHelper().easyAuth(this.getAnonymousCredentials()); // this.getClient().authenticate(authData); // // authenticationCallback.onSuccessfulAuthentication(); // } catch (Exception ex) { // authenticationCallback.onFailedAuthentication(ex); // } // } // // public RedditClient getClient() { // return this.redditClient; // } // // public AccountManager getAccountManager() { // return this.accountManager; // } // // public AuthenticationManager getAuthenticationManager() { // return this.authenticationManager; // } // // public Credentials getCredentials() { // return this.credentialFactory.getCredentials(); // } // // public Credentials getAnonymousCredentials() { // return this.anonymousCredentialFactory.getCredentials(); // } // } // Path: app/src/main/java/party/minge/reddit/menu/SidebarMenuItemRepository.java import android.content.Context; import net.dean.jraw.http.AuthenticationMethod; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.RootContext; import java.util.ArrayList; import party.minge.reddit.client.Manager; import party.minge.reddit.menu.items.About_; import party.minge.reddit.menu.items.Login_; import party.minge.reddit.menu.items.Logout_; import party.minge.reddit.menu.items.ViewSubreddit_; package party.minge.reddit.menu; @EBean public class SidebarMenuItemRepository { @RootContext protected Context rootContext; @Bean
protected Manager manager;
etiennestuder/teamcity-build-scan-plugin
src/main/java/nu/studer/teamcity/buildscan/internal/BuildScanServiceMessageListener.java
// Path: src/main/java/nu/studer/teamcity/buildscan/BuildScanDataStore.java // public interface BuildScanDataStore { // // /** // * Stores an empty data set for the given build. Calls to {@link #fetch} differentiate between returning an empty // * result set and {@code null} for a build for which no information exists. Calls to this method will store an // * empty entry in the store for the given build resulting in subsequent calls to {@link #fetch} returning an // * empty collection instead of {@code null}. // * // * Calls to this method after calling {@link #store} for the same build are ignored. Existing data for the // * build will remain unchanged. // * // * @param build the build for which no scans have yet been published // */ // void mark(SBuild build); // // /** // * Stores the given build scan URL and associates with the given build. This method can be called multiple times // * with the same build to store more than one build scan URL. // * // * @param build the build that published the build scan // * @param buildScanUrl the URL of the published build scan // */ // void store(SBuild build, String buildScanUrl); // // /** // * Returns the list of all build scans published by the given build. If the build published no scans an empty list // * is returned or {@code null} if no data exists for the requested build. // * // * @param build the requested build // * @return all published scans for the given build or {@code null} if no data exists for the given build // */ // @Nullable // List<BuildScanReference> fetch(SBuild build); // // }
import jetbrains.buildServer.messages.BuildMessage1; import jetbrains.buildServer.messages.serviceMessages.ServiceMessage; import jetbrains.buildServer.messages.serviceMessages.ServiceMessageTranslator; import jetbrains.buildServer.serverSide.SRunningBuild; import nu.studer.teamcity.buildscan.BuildScanDataStore; import org.apache.log4j.Logger; import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.List; import static java.util.Objects.requireNonNull;
package nu.studer.teamcity.buildscan.internal; public final class BuildScanServiceMessageListener implements ServiceMessageTranslator { private static final Logger LOGGER = Logger.getLogger("jetbrains.buildServer.BUILDSCAN"); // values need to be kept in sync with build-scan-init.gradle private static final String BUILD_SCAN_SERVICE_MESSAGE_NAME = "nu.studer.teamcity.buildscan.buildScanLifeCycle"; private static final String BUILD_SCAN_SERVICE_STARTED_MESSAGE_ARGUMENT = "BUILD_STARTED"; private static final String BUILD_SCAN_SERVICE_URL_MESSAGE_ARGUMENT_PREFIX = "BUILD_SCAN_URL:";
// Path: src/main/java/nu/studer/teamcity/buildscan/BuildScanDataStore.java // public interface BuildScanDataStore { // // /** // * Stores an empty data set for the given build. Calls to {@link #fetch} differentiate between returning an empty // * result set and {@code null} for a build for which no information exists. Calls to this method will store an // * empty entry in the store for the given build resulting in subsequent calls to {@link #fetch} returning an // * empty collection instead of {@code null}. // * // * Calls to this method after calling {@link #store} for the same build are ignored. Existing data for the // * build will remain unchanged. // * // * @param build the build for which no scans have yet been published // */ // void mark(SBuild build); // // /** // * Stores the given build scan URL and associates with the given build. This method can be called multiple times // * with the same build to store more than one build scan URL. // * // * @param build the build that published the build scan // * @param buildScanUrl the URL of the published build scan // */ // void store(SBuild build, String buildScanUrl); // // /** // * Returns the list of all build scans published by the given build. If the build published no scans an empty list // * is returned or {@code null} if no data exists for the requested build. // * // * @param build the requested build // * @return all published scans for the given build or {@code null} if no data exists for the given build // */ // @Nullable // List<BuildScanReference> fetch(SBuild build); // // } // Path: src/main/java/nu/studer/teamcity/buildscan/internal/BuildScanServiceMessageListener.java import jetbrains.buildServer.messages.BuildMessage1; import jetbrains.buildServer.messages.serviceMessages.ServiceMessage; import jetbrains.buildServer.messages.serviceMessages.ServiceMessageTranslator; import jetbrains.buildServer.serverSide.SRunningBuild; import nu.studer.teamcity.buildscan.BuildScanDataStore; import org.apache.log4j.Logger; import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.List; import static java.util.Objects.requireNonNull; package nu.studer.teamcity.buildscan.internal; public final class BuildScanServiceMessageListener implements ServiceMessageTranslator { private static final Logger LOGGER = Logger.getLogger("jetbrains.buildServer.BUILDSCAN"); // values need to be kept in sync with build-scan-init.gradle private static final String BUILD_SCAN_SERVICE_MESSAGE_NAME = "nu.studer.teamcity.buildscan.buildScanLifeCycle"; private static final String BUILD_SCAN_SERVICE_STARTED_MESSAGE_ARGUMENT = "BUILD_STARTED"; private static final String BUILD_SCAN_SERVICE_URL_MESSAGE_ARGUMENT_PREFIX = "BUILD_SCAN_URL:";
private final BuildScanDataStore buildScanDataStore;
etiennestuder/teamcity-build-scan-plugin
src/main/java/nu/studer/teamcity/buildscan/internal/DefaultBuildScanDisplayArbiter.java
// Path: src/main/java/nu/studer/teamcity/buildscan/BuildScanDisplayArbiter.java // public interface BuildScanDisplayArbiter { // // boolean showBuildScanInfo(@NotNull SBuild build); // // } // // Path: src/main/java/nu/studer/teamcity/buildscan/BuildScanLookup.java // public interface BuildScanLookup { // // @NotNull // BuildScanReferences getBuildScansForBuild(@NotNull SBuild build); // // }
import jetbrains.buildServer.serverSide.SBuild; import jetbrains.buildServer.serverSide.SBuildType; import nu.studer.teamcity.buildscan.BuildScanDisplayArbiter; import nu.studer.teamcity.buildscan.BuildScanLookup; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.List;
package nu.studer.teamcity.buildscan.internal; public final class DefaultBuildScanDisplayArbiter implements BuildScanDisplayArbiter { static final String GRADLE_RUNNER = "gradle-runner"; static final String MAVEN_RUNNER = "Maven2"; static final String SIMPLE_RUNNER = "simpleRunner"; private static final List<String> BUILD_SCAN_SUPPORTING_RUNNER_TYPES = Arrays.asList(GRADLE_RUNNER, MAVEN_RUNNER, SIMPLE_RUNNER);
// Path: src/main/java/nu/studer/teamcity/buildscan/BuildScanDisplayArbiter.java // public interface BuildScanDisplayArbiter { // // boolean showBuildScanInfo(@NotNull SBuild build); // // } // // Path: src/main/java/nu/studer/teamcity/buildscan/BuildScanLookup.java // public interface BuildScanLookup { // // @NotNull // BuildScanReferences getBuildScansForBuild(@NotNull SBuild build); // // } // Path: src/main/java/nu/studer/teamcity/buildscan/internal/DefaultBuildScanDisplayArbiter.java import jetbrains.buildServer.serverSide.SBuild; import jetbrains.buildServer.serverSide.SBuildType; import nu.studer.teamcity.buildscan.BuildScanDisplayArbiter; import nu.studer.teamcity.buildscan.BuildScanLookup; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.List; package nu.studer.teamcity.buildscan.internal; public final class DefaultBuildScanDisplayArbiter implements BuildScanDisplayArbiter { static final String GRADLE_RUNNER = "gradle-runner"; static final String MAVEN_RUNNER = "Maven2"; static final String SIMPLE_RUNNER = "simpleRunner"; private static final List<String> BUILD_SCAN_SUPPORTING_RUNNER_TYPES = Arrays.asList(GRADLE_RUNNER, MAVEN_RUNNER, SIMPLE_RUNNER);
private final BuildScanLookup buildScanLookup;
sgtcaze/NametagEdit
src/main/java/com/nametagedit/plugin/storage/database/tasks/PlayerPriority.java
// Path: src/main/java/com/nametagedit/plugin/storage/database/DatabaseConfig.java // public class DatabaseConfig implements AbstractConfig { // // private NametagEdit plugin; // private NametagHandler handler; // private HikariDataSource hikari; // // // These are used if the user wants to customize the // // schema structure. Perhaps more cosmetic. // public static String TABLE_GROUPS; // public static String TABLE_PLAYERS; // public static String TABLE_CONFIG; // // public DatabaseConfig(NametagEdit plugin, NametagHandler handler, Configuration config) { // this.plugin = plugin; // this.handler = handler; // TABLE_GROUPS = "`" + config.getString("MySQL.GroupsTable", "nte_groups") + "`"; // TABLE_PLAYERS = "`" + config.getString("MySQL.PlayersTable", "nte_players") + "`"; // TABLE_CONFIG = "`" + config.getString("MySQL.ConfigTable", "nte_config") + "`"; // } // // @Override // public void load() { // FileConfiguration config = handler.getConfig(); // shutdown(); // hikari = new HikariDataSource(); // hikari.setMaximumPoolSize(config.getInt("MinimumPoolSize", 10)); // hikari.setPoolName("NametagEdit Pool"); // // String port = "3306"; // // if (config.isSet("MySQL.Port")) { // port = config.getString("MySQL.Port"); // } // // hikari.setJdbcUrl("jdbc:mysql://" + config.getString("MySQL.Hostname") + ":" + port + "/" + config.getString("MySQL.Database")); // hikari.addDataSourceProperty("useSSL", false); // hikari.addDataSourceProperty("requireSSL", false); // hikari.addDataSourceProperty("verifyServerCertificate", false); // hikari.addDataSourceProperty("user", config.getString("MySQL.Username")); // hikari.addDataSourceProperty("password", config.getString("MySQL.Password")); // // hikari.setUsername(config.getString("MySQL.Username")); // hikari.setPassword(config.getString("MySQL.Password")); // // new DatabaseUpdater(handler, hikari, plugin).runTaskAsynchronously(plugin); // } // // @Override // public void reload() { // new DataDownloader(handler, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void shutdown() { // if (hikari != null) { // hikari.close(); // } // } // // @Override // public void load(Player player, boolean loggedIn) { // new PlayerLoader(player.getUniqueId(), plugin, handler, hikari, loggedIn).runTaskAsynchronously(plugin); // } // // @Override // public void save(PlayerData... playerData) { // new PlayerSaver(playerData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void save(GroupData... groupData) { // new GroupSaver(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void savePriority(boolean playerTag, String key, final int priority) { // if (playerTag) { // UUIDFetcher.lookupUUID(key, plugin, uuid -> { // if (uuid != null) { // new PlayerPriority(uuid, priority, hikari).runTaskAsynchronously(plugin); // } else { // plugin.getLogger().severe("An error has occurred while looking for UUID."); // } // }); // } else { // new GroupPriority(key, priority, hikari).runTaskAsynchronously(plugin); // } // } // // @Override // public void delete(GroupData groupData) { // new GroupDeleter(groupData.getGroupName(), hikari).runTaskAsynchronously(plugin); // } // // @Override // public void add(GroupData groupData) { // new GroupAdd(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void clear(UUID uuid, String targetName) { // new PlayerDeleter(uuid, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void orderGroups(CommandSender commandSender, List<String> order) { // String formatted = Arrays.toString(order.toArray()); // formatted = formatted.substring(1, formatted.length() - 1).replace(",", ""); // new GroupConfigUpdater("order", formatted, hikari).runTaskAsynchronously(handler.getPlugin()); // } // // }
import com.nametagedit.plugin.storage.database.DatabaseConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.AllArgsConstructor; import org.bukkit.scheduler.BukkitRunnable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.UUID;
package com.nametagedit.plugin.storage.database.tasks; @AllArgsConstructor public class PlayerPriority extends BukkitRunnable { private final UUID player; private final int priority; private final HikariDataSource hikari; @Override public void run() { try (Connection connection = hikari.getConnection()) {
// Path: src/main/java/com/nametagedit/plugin/storage/database/DatabaseConfig.java // public class DatabaseConfig implements AbstractConfig { // // private NametagEdit plugin; // private NametagHandler handler; // private HikariDataSource hikari; // // // These are used if the user wants to customize the // // schema structure. Perhaps more cosmetic. // public static String TABLE_GROUPS; // public static String TABLE_PLAYERS; // public static String TABLE_CONFIG; // // public DatabaseConfig(NametagEdit plugin, NametagHandler handler, Configuration config) { // this.plugin = plugin; // this.handler = handler; // TABLE_GROUPS = "`" + config.getString("MySQL.GroupsTable", "nte_groups") + "`"; // TABLE_PLAYERS = "`" + config.getString("MySQL.PlayersTable", "nte_players") + "`"; // TABLE_CONFIG = "`" + config.getString("MySQL.ConfigTable", "nte_config") + "`"; // } // // @Override // public void load() { // FileConfiguration config = handler.getConfig(); // shutdown(); // hikari = new HikariDataSource(); // hikari.setMaximumPoolSize(config.getInt("MinimumPoolSize", 10)); // hikari.setPoolName("NametagEdit Pool"); // // String port = "3306"; // // if (config.isSet("MySQL.Port")) { // port = config.getString("MySQL.Port"); // } // // hikari.setJdbcUrl("jdbc:mysql://" + config.getString("MySQL.Hostname") + ":" + port + "/" + config.getString("MySQL.Database")); // hikari.addDataSourceProperty("useSSL", false); // hikari.addDataSourceProperty("requireSSL", false); // hikari.addDataSourceProperty("verifyServerCertificate", false); // hikari.addDataSourceProperty("user", config.getString("MySQL.Username")); // hikari.addDataSourceProperty("password", config.getString("MySQL.Password")); // // hikari.setUsername(config.getString("MySQL.Username")); // hikari.setPassword(config.getString("MySQL.Password")); // // new DatabaseUpdater(handler, hikari, plugin).runTaskAsynchronously(plugin); // } // // @Override // public void reload() { // new DataDownloader(handler, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void shutdown() { // if (hikari != null) { // hikari.close(); // } // } // // @Override // public void load(Player player, boolean loggedIn) { // new PlayerLoader(player.getUniqueId(), plugin, handler, hikari, loggedIn).runTaskAsynchronously(plugin); // } // // @Override // public void save(PlayerData... playerData) { // new PlayerSaver(playerData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void save(GroupData... groupData) { // new GroupSaver(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void savePriority(boolean playerTag, String key, final int priority) { // if (playerTag) { // UUIDFetcher.lookupUUID(key, plugin, uuid -> { // if (uuid != null) { // new PlayerPriority(uuid, priority, hikari).runTaskAsynchronously(plugin); // } else { // plugin.getLogger().severe("An error has occurred while looking for UUID."); // } // }); // } else { // new GroupPriority(key, priority, hikari).runTaskAsynchronously(plugin); // } // } // // @Override // public void delete(GroupData groupData) { // new GroupDeleter(groupData.getGroupName(), hikari).runTaskAsynchronously(plugin); // } // // @Override // public void add(GroupData groupData) { // new GroupAdd(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void clear(UUID uuid, String targetName) { // new PlayerDeleter(uuid, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void orderGroups(CommandSender commandSender, List<String> order) { // String formatted = Arrays.toString(order.toArray()); // formatted = formatted.substring(1, formatted.length() - 1).replace(",", ""); // new GroupConfigUpdater("order", formatted, hikari).runTaskAsynchronously(handler.getPlugin()); // } // // } // Path: src/main/java/com/nametagedit/plugin/storage/database/tasks/PlayerPriority.java import com.nametagedit.plugin.storage.database.DatabaseConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.AllArgsConstructor; import org.bukkit.scheduler.BukkitRunnable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.UUID; package com.nametagedit.plugin.storage.database.tasks; @AllArgsConstructor public class PlayerPriority extends BukkitRunnable { private final UUID player; private final int priority; private final HikariDataSource hikari; @Override public void run() { try (Connection connection = hikari.getConnection()) {
PreparedStatement preparedStatement = connection.prepareStatement("UPDATE " + DatabaseConfig.TABLE_PLAYERS + " SET `priority`=? WHERE `uuid`=?");
sgtcaze/NametagEdit
src/main/java/com/nametagedit/plugin/storage/database/tasks/GroupPriority.java
// Path: src/main/java/com/nametagedit/plugin/storage/database/DatabaseConfig.java // public class DatabaseConfig implements AbstractConfig { // // private NametagEdit plugin; // private NametagHandler handler; // private HikariDataSource hikari; // // // These are used if the user wants to customize the // // schema structure. Perhaps more cosmetic. // public static String TABLE_GROUPS; // public static String TABLE_PLAYERS; // public static String TABLE_CONFIG; // // public DatabaseConfig(NametagEdit plugin, NametagHandler handler, Configuration config) { // this.plugin = plugin; // this.handler = handler; // TABLE_GROUPS = "`" + config.getString("MySQL.GroupsTable", "nte_groups") + "`"; // TABLE_PLAYERS = "`" + config.getString("MySQL.PlayersTable", "nte_players") + "`"; // TABLE_CONFIG = "`" + config.getString("MySQL.ConfigTable", "nte_config") + "`"; // } // // @Override // public void load() { // FileConfiguration config = handler.getConfig(); // shutdown(); // hikari = new HikariDataSource(); // hikari.setMaximumPoolSize(config.getInt("MinimumPoolSize", 10)); // hikari.setPoolName("NametagEdit Pool"); // // String port = "3306"; // // if (config.isSet("MySQL.Port")) { // port = config.getString("MySQL.Port"); // } // // hikari.setJdbcUrl("jdbc:mysql://" + config.getString("MySQL.Hostname") + ":" + port + "/" + config.getString("MySQL.Database")); // hikari.addDataSourceProperty("useSSL", false); // hikari.addDataSourceProperty("requireSSL", false); // hikari.addDataSourceProperty("verifyServerCertificate", false); // hikari.addDataSourceProperty("user", config.getString("MySQL.Username")); // hikari.addDataSourceProperty("password", config.getString("MySQL.Password")); // // hikari.setUsername(config.getString("MySQL.Username")); // hikari.setPassword(config.getString("MySQL.Password")); // // new DatabaseUpdater(handler, hikari, plugin).runTaskAsynchronously(plugin); // } // // @Override // public void reload() { // new DataDownloader(handler, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void shutdown() { // if (hikari != null) { // hikari.close(); // } // } // // @Override // public void load(Player player, boolean loggedIn) { // new PlayerLoader(player.getUniqueId(), plugin, handler, hikari, loggedIn).runTaskAsynchronously(plugin); // } // // @Override // public void save(PlayerData... playerData) { // new PlayerSaver(playerData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void save(GroupData... groupData) { // new GroupSaver(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void savePriority(boolean playerTag, String key, final int priority) { // if (playerTag) { // UUIDFetcher.lookupUUID(key, plugin, uuid -> { // if (uuid != null) { // new PlayerPriority(uuid, priority, hikari).runTaskAsynchronously(plugin); // } else { // plugin.getLogger().severe("An error has occurred while looking for UUID."); // } // }); // } else { // new GroupPriority(key, priority, hikari).runTaskAsynchronously(plugin); // } // } // // @Override // public void delete(GroupData groupData) { // new GroupDeleter(groupData.getGroupName(), hikari).runTaskAsynchronously(plugin); // } // // @Override // public void add(GroupData groupData) { // new GroupAdd(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void clear(UUID uuid, String targetName) { // new PlayerDeleter(uuid, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void orderGroups(CommandSender commandSender, List<String> order) { // String formatted = Arrays.toString(order.toArray()); // formatted = formatted.substring(1, formatted.length() - 1).replace(",", ""); // new GroupConfigUpdater("order", formatted, hikari).runTaskAsynchronously(handler.getPlugin()); // } // // }
import com.nametagedit.plugin.storage.database.DatabaseConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.AllArgsConstructor; import org.bukkit.scheduler.BukkitRunnable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException;
package com.nametagedit.plugin.storage.database.tasks; @AllArgsConstructor public class GroupPriority extends BukkitRunnable { private final String group; private final int priority; private final HikariDataSource hikari; @Override public void run() { try (Connection connection = hikari.getConnection()) {
// Path: src/main/java/com/nametagedit/plugin/storage/database/DatabaseConfig.java // public class DatabaseConfig implements AbstractConfig { // // private NametagEdit plugin; // private NametagHandler handler; // private HikariDataSource hikari; // // // These are used if the user wants to customize the // // schema structure. Perhaps more cosmetic. // public static String TABLE_GROUPS; // public static String TABLE_PLAYERS; // public static String TABLE_CONFIG; // // public DatabaseConfig(NametagEdit plugin, NametagHandler handler, Configuration config) { // this.plugin = plugin; // this.handler = handler; // TABLE_GROUPS = "`" + config.getString("MySQL.GroupsTable", "nte_groups") + "`"; // TABLE_PLAYERS = "`" + config.getString("MySQL.PlayersTable", "nte_players") + "`"; // TABLE_CONFIG = "`" + config.getString("MySQL.ConfigTable", "nte_config") + "`"; // } // // @Override // public void load() { // FileConfiguration config = handler.getConfig(); // shutdown(); // hikari = new HikariDataSource(); // hikari.setMaximumPoolSize(config.getInt("MinimumPoolSize", 10)); // hikari.setPoolName("NametagEdit Pool"); // // String port = "3306"; // // if (config.isSet("MySQL.Port")) { // port = config.getString("MySQL.Port"); // } // // hikari.setJdbcUrl("jdbc:mysql://" + config.getString("MySQL.Hostname") + ":" + port + "/" + config.getString("MySQL.Database")); // hikari.addDataSourceProperty("useSSL", false); // hikari.addDataSourceProperty("requireSSL", false); // hikari.addDataSourceProperty("verifyServerCertificate", false); // hikari.addDataSourceProperty("user", config.getString("MySQL.Username")); // hikari.addDataSourceProperty("password", config.getString("MySQL.Password")); // // hikari.setUsername(config.getString("MySQL.Username")); // hikari.setPassword(config.getString("MySQL.Password")); // // new DatabaseUpdater(handler, hikari, plugin).runTaskAsynchronously(plugin); // } // // @Override // public void reload() { // new DataDownloader(handler, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void shutdown() { // if (hikari != null) { // hikari.close(); // } // } // // @Override // public void load(Player player, boolean loggedIn) { // new PlayerLoader(player.getUniqueId(), plugin, handler, hikari, loggedIn).runTaskAsynchronously(plugin); // } // // @Override // public void save(PlayerData... playerData) { // new PlayerSaver(playerData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void save(GroupData... groupData) { // new GroupSaver(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void savePriority(boolean playerTag, String key, final int priority) { // if (playerTag) { // UUIDFetcher.lookupUUID(key, plugin, uuid -> { // if (uuid != null) { // new PlayerPriority(uuid, priority, hikari).runTaskAsynchronously(plugin); // } else { // plugin.getLogger().severe("An error has occurred while looking for UUID."); // } // }); // } else { // new GroupPriority(key, priority, hikari).runTaskAsynchronously(plugin); // } // } // // @Override // public void delete(GroupData groupData) { // new GroupDeleter(groupData.getGroupName(), hikari).runTaskAsynchronously(plugin); // } // // @Override // public void add(GroupData groupData) { // new GroupAdd(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void clear(UUID uuid, String targetName) { // new PlayerDeleter(uuid, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void orderGroups(CommandSender commandSender, List<String> order) { // String formatted = Arrays.toString(order.toArray()); // formatted = formatted.substring(1, formatted.length() - 1).replace(",", ""); // new GroupConfigUpdater("order", formatted, hikari).runTaskAsynchronously(handler.getPlugin()); // } // // } // Path: src/main/java/com/nametagedit/plugin/storage/database/tasks/GroupPriority.java import com.nametagedit.plugin.storage.database.DatabaseConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.AllArgsConstructor; import org.bukkit.scheduler.BukkitRunnable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; package com.nametagedit.plugin.storage.database.tasks; @AllArgsConstructor public class GroupPriority extends BukkitRunnable { private final String group; private final int priority; private final HikariDataSource hikari; @Override public void run() { try (Connection connection = hikari.getConnection()) {
PreparedStatement preparedStatement = connection.prepareStatement("UPDATE " + DatabaseConfig.TABLE_GROUPS + " SET `priority`=? WHERE `name`=?");
sgtcaze/NametagEdit
src/main/java/com/nametagedit/plugin/storage/database/tasks/GroupAdd.java
// Path: src/main/java/com/nametagedit/plugin/api/data/GroupData.java // @Data // @AllArgsConstructor // public class GroupData implements INametag { // // private String groupName; // private String prefix; // private String suffix; // private String permission; // private Permission bukkitPermission; // private int sortPriority; // // public GroupData() { // // } // // public void setPermission(String permission) { // this.permission = permission; // bukkitPermission = new Permission(permission, PermissionDefault.FALSE); // } // // @Override // public boolean isPlayerTag() { // return false; // } // // } // // Path: src/main/java/com/nametagedit/plugin/storage/database/DatabaseConfig.java // public class DatabaseConfig implements AbstractConfig { // // private NametagEdit plugin; // private NametagHandler handler; // private HikariDataSource hikari; // // // These are used if the user wants to customize the // // schema structure. Perhaps more cosmetic. // public static String TABLE_GROUPS; // public static String TABLE_PLAYERS; // public static String TABLE_CONFIG; // // public DatabaseConfig(NametagEdit plugin, NametagHandler handler, Configuration config) { // this.plugin = plugin; // this.handler = handler; // TABLE_GROUPS = "`" + config.getString("MySQL.GroupsTable", "nte_groups") + "`"; // TABLE_PLAYERS = "`" + config.getString("MySQL.PlayersTable", "nte_players") + "`"; // TABLE_CONFIG = "`" + config.getString("MySQL.ConfigTable", "nte_config") + "`"; // } // // @Override // public void load() { // FileConfiguration config = handler.getConfig(); // shutdown(); // hikari = new HikariDataSource(); // hikari.setMaximumPoolSize(config.getInt("MinimumPoolSize", 10)); // hikari.setPoolName("NametagEdit Pool"); // // String port = "3306"; // // if (config.isSet("MySQL.Port")) { // port = config.getString("MySQL.Port"); // } // // hikari.setJdbcUrl("jdbc:mysql://" + config.getString("MySQL.Hostname") + ":" + port + "/" + config.getString("MySQL.Database")); // hikari.addDataSourceProperty("useSSL", false); // hikari.addDataSourceProperty("requireSSL", false); // hikari.addDataSourceProperty("verifyServerCertificate", false); // hikari.addDataSourceProperty("user", config.getString("MySQL.Username")); // hikari.addDataSourceProperty("password", config.getString("MySQL.Password")); // // hikari.setUsername(config.getString("MySQL.Username")); // hikari.setPassword(config.getString("MySQL.Password")); // // new DatabaseUpdater(handler, hikari, plugin).runTaskAsynchronously(plugin); // } // // @Override // public void reload() { // new DataDownloader(handler, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void shutdown() { // if (hikari != null) { // hikari.close(); // } // } // // @Override // public void load(Player player, boolean loggedIn) { // new PlayerLoader(player.getUniqueId(), plugin, handler, hikari, loggedIn).runTaskAsynchronously(plugin); // } // // @Override // public void save(PlayerData... playerData) { // new PlayerSaver(playerData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void save(GroupData... groupData) { // new GroupSaver(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void savePriority(boolean playerTag, String key, final int priority) { // if (playerTag) { // UUIDFetcher.lookupUUID(key, plugin, uuid -> { // if (uuid != null) { // new PlayerPriority(uuid, priority, hikari).runTaskAsynchronously(plugin); // } else { // plugin.getLogger().severe("An error has occurred while looking for UUID."); // } // }); // } else { // new GroupPriority(key, priority, hikari).runTaskAsynchronously(plugin); // } // } // // @Override // public void delete(GroupData groupData) { // new GroupDeleter(groupData.getGroupName(), hikari).runTaskAsynchronously(plugin); // } // // @Override // public void add(GroupData groupData) { // new GroupAdd(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void clear(UUID uuid, String targetName) { // new PlayerDeleter(uuid, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void orderGroups(CommandSender commandSender, List<String> order) { // String formatted = Arrays.toString(order.toArray()); // formatted = formatted.substring(1, formatted.length() - 1).replace(",", ""); // new GroupConfigUpdater("order", formatted, hikari).runTaskAsynchronously(handler.getPlugin()); // } // // }
import com.nametagedit.plugin.api.data.GroupData; import com.nametagedit.plugin.storage.database.DatabaseConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.AllArgsConstructor; import org.bukkit.scheduler.BukkitRunnable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException;
package com.nametagedit.plugin.storage.database.tasks; @AllArgsConstructor public class GroupAdd extends BukkitRunnable {
// Path: src/main/java/com/nametagedit/plugin/api/data/GroupData.java // @Data // @AllArgsConstructor // public class GroupData implements INametag { // // private String groupName; // private String prefix; // private String suffix; // private String permission; // private Permission bukkitPermission; // private int sortPriority; // // public GroupData() { // // } // // public void setPermission(String permission) { // this.permission = permission; // bukkitPermission = new Permission(permission, PermissionDefault.FALSE); // } // // @Override // public boolean isPlayerTag() { // return false; // } // // } // // Path: src/main/java/com/nametagedit/plugin/storage/database/DatabaseConfig.java // public class DatabaseConfig implements AbstractConfig { // // private NametagEdit plugin; // private NametagHandler handler; // private HikariDataSource hikari; // // // These are used if the user wants to customize the // // schema structure. Perhaps more cosmetic. // public static String TABLE_GROUPS; // public static String TABLE_PLAYERS; // public static String TABLE_CONFIG; // // public DatabaseConfig(NametagEdit plugin, NametagHandler handler, Configuration config) { // this.plugin = plugin; // this.handler = handler; // TABLE_GROUPS = "`" + config.getString("MySQL.GroupsTable", "nte_groups") + "`"; // TABLE_PLAYERS = "`" + config.getString("MySQL.PlayersTable", "nte_players") + "`"; // TABLE_CONFIG = "`" + config.getString("MySQL.ConfigTable", "nte_config") + "`"; // } // // @Override // public void load() { // FileConfiguration config = handler.getConfig(); // shutdown(); // hikari = new HikariDataSource(); // hikari.setMaximumPoolSize(config.getInt("MinimumPoolSize", 10)); // hikari.setPoolName("NametagEdit Pool"); // // String port = "3306"; // // if (config.isSet("MySQL.Port")) { // port = config.getString("MySQL.Port"); // } // // hikari.setJdbcUrl("jdbc:mysql://" + config.getString("MySQL.Hostname") + ":" + port + "/" + config.getString("MySQL.Database")); // hikari.addDataSourceProperty("useSSL", false); // hikari.addDataSourceProperty("requireSSL", false); // hikari.addDataSourceProperty("verifyServerCertificate", false); // hikari.addDataSourceProperty("user", config.getString("MySQL.Username")); // hikari.addDataSourceProperty("password", config.getString("MySQL.Password")); // // hikari.setUsername(config.getString("MySQL.Username")); // hikari.setPassword(config.getString("MySQL.Password")); // // new DatabaseUpdater(handler, hikari, plugin).runTaskAsynchronously(plugin); // } // // @Override // public void reload() { // new DataDownloader(handler, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void shutdown() { // if (hikari != null) { // hikari.close(); // } // } // // @Override // public void load(Player player, boolean loggedIn) { // new PlayerLoader(player.getUniqueId(), plugin, handler, hikari, loggedIn).runTaskAsynchronously(plugin); // } // // @Override // public void save(PlayerData... playerData) { // new PlayerSaver(playerData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void save(GroupData... groupData) { // new GroupSaver(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void savePriority(boolean playerTag, String key, final int priority) { // if (playerTag) { // UUIDFetcher.lookupUUID(key, plugin, uuid -> { // if (uuid != null) { // new PlayerPriority(uuid, priority, hikari).runTaskAsynchronously(plugin); // } else { // plugin.getLogger().severe("An error has occurred while looking for UUID."); // } // }); // } else { // new GroupPriority(key, priority, hikari).runTaskAsynchronously(plugin); // } // } // // @Override // public void delete(GroupData groupData) { // new GroupDeleter(groupData.getGroupName(), hikari).runTaskAsynchronously(plugin); // } // // @Override // public void add(GroupData groupData) { // new GroupAdd(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void clear(UUID uuid, String targetName) { // new PlayerDeleter(uuid, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void orderGroups(CommandSender commandSender, List<String> order) { // String formatted = Arrays.toString(order.toArray()); // formatted = formatted.substring(1, formatted.length() - 1).replace(",", ""); // new GroupConfigUpdater("order", formatted, hikari).runTaskAsynchronously(handler.getPlugin()); // } // // } // Path: src/main/java/com/nametagedit/plugin/storage/database/tasks/GroupAdd.java import com.nametagedit.plugin.api.data.GroupData; import com.nametagedit.plugin.storage.database.DatabaseConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.AllArgsConstructor; import org.bukkit.scheduler.BukkitRunnable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; package com.nametagedit.plugin.storage.database.tasks; @AllArgsConstructor public class GroupAdd extends BukkitRunnable {
private final GroupData groupData;
sgtcaze/NametagEdit
src/main/java/com/nametagedit/plugin/storage/database/tasks/GroupAdd.java
// Path: src/main/java/com/nametagedit/plugin/api/data/GroupData.java // @Data // @AllArgsConstructor // public class GroupData implements INametag { // // private String groupName; // private String prefix; // private String suffix; // private String permission; // private Permission bukkitPermission; // private int sortPriority; // // public GroupData() { // // } // // public void setPermission(String permission) { // this.permission = permission; // bukkitPermission = new Permission(permission, PermissionDefault.FALSE); // } // // @Override // public boolean isPlayerTag() { // return false; // } // // } // // Path: src/main/java/com/nametagedit/plugin/storage/database/DatabaseConfig.java // public class DatabaseConfig implements AbstractConfig { // // private NametagEdit plugin; // private NametagHandler handler; // private HikariDataSource hikari; // // // These are used if the user wants to customize the // // schema structure. Perhaps more cosmetic. // public static String TABLE_GROUPS; // public static String TABLE_PLAYERS; // public static String TABLE_CONFIG; // // public DatabaseConfig(NametagEdit plugin, NametagHandler handler, Configuration config) { // this.plugin = plugin; // this.handler = handler; // TABLE_GROUPS = "`" + config.getString("MySQL.GroupsTable", "nte_groups") + "`"; // TABLE_PLAYERS = "`" + config.getString("MySQL.PlayersTable", "nte_players") + "`"; // TABLE_CONFIG = "`" + config.getString("MySQL.ConfigTable", "nte_config") + "`"; // } // // @Override // public void load() { // FileConfiguration config = handler.getConfig(); // shutdown(); // hikari = new HikariDataSource(); // hikari.setMaximumPoolSize(config.getInt("MinimumPoolSize", 10)); // hikari.setPoolName("NametagEdit Pool"); // // String port = "3306"; // // if (config.isSet("MySQL.Port")) { // port = config.getString("MySQL.Port"); // } // // hikari.setJdbcUrl("jdbc:mysql://" + config.getString("MySQL.Hostname") + ":" + port + "/" + config.getString("MySQL.Database")); // hikari.addDataSourceProperty("useSSL", false); // hikari.addDataSourceProperty("requireSSL", false); // hikari.addDataSourceProperty("verifyServerCertificate", false); // hikari.addDataSourceProperty("user", config.getString("MySQL.Username")); // hikari.addDataSourceProperty("password", config.getString("MySQL.Password")); // // hikari.setUsername(config.getString("MySQL.Username")); // hikari.setPassword(config.getString("MySQL.Password")); // // new DatabaseUpdater(handler, hikari, plugin).runTaskAsynchronously(plugin); // } // // @Override // public void reload() { // new DataDownloader(handler, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void shutdown() { // if (hikari != null) { // hikari.close(); // } // } // // @Override // public void load(Player player, boolean loggedIn) { // new PlayerLoader(player.getUniqueId(), plugin, handler, hikari, loggedIn).runTaskAsynchronously(plugin); // } // // @Override // public void save(PlayerData... playerData) { // new PlayerSaver(playerData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void save(GroupData... groupData) { // new GroupSaver(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void savePriority(boolean playerTag, String key, final int priority) { // if (playerTag) { // UUIDFetcher.lookupUUID(key, plugin, uuid -> { // if (uuid != null) { // new PlayerPriority(uuid, priority, hikari).runTaskAsynchronously(plugin); // } else { // plugin.getLogger().severe("An error has occurred while looking for UUID."); // } // }); // } else { // new GroupPriority(key, priority, hikari).runTaskAsynchronously(plugin); // } // } // // @Override // public void delete(GroupData groupData) { // new GroupDeleter(groupData.getGroupName(), hikari).runTaskAsynchronously(plugin); // } // // @Override // public void add(GroupData groupData) { // new GroupAdd(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void clear(UUID uuid, String targetName) { // new PlayerDeleter(uuid, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void orderGroups(CommandSender commandSender, List<String> order) { // String formatted = Arrays.toString(order.toArray()); // formatted = formatted.substring(1, formatted.length() - 1).replace(",", ""); // new GroupConfigUpdater("order", formatted, hikari).runTaskAsynchronously(handler.getPlugin()); // } // // }
import com.nametagedit.plugin.api.data.GroupData; import com.nametagedit.plugin.storage.database.DatabaseConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.AllArgsConstructor; import org.bukkit.scheduler.BukkitRunnable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException;
package com.nametagedit.plugin.storage.database.tasks; @AllArgsConstructor public class GroupAdd extends BukkitRunnable { private final GroupData groupData; private final HikariDataSource hikari; @Override public void run() { try (Connection connection = hikari.getConnection()) {
// Path: src/main/java/com/nametagedit/plugin/api/data/GroupData.java // @Data // @AllArgsConstructor // public class GroupData implements INametag { // // private String groupName; // private String prefix; // private String suffix; // private String permission; // private Permission bukkitPermission; // private int sortPriority; // // public GroupData() { // // } // // public void setPermission(String permission) { // this.permission = permission; // bukkitPermission = new Permission(permission, PermissionDefault.FALSE); // } // // @Override // public boolean isPlayerTag() { // return false; // } // // } // // Path: src/main/java/com/nametagedit/plugin/storage/database/DatabaseConfig.java // public class DatabaseConfig implements AbstractConfig { // // private NametagEdit plugin; // private NametagHandler handler; // private HikariDataSource hikari; // // // These are used if the user wants to customize the // // schema structure. Perhaps more cosmetic. // public static String TABLE_GROUPS; // public static String TABLE_PLAYERS; // public static String TABLE_CONFIG; // // public DatabaseConfig(NametagEdit plugin, NametagHandler handler, Configuration config) { // this.plugin = plugin; // this.handler = handler; // TABLE_GROUPS = "`" + config.getString("MySQL.GroupsTable", "nte_groups") + "`"; // TABLE_PLAYERS = "`" + config.getString("MySQL.PlayersTable", "nte_players") + "`"; // TABLE_CONFIG = "`" + config.getString("MySQL.ConfigTable", "nte_config") + "`"; // } // // @Override // public void load() { // FileConfiguration config = handler.getConfig(); // shutdown(); // hikari = new HikariDataSource(); // hikari.setMaximumPoolSize(config.getInt("MinimumPoolSize", 10)); // hikari.setPoolName("NametagEdit Pool"); // // String port = "3306"; // // if (config.isSet("MySQL.Port")) { // port = config.getString("MySQL.Port"); // } // // hikari.setJdbcUrl("jdbc:mysql://" + config.getString("MySQL.Hostname") + ":" + port + "/" + config.getString("MySQL.Database")); // hikari.addDataSourceProperty("useSSL", false); // hikari.addDataSourceProperty("requireSSL", false); // hikari.addDataSourceProperty("verifyServerCertificate", false); // hikari.addDataSourceProperty("user", config.getString("MySQL.Username")); // hikari.addDataSourceProperty("password", config.getString("MySQL.Password")); // // hikari.setUsername(config.getString("MySQL.Username")); // hikari.setPassword(config.getString("MySQL.Password")); // // new DatabaseUpdater(handler, hikari, plugin).runTaskAsynchronously(plugin); // } // // @Override // public void reload() { // new DataDownloader(handler, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void shutdown() { // if (hikari != null) { // hikari.close(); // } // } // // @Override // public void load(Player player, boolean loggedIn) { // new PlayerLoader(player.getUniqueId(), plugin, handler, hikari, loggedIn).runTaskAsynchronously(plugin); // } // // @Override // public void save(PlayerData... playerData) { // new PlayerSaver(playerData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void save(GroupData... groupData) { // new GroupSaver(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void savePriority(boolean playerTag, String key, final int priority) { // if (playerTag) { // UUIDFetcher.lookupUUID(key, plugin, uuid -> { // if (uuid != null) { // new PlayerPriority(uuid, priority, hikari).runTaskAsynchronously(plugin); // } else { // plugin.getLogger().severe("An error has occurred while looking for UUID."); // } // }); // } else { // new GroupPriority(key, priority, hikari).runTaskAsynchronously(plugin); // } // } // // @Override // public void delete(GroupData groupData) { // new GroupDeleter(groupData.getGroupName(), hikari).runTaskAsynchronously(plugin); // } // // @Override // public void add(GroupData groupData) { // new GroupAdd(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void clear(UUID uuid, String targetName) { // new PlayerDeleter(uuid, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void orderGroups(CommandSender commandSender, List<String> order) { // String formatted = Arrays.toString(order.toArray()); // formatted = formatted.substring(1, formatted.length() - 1).replace(",", ""); // new GroupConfigUpdater("order", formatted, hikari).runTaskAsynchronously(handler.getPlugin()); // } // // } // Path: src/main/java/com/nametagedit/plugin/storage/database/tasks/GroupAdd.java import com.nametagedit.plugin.api.data.GroupData; import com.nametagedit.plugin.storage.database.DatabaseConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.AllArgsConstructor; import org.bukkit.scheduler.BukkitRunnable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; package com.nametagedit.plugin.storage.database.tasks; @AllArgsConstructor public class GroupAdd extends BukkitRunnable { private final GroupData groupData; private final HikariDataSource hikari; @Override public void run() { try (Connection connection = hikari.getConnection()) {
final String QUERY = "INSERT INTO " + DatabaseConfig.TABLE_GROUPS + " VALUES(?, ?, ?, ?, ?)";
sgtcaze/NametagEdit
src/main/java/com/nametagedit/plugin/utils/Utils.java
// Path: src/main/java/com/nametagedit/plugin/packets/VersionChecker.java // public class VersionChecker { // // private static final BukkitVersion bukkitVersion; // // static { // final String version = Bukkit.getVersion(); // if (version.contains("(MC: 1.8)") || version.contains("(MC: 1.8.1)") || version.contains("(MC: 1.8.2)")) // bukkitVersion = BukkitVersion.v1_8_R1; // else if (version.contains("(MC: 1.8.3)")) // bukkitVersion = BukkitVersion.v1_8_R2; // else if (version.contains("(MC: 1.8.4)") || version.contains("(MC: 1.8.5)") || version.contains("(MC: 1.8.6)") || version.contains("(MC: 1.8.7)") || version.contains("(MC: 1.8.8)") || version.contains("(MC: 1.8.9)")) // bukkitVersion = BukkitVersion.v1_8_R3; // else if (version.contains("(MC: 1.9)") || version.contains("(MC: 1.9.1)") || version.contains("(MC: 1.9.2)") || version.contains("(MC: 1.9.3)")) // bukkitVersion = BukkitVersion.v1_9_R1; // else if (version.contains("(MC: 1.9.4)")) // bukkitVersion = BukkitVersion.v1_9_R2; // else if (version.contains("(MC: 1.10)") || version.contains("(MC: 1.10.1)") || version.contains("(MC: 1.10.2)")) // bukkitVersion = BukkitVersion.v1_10_R1; // else if (version.contains("(MC: 1.11)") || version.contains("(MC: 1.11.1)") || version.contains("(MC: 1.11.2)")) // bukkitVersion = BukkitVersion.v1_11_R1; // else if (version.contains("(MC: 1.12)") || version.contains("(MC: 1.12.1)") || version.contains("(MC: 1.12.2)")) // bukkitVersion = BukkitVersion.v1_12_R1; // else if (version.contains("(MC: 1.13)")) // bukkitVersion = BukkitVersion.v1_13_R1; // else if (version.contains("(MC: 1.13.1)") || version.contains("(MC: 1.13.2)")) // bukkitVersion = BukkitVersion.v1_13_R2; // else if (version.contains("(MC: 1.14)") || version.contains("(MC: 1.14.1)") || version.contains("(MC: 1.14.2)") || version.contains("(MC: 1.14.3)")) // bukkitVersion = BukkitVersion.v1_14_R1; // else if (version.contains("(MC: 1.14.4)")) // bukkitVersion = BukkitVersion.v1_14_R2; // else if (version.contains("(MC: 1.15)") || version.contains("(MC: 1.15.1)") || version.contains("(MC: 1.15.2)")) // bukkitVersion = BukkitVersion.v1_15_R1; // else if (version.contains("(MC: 1.16.1)")) // bukkitVersion = BukkitVersion.v1_16_R1; // else if (version.contains("(MC: 1.16.2)") || version.contains("(MC: 1.16.3)")) // bukkitVersion = BukkitVersion.v1_16_R2; // else if (version.contains("(MC: 1.16.4)") || version.contains("(MC: 1.16.5)")) // bukkitVersion = BukkitVersion.v1_16_R3; // else if (version.contains("(MC: 1.17)") || version.contains("(MC: 1.17.1)")) // bukkitVersion = BukkitVersion.v1_17_R1; // else // bukkitVersion = null; // } // // public static BukkitVersion getBukkitVersion() { // return bukkitVersion; // } // // public static boolean canHex() { // String[] split = Bukkit.getBukkitVersion().split("-")[0].split("\\."); // String minorVer = split[1]; // return Integer.parseInt(minorVer) >= 16; // } // // public enum BukkitVersion { // v1_8_R1, v1_8_R2, v1_8_R3, v1_9_R1, v1_9_R2, v1_10_R1, v1_11_R1, v1_12_R1, v1_13_R1, v1_13_R2, v1_14_R1, v1_14_R2, v1_15_R1, v1_16_R1, v1_16_R2, v1_16_R3, v1_17_R1 // } // // }
import com.nametagedit.plugin.packets.VersionChecker; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;
package com.nametagedit.plugin.utils; public class Utils { private static final Pattern hexPattern = Pattern.compile("&#([A-Fa-f0-9]{6})"); public static String format(String[] text, int to, int from) { return StringUtils.join(text, ' ', to, from).replace("'", ""); } public static String deformat(String input) { return ChatColor.stripColor(input); } public static String format(String input) { return format(input, false); } public static String format(String input, boolean limitChars) { String colored = color(input);
// Path: src/main/java/com/nametagedit/plugin/packets/VersionChecker.java // public class VersionChecker { // // private static final BukkitVersion bukkitVersion; // // static { // final String version = Bukkit.getVersion(); // if (version.contains("(MC: 1.8)") || version.contains("(MC: 1.8.1)") || version.contains("(MC: 1.8.2)")) // bukkitVersion = BukkitVersion.v1_8_R1; // else if (version.contains("(MC: 1.8.3)")) // bukkitVersion = BukkitVersion.v1_8_R2; // else if (version.contains("(MC: 1.8.4)") || version.contains("(MC: 1.8.5)") || version.contains("(MC: 1.8.6)") || version.contains("(MC: 1.8.7)") || version.contains("(MC: 1.8.8)") || version.contains("(MC: 1.8.9)")) // bukkitVersion = BukkitVersion.v1_8_R3; // else if (version.contains("(MC: 1.9)") || version.contains("(MC: 1.9.1)") || version.contains("(MC: 1.9.2)") || version.contains("(MC: 1.9.3)")) // bukkitVersion = BukkitVersion.v1_9_R1; // else if (version.contains("(MC: 1.9.4)")) // bukkitVersion = BukkitVersion.v1_9_R2; // else if (version.contains("(MC: 1.10)") || version.contains("(MC: 1.10.1)") || version.contains("(MC: 1.10.2)")) // bukkitVersion = BukkitVersion.v1_10_R1; // else if (version.contains("(MC: 1.11)") || version.contains("(MC: 1.11.1)") || version.contains("(MC: 1.11.2)")) // bukkitVersion = BukkitVersion.v1_11_R1; // else if (version.contains("(MC: 1.12)") || version.contains("(MC: 1.12.1)") || version.contains("(MC: 1.12.2)")) // bukkitVersion = BukkitVersion.v1_12_R1; // else if (version.contains("(MC: 1.13)")) // bukkitVersion = BukkitVersion.v1_13_R1; // else if (version.contains("(MC: 1.13.1)") || version.contains("(MC: 1.13.2)")) // bukkitVersion = BukkitVersion.v1_13_R2; // else if (version.contains("(MC: 1.14)") || version.contains("(MC: 1.14.1)") || version.contains("(MC: 1.14.2)") || version.contains("(MC: 1.14.3)")) // bukkitVersion = BukkitVersion.v1_14_R1; // else if (version.contains("(MC: 1.14.4)")) // bukkitVersion = BukkitVersion.v1_14_R2; // else if (version.contains("(MC: 1.15)") || version.contains("(MC: 1.15.1)") || version.contains("(MC: 1.15.2)")) // bukkitVersion = BukkitVersion.v1_15_R1; // else if (version.contains("(MC: 1.16.1)")) // bukkitVersion = BukkitVersion.v1_16_R1; // else if (version.contains("(MC: 1.16.2)") || version.contains("(MC: 1.16.3)")) // bukkitVersion = BukkitVersion.v1_16_R2; // else if (version.contains("(MC: 1.16.4)") || version.contains("(MC: 1.16.5)")) // bukkitVersion = BukkitVersion.v1_16_R3; // else if (version.contains("(MC: 1.17)") || version.contains("(MC: 1.17.1)")) // bukkitVersion = BukkitVersion.v1_17_R1; // else // bukkitVersion = null; // } // // public static BukkitVersion getBukkitVersion() { // return bukkitVersion; // } // // public static boolean canHex() { // String[] split = Bukkit.getBukkitVersion().split("-")[0].split("\\."); // String minorVer = split[1]; // return Integer.parseInt(minorVer) >= 16; // } // // public enum BukkitVersion { // v1_8_R1, v1_8_R2, v1_8_R3, v1_9_R1, v1_9_R2, v1_10_R1, v1_11_R1, v1_12_R1, v1_13_R1, v1_13_R2, v1_14_R1, v1_14_R2, v1_15_R1, v1_16_R1, v1_16_R2, v1_16_R3, v1_17_R1 // } // // } // Path: src/main/java/com/nametagedit/plugin/utils/Utils.java import com.nametagedit.plugin.packets.VersionChecker; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; package com.nametagedit.plugin.utils; public class Utils { private static final Pattern hexPattern = Pattern.compile("&#([A-Fa-f0-9]{6})"); public static String format(String[] text, int to, int from) { return StringUtils.join(text, ' ', to, from).replace("'", ""); } public static String deformat(String input) { return ChatColor.stripColor(input); } public static String format(String input) { return format(input, false); } public static String format(String input, boolean limitChars) { String colored = color(input);
switch (VersionChecker.getBukkitVersion()) {
sgtcaze/NametagEdit
src/main/java/com/nametagedit/plugin/hooks/HookLibsDisguise.java
// Path: src/main/java/com/nametagedit/plugin/NametagEdit.java // @Getter // public class NametagEdit extends JavaPlugin { // // private static INametagApi api; // // private NametagHandler handler; // private NametagManager manager; // // public static INametagApi getApi() { // return api; // } // // @Override // public void onEnable() { // testCompat(); // if (!isEnabled()) return; // // manager = new NametagManager(this); // handler = new NametagHandler(this, manager); // // PluginManager pluginManager = Bukkit.getPluginManager(); // if (checkShouldRegister("zPermissions")) { // pluginManager.registerEvents(new HookZPermissions(handler), this); // } else if (checkShouldRegister("PermissionsEx")) { // pluginManager.registerEvents(new HookPermissionsEX(handler), this); // } else if (checkShouldRegister("GroupManager")) { // pluginManager.registerEvents(new HookGroupManager(handler), this); // } else if (checkShouldRegister("LuckPerms")) { // pluginManager.registerEvents(new HookLuckPerms(handler), this); // } // // if (pluginManager.getPlugin("LibsDisguises") != null) { // pluginManager.registerEvents(new HookLibsDisguise(this), this); // } // if (pluginManager.getPlugin("Guilds") != null) { // pluginManager.registerEvents(new HookGuilds(handler), this); // } // // getCommand("ne").setExecutor(new NametagCommand(handler)); // // if (api == null) { // api = new NametagAPI(handler, manager); // } // } // // @Override // public void onDisable() { // manager.reset(); // handler.getAbstractConfig().shutdown(); // } // // void debug(String message) { // if (handler != null && handler.debug()) { // getLogger().info("[DEBUG] " + message); // } // } // // private boolean checkShouldRegister(String plugin) { // if (Bukkit.getPluginManager().getPlugin(plugin) == null) return false; // getLogger().info("Found " + plugin + "! Hooking in."); // return true; // } // // private void testCompat() { // PacketWrapper wrapper = new PacketWrapper("TEST", "&f", "", 0, new ArrayList<>(), true); // wrapper.send(); // if (wrapper.error == null) return; // Bukkit.getPluginManager().disablePlugin(this); // getLogger().severe("\n------------------------------------------------------\n" + // "[WARNING] NametagEdit v" + getDescription().getVersion() + " Failed to load! [WARNING]" + // "\n------------------------------------------------------" + // "\nThis might be an issue with reflection. REPORT this:\n> " + // wrapper.error + // "\nThe plugin will now self destruct.\n------------------------------------------------------"); // } // // }
import com.nametagedit.plugin.NametagEdit; import lombok.AllArgsConstructor; import me.libraryaddict.disguise.events.DisguiseEvent; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.scheduler.BukkitRunnable;
package com.nametagedit.plugin.hooks; @AllArgsConstructor public class HookLibsDisguise implements Listener {
// Path: src/main/java/com/nametagedit/plugin/NametagEdit.java // @Getter // public class NametagEdit extends JavaPlugin { // // private static INametagApi api; // // private NametagHandler handler; // private NametagManager manager; // // public static INametagApi getApi() { // return api; // } // // @Override // public void onEnable() { // testCompat(); // if (!isEnabled()) return; // // manager = new NametagManager(this); // handler = new NametagHandler(this, manager); // // PluginManager pluginManager = Bukkit.getPluginManager(); // if (checkShouldRegister("zPermissions")) { // pluginManager.registerEvents(new HookZPermissions(handler), this); // } else if (checkShouldRegister("PermissionsEx")) { // pluginManager.registerEvents(new HookPermissionsEX(handler), this); // } else if (checkShouldRegister("GroupManager")) { // pluginManager.registerEvents(new HookGroupManager(handler), this); // } else if (checkShouldRegister("LuckPerms")) { // pluginManager.registerEvents(new HookLuckPerms(handler), this); // } // // if (pluginManager.getPlugin("LibsDisguises") != null) { // pluginManager.registerEvents(new HookLibsDisguise(this), this); // } // if (pluginManager.getPlugin("Guilds") != null) { // pluginManager.registerEvents(new HookGuilds(handler), this); // } // // getCommand("ne").setExecutor(new NametagCommand(handler)); // // if (api == null) { // api = new NametagAPI(handler, manager); // } // } // // @Override // public void onDisable() { // manager.reset(); // handler.getAbstractConfig().shutdown(); // } // // void debug(String message) { // if (handler != null && handler.debug()) { // getLogger().info("[DEBUG] " + message); // } // } // // private boolean checkShouldRegister(String plugin) { // if (Bukkit.getPluginManager().getPlugin(plugin) == null) return false; // getLogger().info("Found " + plugin + "! Hooking in."); // return true; // } // // private void testCompat() { // PacketWrapper wrapper = new PacketWrapper("TEST", "&f", "", 0, new ArrayList<>(), true); // wrapper.send(); // if (wrapper.error == null) return; // Bukkit.getPluginManager().disablePlugin(this); // getLogger().severe("\n------------------------------------------------------\n" + // "[WARNING] NametagEdit v" + getDescription().getVersion() + " Failed to load! [WARNING]" + // "\n------------------------------------------------------" + // "\nThis might be an issue with reflection. REPORT this:\n> " + // wrapper.error + // "\nThe plugin will now self destruct.\n------------------------------------------------------"); // } // // } // Path: src/main/java/com/nametagedit/plugin/hooks/HookLibsDisguise.java import com.nametagedit.plugin.NametagEdit; import lombok.AllArgsConstructor; import me.libraryaddict.disguise.events.DisguiseEvent; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.scheduler.BukkitRunnable; package com.nametagedit.plugin.hooks; @AllArgsConstructor public class HookLibsDisguise implements Listener {
private final NametagEdit plugin;
sgtcaze/NametagEdit
src/main/java/com/nametagedit/plugin/api/events/NametagFirstLoadedEvent.java
// Path: src/main/java/com/nametagedit/plugin/api/data/INametag.java // public interface INametag { // String getPrefix(); // // String getSuffix(); // // int getSortPriority(); // // boolean isPlayerTag(); // }
import com.nametagedit.plugin.api.data.INametag; import lombok.AllArgsConstructor; import lombok.Getter; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.HandlerList;
package com.nametagedit.plugin.api.events; /** * This class represents an Event that is fired when a * player joins the server and receives their nametag. */ @Getter @AllArgsConstructor public class NametagFirstLoadedEvent extends Event { private static final HandlerList HANDLERS = new HandlerList(); private final Player player;
// Path: src/main/java/com/nametagedit/plugin/api/data/INametag.java // public interface INametag { // String getPrefix(); // // String getSuffix(); // // int getSortPriority(); // // boolean isPlayerTag(); // } // Path: src/main/java/com/nametagedit/plugin/api/events/NametagFirstLoadedEvent.java import com.nametagedit.plugin.api.data.INametag; import lombok.AllArgsConstructor; import lombok.Getter; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; package com.nametagedit.plugin.api.events; /** * This class represents an Event that is fired when a * player joins the server and receives their nametag. */ @Getter @AllArgsConstructor public class NametagFirstLoadedEvent extends Event { private static final HandlerList HANDLERS = new HandlerList(); private final Player player;
private final INametag nametag;
sgtcaze/NametagEdit
src/main/java/com/nametagedit/plugin/storage/AbstractConfig.java
// Path: src/main/java/com/nametagedit/plugin/api/data/GroupData.java // @Data // @AllArgsConstructor // public class GroupData implements INametag { // // private String groupName; // private String prefix; // private String suffix; // private String permission; // private Permission bukkitPermission; // private int sortPriority; // // public GroupData() { // // } // // public void setPermission(String permission) { // this.permission = permission; // bukkitPermission = new Permission(permission, PermissionDefault.FALSE); // } // // @Override // public boolean isPlayerTag() { // return false; // } // // } // // Path: src/main/java/com/nametagedit/plugin/api/data/PlayerData.java // @Getter // @Setter // @AllArgsConstructor // public class PlayerData implements INametag { // // private String name; // private UUID uuid; // private String prefix; // private String suffix; // private int sortPriority; // // public PlayerData() { // // } // // public static PlayerData fromFile(String key, YamlConfiguration file) { // if (!file.contains("Players." + key)) return null; // PlayerData data = new PlayerData(); // data.setUuid(UUID.fromString(key)); // data.setName(file.getString("Players." + key + ".Name")); // data.setPrefix(file.getString("Players." + key + ".Prefix", "")); // data.setSuffix(file.getString("Players." + key + ".Suffix", "")); // data.setSortPriority(file.getInt("Players." + key + ".SortPriority", -1)); // return data; // } // // @Override // public boolean isPlayerTag() { // return true; // } // // }
import com.nametagedit.plugin.api.data.GroupData; import com.nametagedit.plugin.api.data.PlayerData; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.List; import java.util.UUID;
package com.nametagedit.plugin.storage; /** * This is responsible for abstracting * a database/flat file storage */ public interface AbstractConfig { void load(); void reload(); void shutdown(); void load(Player player, boolean loggedIn);
// Path: src/main/java/com/nametagedit/plugin/api/data/GroupData.java // @Data // @AllArgsConstructor // public class GroupData implements INametag { // // private String groupName; // private String prefix; // private String suffix; // private String permission; // private Permission bukkitPermission; // private int sortPriority; // // public GroupData() { // // } // // public void setPermission(String permission) { // this.permission = permission; // bukkitPermission = new Permission(permission, PermissionDefault.FALSE); // } // // @Override // public boolean isPlayerTag() { // return false; // } // // } // // Path: src/main/java/com/nametagedit/plugin/api/data/PlayerData.java // @Getter // @Setter // @AllArgsConstructor // public class PlayerData implements INametag { // // private String name; // private UUID uuid; // private String prefix; // private String suffix; // private int sortPriority; // // public PlayerData() { // // } // // public static PlayerData fromFile(String key, YamlConfiguration file) { // if (!file.contains("Players." + key)) return null; // PlayerData data = new PlayerData(); // data.setUuid(UUID.fromString(key)); // data.setName(file.getString("Players." + key + ".Name")); // data.setPrefix(file.getString("Players." + key + ".Prefix", "")); // data.setSuffix(file.getString("Players." + key + ".Suffix", "")); // data.setSortPriority(file.getInt("Players." + key + ".SortPriority", -1)); // return data; // } // // @Override // public boolean isPlayerTag() { // return true; // } // // } // Path: src/main/java/com/nametagedit/plugin/storage/AbstractConfig.java import com.nametagedit.plugin.api.data.GroupData; import com.nametagedit.plugin.api.data.PlayerData; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.List; import java.util.UUID; package com.nametagedit.plugin.storage; /** * This is responsible for abstracting * a database/flat file storage */ public interface AbstractConfig { void load(); void reload(); void shutdown(); void load(Player player, boolean loggedIn);
void save(PlayerData... playerData);
sgtcaze/NametagEdit
src/main/java/com/nametagedit/plugin/storage/AbstractConfig.java
// Path: src/main/java/com/nametagedit/plugin/api/data/GroupData.java // @Data // @AllArgsConstructor // public class GroupData implements INametag { // // private String groupName; // private String prefix; // private String suffix; // private String permission; // private Permission bukkitPermission; // private int sortPriority; // // public GroupData() { // // } // // public void setPermission(String permission) { // this.permission = permission; // bukkitPermission = new Permission(permission, PermissionDefault.FALSE); // } // // @Override // public boolean isPlayerTag() { // return false; // } // // } // // Path: src/main/java/com/nametagedit/plugin/api/data/PlayerData.java // @Getter // @Setter // @AllArgsConstructor // public class PlayerData implements INametag { // // private String name; // private UUID uuid; // private String prefix; // private String suffix; // private int sortPriority; // // public PlayerData() { // // } // // public static PlayerData fromFile(String key, YamlConfiguration file) { // if (!file.contains("Players." + key)) return null; // PlayerData data = new PlayerData(); // data.setUuid(UUID.fromString(key)); // data.setName(file.getString("Players." + key + ".Name")); // data.setPrefix(file.getString("Players." + key + ".Prefix", "")); // data.setSuffix(file.getString("Players." + key + ".Suffix", "")); // data.setSortPriority(file.getInt("Players." + key + ".SortPriority", -1)); // return data; // } // // @Override // public boolean isPlayerTag() { // return true; // } // // }
import com.nametagedit.plugin.api.data.GroupData; import com.nametagedit.plugin.api.data.PlayerData; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.List; import java.util.UUID;
package com.nametagedit.plugin.storage; /** * This is responsible for abstracting * a database/flat file storage */ public interface AbstractConfig { void load(); void reload(); void shutdown(); void load(Player player, boolean loggedIn); void save(PlayerData... playerData);
// Path: src/main/java/com/nametagedit/plugin/api/data/GroupData.java // @Data // @AllArgsConstructor // public class GroupData implements INametag { // // private String groupName; // private String prefix; // private String suffix; // private String permission; // private Permission bukkitPermission; // private int sortPriority; // // public GroupData() { // // } // // public void setPermission(String permission) { // this.permission = permission; // bukkitPermission = new Permission(permission, PermissionDefault.FALSE); // } // // @Override // public boolean isPlayerTag() { // return false; // } // // } // // Path: src/main/java/com/nametagedit/plugin/api/data/PlayerData.java // @Getter // @Setter // @AllArgsConstructor // public class PlayerData implements INametag { // // private String name; // private UUID uuid; // private String prefix; // private String suffix; // private int sortPriority; // // public PlayerData() { // // } // // public static PlayerData fromFile(String key, YamlConfiguration file) { // if (!file.contains("Players." + key)) return null; // PlayerData data = new PlayerData(); // data.setUuid(UUID.fromString(key)); // data.setName(file.getString("Players." + key + ".Name")); // data.setPrefix(file.getString("Players." + key + ".Prefix", "")); // data.setSuffix(file.getString("Players." + key + ".Suffix", "")); // data.setSortPriority(file.getInt("Players." + key + ".SortPriority", -1)); // return data; // } // // @Override // public boolean isPlayerTag() { // return true; // } // // } // Path: src/main/java/com/nametagedit/plugin/storage/AbstractConfig.java import com.nametagedit.plugin.api.data.GroupData; import com.nametagedit.plugin.api.data.PlayerData; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.List; import java.util.UUID; package com.nametagedit.plugin.storage; /** * This is responsible for abstracting * a database/flat file storage */ public interface AbstractConfig { void load(); void reload(); void shutdown(); void load(Player player, boolean loggedIn); void save(PlayerData... playerData);
void save(GroupData... groupData);
sgtcaze/NametagEdit
src/main/java/com/nametagedit/plugin/NametagMessages.java
// Path: src/main/java/com/nametagedit/plugin/utils/Utils.java // public class Utils { // // private static final Pattern hexPattern = Pattern.compile("&#([A-Fa-f0-9]{6})"); // // public static String format(String[] text, int to, int from) { // return StringUtils.join(text, ' ', to, from).replace("'", ""); // } // // public static String deformat(String input) { // return ChatColor.stripColor(input); // } // // public static String format(String input) { // return format(input, false); // } // // public static String format(String input, boolean limitChars) { // String colored = color(input); // // switch (VersionChecker.getBukkitVersion()) { // case v1_13_R1: case v1_14_R1: case v1_14_R2: case v1_15_R1: case v1_16_R1: // case v1_16_R2: case v1_16_R3: case v1_17_R1: // return limitChars && colored.length() > 256 ? colored.substring(0, 256) : colored; // default: // return limitChars && colored.length() > 16 ? colored.substring(0, 16) : colored; // } // } // // public static String color(String text) { // if (text == null) return ""; // // text = ChatColor.translateAlternateColorCodes('&', text); // // if (VersionChecker.canHex()) { // final char colorChar = ChatColor.COLOR_CHAR; // // final Matcher matcher = hexPattern.matcher(text); // final StringBuffer buffer = new StringBuffer(text.length() + 4 * 8); // // while (matcher.find()) { // final String group = matcher.group(1); // // matcher.appendReplacement(buffer, colorChar + "x" // + colorChar + group.charAt(0) + colorChar + group.charAt(1) // + colorChar + group.charAt(2) + colorChar + group.charAt(3) // + colorChar + group.charAt(4) + colorChar + group.charAt(5)); // } // // text = matcher.appendTail(buffer).toString(); // } // // return text; // } // // public static List<Player> getOnline() { // List<Player> list = new ArrayList<>(); // // for (World world : Bukkit.getWorlds()) { // list.addAll(world.getPlayers()); // } // // return Collections.unmodifiableList(list); // } // // public static YamlConfiguration getConfig(File file) { // try { // if (!file.exists()) { // file.createNewFile(); // } // } catch (IOException e) { // e.printStackTrace(); // } // // return YamlConfiguration.loadConfiguration(file); // } // // public static YamlConfiguration getConfig(File file, String resource, Plugin plugin) { // try { // if (!file.exists()) { // file.createNewFile(); // InputStream inputStream = plugin.getResource(resource); // OutputStream outputStream = new FileOutputStream(file); // byte[] buffer = new byte[1024]; // int bytesRead; // while ((bytesRead = inputStream.read(buffer)) != -1) { // outputStream.write(buffer, 0, bytesRead); // } // inputStream.close(); // outputStream.flush(); // outputStream.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // // return YamlConfiguration.loadConfiguration(file); // } // // public static String generateUUID() { // String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // StringBuilder builder = new StringBuilder(); // for (int i = 0; i < 5; i++) { // builder.append(chars.charAt((int) (Math.random() * chars.length()))); // } // return builder.toString(); // } // // }
import com.nametagedit.plugin.utils.Utils; import lombok.AllArgsConstructor; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender;
package com.nametagedit.plugin; @AllArgsConstructor public enum NametagMessages { SET_PRIORITY("Set sort priority to %s for %s"), CLEARED_TEAMS("Empty teams: %s. Purge: %s."), DEBUG_TOGGLED("NametagEdit debug has been %s"), LONG_TAGS("Long Nametags has been %s"), GROUP_EXISTS("The group %s already exists"), GROUP_VALUE_CLEARED("Cleared the %s for the group %s"), GROUP_EXISTS_NOT("The group %s does not exist!"), GROUP_VALUE("Changed %s's %s to %s"), USAGE_CONVERT("Usage: /nte convert <file/db> <file/db> <legacy (true/false)>"), GROUP_REMOVED("Successfully removed group %s"), MODIFY_OWN_TAG("You can only modify your own tag."), NO_PERMISSION("You do not have permission to use this."), RELOADED_DATA("Successfully reloaded plugin data"), FILE_DOESNT_EXIST("The file %s does not exist"), UUID_LOOKUP_FAILED("Could not find the uuid for %s"), CREATED_GROUP("Created group %s"), NOT_A_NUMBER("Uh-oh! %s does not appear to be a number!"), FILE_MISCONFIGURED("The file %s is not properly configured. Please read the configuration guide, otherwise conversion will fail."), CONVERSION("Attempting to convert %s from %s to %s. (Legacy: %s)"); private final String text; @Override public String toString() {
// Path: src/main/java/com/nametagedit/plugin/utils/Utils.java // public class Utils { // // private static final Pattern hexPattern = Pattern.compile("&#([A-Fa-f0-9]{6})"); // // public static String format(String[] text, int to, int from) { // return StringUtils.join(text, ' ', to, from).replace("'", ""); // } // // public static String deformat(String input) { // return ChatColor.stripColor(input); // } // // public static String format(String input) { // return format(input, false); // } // // public static String format(String input, boolean limitChars) { // String colored = color(input); // // switch (VersionChecker.getBukkitVersion()) { // case v1_13_R1: case v1_14_R1: case v1_14_R2: case v1_15_R1: case v1_16_R1: // case v1_16_R2: case v1_16_R3: case v1_17_R1: // return limitChars && colored.length() > 256 ? colored.substring(0, 256) : colored; // default: // return limitChars && colored.length() > 16 ? colored.substring(0, 16) : colored; // } // } // // public static String color(String text) { // if (text == null) return ""; // // text = ChatColor.translateAlternateColorCodes('&', text); // // if (VersionChecker.canHex()) { // final char colorChar = ChatColor.COLOR_CHAR; // // final Matcher matcher = hexPattern.matcher(text); // final StringBuffer buffer = new StringBuffer(text.length() + 4 * 8); // // while (matcher.find()) { // final String group = matcher.group(1); // // matcher.appendReplacement(buffer, colorChar + "x" // + colorChar + group.charAt(0) + colorChar + group.charAt(1) // + colorChar + group.charAt(2) + colorChar + group.charAt(3) // + colorChar + group.charAt(4) + colorChar + group.charAt(5)); // } // // text = matcher.appendTail(buffer).toString(); // } // // return text; // } // // public static List<Player> getOnline() { // List<Player> list = new ArrayList<>(); // // for (World world : Bukkit.getWorlds()) { // list.addAll(world.getPlayers()); // } // // return Collections.unmodifiableList(list); // } // // public static YamlConfiguration getConfig(File file) { // try { // if (!file.exists()) { // file.createNewFile(); // } // } catch (IOException e) { // e.printStackTrace(); // } // // return YamlConfiguration.loadConfiguration(file); // } // // public static YamlConfiguration getConfig(File file, String resource, Plugin plugin) { // try { // if (!file.exists()) { // file.createNewFile(); // InputStream inputStream = plugin.getResource(resource); // OutputStream outputStream = new FileOutputStream(file); // byte[] buffer = new byte[1024]; // int bytesRead; // while ((bytesRead = inputStream.read(buffer)) != -1) { // outputStream.write(buffer, 0, bytesRead); // } // inputStream.close(); // outputStream.flush(); // outputStream.close(); // } // } catch (IOException e) { // e.printStackTrace(); // } // // return YamlConfiguration.loadConfiguration(file); // } // // public static String generateUUID() { // String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // StringBuilder builder = new StringBuilder(); // for (int i = 0; i < 5; i++) { // builder.append(chars.charAt((int) (Math.random() * chars.length()))); // } // return builder.toString(); // } // // } // Path: src/main/java/com/nametagedit/plugin/NametagMessages.java import com.nametagedit.plugin.utils.Utils; import lombok.AllArgsConstructor; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; package com.nametagedit.plugin; @AllArgsConstructor public enum NametagMessages { SET_PRIORITY("Set sort priority to %s for %s"), CLEARED_TEAMS("Empty teams: %s. Purge: %s."), DEBUG_TOGGLED("NametagEdit debug has been %s"), LONG_TAGS("Long Nametags has been %s"), GROUP_EXISTS("The group %s already exists"), GROUP_VALUE_CLEARED("Cleared the %s for the group %s"), GROUP_EXISTS_NOT("The group %s does not exist!"), GROUP_VALUE("Changed %s's %s to %s"), USAGE_CONVERT("Usage: /nte convert <file/db> <file/db> <legacy (true/false)>"), GROUP_REMOVED("Successfully removed group %s"), MODIFY_OWN_TAG("You can only modify your own tag."), NO_PERMISSION("You do not have permission to use this."), RELOADED_DATA("Successfully reloaded plugin data"), FILE_DOESNT_EXIST("The file %s does not exist"), UUID_LOOKUP_FAILED("Could not find the uuid for %s"), CREATED_GROUP("Created group %s"), NOT_A_NUMBER("Uh-oh! %s does not appear to be a number!"), FILE_MISCONFIGURED("The file %s is not properly configured. Please read the configuration guide, otherwise conversion will fail."), CONVERSION("Attempting to convert %s from %s to %s. (Legacy: %s)"); private final String text; @Override public String toString() {
return Utils.color("&8» &a" + text);
sgtcaze/NametagEdit
src/main/java/com/nametagedit/plugin/storage/database/tasks/GroupConfigUpdater.java
// Path: src/main/java/com/nametagedit/plugin/storage/database/DatabaseConfig.java // public class DatabaseConfig implements AbstractConfig { // // private NametagEdit plugin; // private NametagHandler handler; // private HikariDataSource hikari; // // // These are used if the user wants to customize the // // schema structure. Perhaps more cosmetic. // public static String TABLE_GROUPS; // public static String TABLE_PLAYERS; // public static String TABLE_CONFIG; // // public DatabaseConfig(NametagEdit plugin, NametagHandler handler, Configuration config) { // this.plugin = plugin; // this.handler = handler; // TABLE_GROUPS = "`" + config.getString("MySQL.GroupsTable", "nte_groups") + "`"; // TABLE_PLAYERS = "`" + config.getString("MySQL.PlayersTable", "nte_players") + "`"; // TABLE_CONFIG = "`" + config.getString("MySQL.ConfigTable", "nte_config") + "`"; // } // // @Override // public void load() { // FileConfiguration config = handler.getConfig(); // shutdown(); // hikari = new HikariDataSource(); // hikari.setMaximumPoolSize(config.getInt("MinimumPoolSize", 10)); // hikari.setPoolName("NametagEdit Pool"); // // String port = "3306"; // // if (config.isSet("MySQL.Port")) { // port = config.getString("MySQL.Port"); // } // // hikari.setJdbcUrl("jdbc:mysql://" + config.getString("MySQL.Hostname") + ":" + port + "/" + config.getString("MySQL.Database")); // hikari.addDataSourceProperty("useSSL", false); // hikari.addDataSourceProperty("requireSSL", false); // hikari.addDataSourceProperty("verifyServerCertificate", false); // hikari.addDataSourceProperty("user", config.getString("MySQL.Username")); // hikari.addDataSourceProperty("password", config.getString("MySQL.Password")); // // hikari.setUsername(config.getString("MySQL.Username")); // hikari.setPassword(config.getString("MySQL.Password")); // // new DatabaseUpdater(handler, hikari, plugin).runTaskAsynchronously(plugin); // } // // @Override // public void reload() { // new DataDownloader(handler, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void shutdown() { // if (hikari != null) { // hikari.close(); // } // } // // @Override // public void load(Player player, boolean loggedIn) { // new PlayerLoader(player.getUniqueId(), plugin, handler, hikari, loggedIn).runTaskAsynchronously(plugin); // } // // @Override // public void save(PlayerData... playerData) { // new PlayerSaver(playerData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void save(GroupData... groupData) { // new GroupSaver(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void savePriority(boolean playerTag, String key, final int priority) { // if (playerTag) { // UUIDFetcher.lookupUUID(key, plugin, uuid -> { // if (uuid != null) { // new PlayerPriority(uuid, priority, hikari).runTaskAsynchronously(plugin); // } else { // plugin.getLogger().severe("An error has occurred while looking for UUID."); // } // }); // } else { // new GroupPriority(key, priority, hikari).runTaskAsynchronously(plugin); // } // } // // @Override // public void delete(GroupData groupData) { // new GroupDeleter(groupData.getGroupName(), hikari).runTaskAsynchronously(plugin); // } // // @Override // public void add(GroupData groupData) { // new GroupAdd(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void clear(UUID uuid, String targetName) { // new PlayerDeleter(uuid, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void orderGroups(CommandSender commandSender, List<String> order) { // String formatted = Arrays.toString(order.toArray()); // formatted = formatted.substring(1, formatted.length() - 1).replace(",", ""); // new GroupConfigUpdater("order", formatted, hikari).runTaskAsynchronously(handler.getPlugin()); // } // // }
import com.nametagedit.plugin.storage.database.DatabaseConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.AllArgsConstructor; import org.bukkit.scheduler.BukkitRunnable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException;
package com.nametagedit.plugin.storage.database.tasks; @AllArgsConstructor public class GroupConfigUpdater extends BukkitRunnable { private final String setting; private final String value; private final HikariDataSource hikari; @Override public void run() { try (Connection connection = hikari.getConnection()) {
// Path: src/main/java/com/nametagedit/plugin/storage/database/DatabaseConfig.java // public class DatabaseConfig implements AbstractConfig { // // private NametagEdit plugin; // private NametagHandler handler; // private HikariDataSource hikari; // // // These are used if the user wants to customize the // // schema structure. Perhaps more cosmetic. // public static String TABLE_GROUPS; // public static String TABLE_PLAYERS; // public static String TABLE_CONFIG; // // public DatabaseConfig(NametagEdit plugin, NametagHandler handler, Configuration config) { // this.plugin = plugin; // this.handler = handler; // TABLE_GROUPS = "`" + config.getString("MySQL.GroupsTable", "nte_groups") + "`"; // TABLE_PLAYERS = "`" + config.getString("MySQL.PlayersTable", "nte_players") + "`"; // TABLE_CONFIG = "`" + config.getString("MySQL.ConfigTable", "nte_config") + "`"; // } // // @Override // public void load() { // FileConfiguration config = handler.getConfig(); // shutdown(); // hikari = new HikariDataSource(); // hikari.setMaximumPoolSize(config.getInt("MinimumPoolSize", 10)); // hikari.setPoolName("NametagEdit Pool"); // // String port = "3306"; // // if (config.isSet("MySQL.Port")) { // port = config.getString("MySQL.Port"); // } // // hikari.setJdbcUrl("jdbc:mysql://" + config.getString("MySQL.Hostname") + ":" + port + "/" + config.getString("MySQL.Database")); // hikari.addDataSourceProperty("useSSL", false); // hikari.addDataSourceProperty("requireSSL", false); // hikari.addDataSourceProperty("verifyServerCertificate", false); // hikari.addDataSourceProperty("user", config.getString("MySQL.Username")); // hikari.addDataSourceProperty("password", config.getString("MySQL.Password")); // // hikari.setUsername(config.getString("MySQL.Username")); // hikari.setPassword(config.getString("MySQL.Password")); // // new DatabaseUpdater(handler, hikari, plugin).runTaskAsynchronously(plugin); // } // // @Override // public void reload() { // new DataDownloader(handler, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void shutdown() { // if (hikari != null) { // hikari.close(); // } // } // // @Override // public void load(Player player, boolean loggedIn) { // new PlayerLoader(player.getUniqueId(), plugin, handler, hikari, loggedIn).runTaskAsynchronously(plugin); // } // // @Override // public void save(PlayerData... playerData) { // new PlayerSaver(playerData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void save(GroupData... groupData) { // new GroupSaver(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void savePriority(boolean playerTag, String key, final int priority) { // if (playerTag) { // UUIDFetcher.lookupUUID(key, plugin, uuid -> { // if (uuid != null) { // new PlayerPriority(uuid, priority, hikari).runTaskAsynchronously(plugin); // } else { // plugin.getLogger().severe("An error has occurred while looking for UUID."); // } // }); // } else { // new GroupPriority(key, priority, hikari).runTaskAsynchronously(plugin); // } // } // // @Override // public void delete(GroupData groupData) { // new GroupDeleter(groupData.getGroupName(), hikari).runTaskAsynchronously(plugin); // } // // @Override // public void add(GroupData groupData) { // new GroupAdd(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void clear(UUID uuid, String targetName) { // new PlayerDeleter(uuid, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void orderGroups(CommandSender commandSender, List<String> order) { // String formatted = Arrays.toString(order.toArray()); // formatted = formatted.substring(1, formatted.length() - 1).replace(",", ""); // new GroupConfigUpdater("order", formatted, hikari).runTaskAsynchronously(handler.getPlugin()); // } // // } // Path: src/main/java/com/nametagedit/plugin/storage/database/tasks/GroupConfigUpdater.java import com.nametagedit.plugin.storage.database.DatabaseConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.AllArgsConstructor; import org.bukkit.scheduler.BukkitRunnable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; package com.nametagedit.plugin.storage.database.tasks; @AllArgsConstructor public class GroupConfigUpdater extends BukkitRunnable { private final String setting; private final String value; private final HikariDataSource hikari; @Override public void run() { try (Connection connection = hikari.getConnection()) {
final String QUERY = "INSERT INTO " + DatabaseConfig.TABLE_GROUPS + " VALUES(?, ?) ON DUPLICATE KEY UPDATE `value`=?";
sgtcaze/NametagEdit
src/main/java/com/nametagedit/plugin/api/INametagApi.java
// Path: src/main/java/com/nametagedit/plugin/api/data/FakeTeam.java // @Data // public class FakeTeam { // // // Because some networks use NametagEdit on multiple servers, we may have clashes // // with the same Team names. The UNIQUE_ID ensures there will be no clashing. // private static final String UNIQUE_ID = Utils.generateUUID(); // // This represents the number of FakeTeams that have been created. // // It is used to generate a unique Team name. // private static int ID = 0; // private final ArrayList<String> members = new ArrayList<>(); // private String name; // private String prefix; // private String suffix; // private boolean visible = true; // // public FakeTeam(String prefix, String suffix, int sortPriority, boolean playerTag) { // this.name = UNIQUE_ID + "_" + getNameFromInput(sortPriority) + ++ID + (playerTag ? "+P" : ""); // // switch (VersionChecker.getBukkitVersion()) { // case v1_13_R1: case v1_14_R1: case v1_14_R2: case v1_15_R1: case v1_16_R1: // case v1_16_R2: case v1_16_R3: case v1_17_R1: // this.name = this.name.length() > 256 ? this.name.substring(0, 256) : this.name; // default: // this.name = this.name.length() > 16 ? this.name.substring(0, 16) : this.name; // } // // this.prefix = prefix; // this.suffix = suffix; // // } // // public void addMember(String player) { // if (!members.contains(player)) { // members.add(player); // } // } // // public boolean isSimilar(String prefix, String suffix, boolean visible) { // return this.prefix.equals(prefix) && this.suffix.equals(suffix) && this.visible == visible; // } // // /** // * This is a special method to sort nametags in // * the tablist. It takes a priority and converts // * it to an alphabetic representation to force a // * specific sort. // * // * @param input the sort priority // * @return the team name // */ // private String getNameFromInput(int input) { // if (input < 0) return "Z"; // char letter = (char) ((input / 5) + 65); // int repeat = input % 5 + 1; // StringBuilder builder = new StringBuilder(); // for (int i = 0; i < repeat; i++) { // builder.append(letter); // } // return builder.toString(); // } // // } // // Path: src/main/java/com/nametagedit/plugin/api/data/GroupData.java // @Data // @AllArgsConstructor // public class GroupData implements INametag { // // private String groupName; // private String prefix; // private String suffix; // private String permission; // private Permission bukkitPermission; // private int sortPriority; // // public GroupData() { // // } // // public void setPermission(String permission) { // this.permission = permission; // bukkitPermission = new Permission(permission, PermissionDefault.FALSE); // } // // @Override // public boolean isPlayerTag() { // return false; // } // // } // // Path: src/main/java/com/nametagedit/plugin/api/data/Nametag.java // @Getter // @Setter // @AllArgsConstructor // public class Nametag { // private String prefix; // private String suffix; // }
import com.nametagedit.plugin.api.data.FakeTeam; import com.nametagedit.plugin.api.data.GroupData; import com.nametagedit.plugin.api.data.Nametag; import org.bukkit.entity.Player; import java.util.List;
package com.nametagedit.plugin.api; /** * */ public interface INametagApi { /** * Function gets the fake team data for * player. * * @param player the player to check * @return the fake team */ FakeTeam getFakeTeam(Player player); /** * Function gets the nametag for a player if * it exists. This will never return a null. * * @param player the player to check * @return the nametag for the player */
// Path: src/main/java/com/nametagedit/plugin/api/data/FakeTeam.java // @Data // public class FakeTeam { // // // Because some networks use NametagEdit on multiple servers, we may have clashes // // with the same Team names. The UNIQUE_ID ensures there will be no clashing. // private static final String UNIQUE_ID = Utils.generateUUID(); // // This represents the number of FakeTeams that have been created. // // It is used to generate a unique Team name. // private static int ID = 0; // private final ArrayList<String> members = new ArrayList<>(); // private String name; // private String prefix; // private String suffix; // private boolean visible = true; // // public FakeTeam(String prefix, String suffix, int sortPriority, boolean playerTag) { // this.name = UNIQUE_ID + "_" + getNameFromInput(sortPriority) + ++ID + (playerTag ? "+P" : ""); // // switch (VersionChecker.getBukkitVersion()) { // case v1_13_R1: case v1_14_R1: case v1_14_R2: case v1_15_R1: case v1_16_R1: // case v1_16_R2: case v1_16_R3: case v1_17_R1: // this.name = this.name.length() > 256 ? this.name.substring(0, 256) : this.name; // default: // this.name = this.name.length() > 16 ? this.name.substring(0, 16) : this.name; // } // // this.prefix = prefix; // this.suffix = suffix; // // } // // public void addMember(String player) { // if (!members.contains(player)) { // members.add(player); // } // } // // public boolean isSimilar(String prefix, String suffix, boolean visible) { // return this.prefix.equals(prefix) && this.suffix.equals(suffix) && this.visible == visible; // } // // /** // * This is a special method to sort nametags in // * the tablist. It takes a priority and converts // * it to an alphabetic representation to force a // * specific sort. // * // * @param input the sort priority // * @return the team name // */ // private String getNameFromInput(int input) { // if (input < 0) return "Z"; // char letter = (char) ((input / 5) + 65); // int repeat = input % 5 + 1; // StringBuilder builder = new StringBuilder(); // for (int i = 0; i < repeat; i++) { // builder.append(letter); // } // return builder.toString(); // } // // } // // Path: src/main/java/com/nametagedit/plugin/api/data/GroupData.java // @Data // @AllArgsConstructor // public class GroupData implements INametag { // // private String groupName; // private String prefix; // private String suffix; // private String permission; // private Permission bukkitPermission; // private int sortPriority; // // public GroupData() { // // } // // public void setPermission(String permission) { // this.permission = permission; // bukkitPermission = new Permission(permission, PermissionDefault.FALSE); // } // // @Override // public boolean isPlayerTag() { // return false; // } // // } // // Path: src/main/java/com/nametagedit/plugin/api/data/Nametag.java // @Getter // @Setter // @AllArgsConstructor // public class Nametag { // private String prefix; // private String suffix; // } // Path: src/main/java/com/nametagedit/plugin/api/INametagApi.java import com.nametagedit.plugin.api.data.FakeTeam; import com.nametagedit.plugin.api.data.GroupData; import com.nametagedit.plugin.api.data.Nametag; import org.bukkit.entity.Player; import java.util.List; package com.nametagedit.plugin.api; /** * */ public interface INametagApi { /** * Function gets the fake team data for * player. * * @param player the player to check * @return the fake team */ FakeTeam getFakeTeam(Player player); /** * Function gets the nametag for a player if * it exists. This will never return a null. * * @param player the player to check * @return the nametag for the player */
Nametag getNametag(Player player);
sgtcaze/NametagEdit
src/main/java/com/nametagedit/plugin/api/events/NametagEvent.java
// Path: src/main/java/com/nametagedit/plugin/api/data/Nametag.java // @Getter // @Setter // @AllArgsConstructor // public class Nametag { // private String prefix; // private String suffix; // }
import com.nametagedit.plugin.api.data.Nametag; import lombok.Getter; import lombok.Setter; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList;
package com.nametagedit.plugin.api.events; /** * This class represents an Event that is fired when a * nametag is changed. */ public class NametagEvent extends Event implements Cancellable { private static final HandlerList HANDLERS = new HandlerList(); private boolean cancelled; @Getter @Setter @Deprecated private String value; @Getter @Setter
// Path: src/main/java/com/nametagedit/plugin/api/data/Nametag.java // @Getter // @Setter // @AllArgsConstructor // public class Nametag { // private String prefix; // private String suffix; // } // Path: src/main/java/com/nametagedit/plugin/api/events/NametagEvent.java import com.nametagedit.plugin.api.data.Nametag; import lombok.Getter; import lombok.Setter; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; package com.nametagedit.plugin.api.events; /** * This class represents an Event that is fired when a * nametag is changed. */ public class NametagEvent extends Event implements Cancellable { private static final HandlerList HANDLERS = new HandlerList(); private boolean cancelled; @Getter @Setter @Deprecated private String value; @Getter @Setter
private Nametag nametag;
sgtcaze/NametagEdit
src/main/java/com/nametagedit/plugin/storage/database/tasks/GroupDeleter.java
// Path: src/main/java/com/nametagedit/plugin/storage/database/DatabaseConfig.java // public class DatabaseConfig implements AbstractConfig { // // private NametagEdit plugin; // private NametagHandler handler; // private HikariDataSource hikari; // // // These are used if the user wants to customize the // // schema structure. Perhaps more cosmetic. // public static String TABLE_GROUPS; // public static String TABLE_PLAYERS; // public static String TABLE_CONFIG; // // public DatabaseConfig(NametagEdit plugin, NametagHandler handler, Configuration config) { // this.plugin = plugin; // this.handler = handler; // TABLE_GROUPS = "`" + config.getString("MySQL.GroupsTable", "nte_groups") + "`"; // TABLE_PLAYERS = "`" + config.getString("MySQL.PlayersTable", "nte_players") + "`"; // TABLE_CONFIG = "`" + config.getString("MySQL.ConfigTable", "nte_config") + "`"; // } // // @Override // public void load() { // FileConfiguration config = handler.getConfig(); // shutdown(); // hikari = new HikariDataSource(); // hikari.setMaximumPoolSize(config.getInt("MinimumPoolSize", 10)); // hikari.setPoolName("NametagEdit Pool"); // // String port = "3306"; // // if (config.isSet("MySQL.Port")) { // port = config.getString("MySQL.Port"); // } // // hikari.setJdbcUrl("jdbc:mysql://" + config.getString("MySQL.Hostname") + ":" + port + "/" + config.getString("MySQL.Database")); // hikari.addDataSourceProperty("useSSL", false); // hikari.addDataSourceProperty("requireSSL", false); // hikari.addDataSourceProperty("verifyServerCertificate", false); // hikari.addDataSourceProperty("user", config.getString("MySQL.Username")); // hikari.addDataSourceProperty("password", config.getString("MySQL.Password")); // // hikari.setUsername(config.getString("MySQL.Username")); // hikari.setPassword(config.getString("MySQL.Password")); // // new DatabaseUpdater(handler, hikari, plugin).runTaskAsynchronously(plugin); // } // // @Override // public void reload() { // new DataDownloader(handler, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void shutdown() { // if (hikari != null) { // hikari.close(); // } // } // // @Override // public void load(Player player, boolean loggedIn) { // new PlayerLoader(player.getUniqueId(), plugin, handler, hikari, loggedIn).runTaskAsynchronously(plugin); // } // // @Override // public void save(PlayerData... playerData) { // new PlayerSaver(playerData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void save(GroupData... groupData) { // new GroupSaver(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void savePriority(boolean playerTag, String key, final int priority) { // if (playerTag) { // UUIDFetcher.lookupUUID(key, plugin, uuid -> { // if (uuid != null) { // new PlayerPriority(uuid, priority, hikari).runTaskAsynchronously(plugin); // } else { // plugin.getLogger().severe("An error has occurred while looking for UUID."); // } // }); // } else { // new GroupPriority(key, priority, hikari).runTaskAsynchronously(plugin); // } // } // // @Override // public void delete(GroupData groupData) { // new GroupDeleter(groupData.getGroupName(), hikari).runTaskAsynchronously(plugin); // } // // @Override // public void add(GroupData groupData) { // new GroupAdd(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void clear(UUID uuid, String targetName) { // new PlayerDeleter(uuid, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void orderGroups(CommandSender commandSender, List<String> order) { // String formatted = Arrays.toString(order.toArray()); // formatted = formatted.substring(1, formatted.length() - 1).replace(",", ""); // new GroupConfigUpdater("order", formatted, hikari).runTaskAsynchronously(handler.getPlugin()); // } // // }
import com.nametagedit.plugin.storage.database.DatabaseConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.AllArgsConstructor; import org.bukkit.scheduler.BukkitRunnable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException;
package com.nametagedit.plugin.storage.database.tasks; @AllArgsConstructor public class GroupDeleter extends BukkitRunnable { private final String groupName; private final HikariDataSource hikari; @Override public void run() { try (Connection connection = hikari.getConnection()) {
// Path: src/main/java/com/nametagedit/plugin/storage/database/DatabaseConfig.java // public class DatabaseConfig implements AbstractConfig { // // private NametagEdit plugin; // private NametagHandler handler; // private HikariDataSource hikari; // // // These are used if the user wants to customize the // // schema structure. Perhaps more cosmetic. // public static String TABLE_GROUPS; // public static String TABLE_PLAYERS; // public static String TABLE_CONFIG; // // public DatabaseConfig(NametagEdit plugin, NametagHandler handler, Configuration config) { // this.plugin = plugin; // this.handler = handler; // TABLE_GROUPS = "`" + config.getString("MySQL.GroupsTable", "nte_groups") + "`"; // TABLE_PLAYERS = "`" + config.getString("MySQL.PlayersTable", "nte_players") + "`"; // TABLE_CONFIG = "`" + config.getString("MySQL.ConfigTable", "nte_config") + "`"; // } // // @Override // public void load() { // FileConfiguration config = handler.getConfig(); // shutdown(); // hikari = new HikariDataSource(); // hikari.setMaximumPoolSize(config.getInt("MinimumPoolSize", 10)); // hikari.setPoolName("NametagEdit Pool"); // // String port = "3306"; // // if (config.isSet("MySQL.Port")) { // port = config.getString("MySQL.Port"); // } // // hikari.setJdbcUrl("jdbc:mysql://" + config.getString("MySQL.Hostname") + ":" + port + "/" + config.getString("MySQL.Database")); // hikari.addDataSourceProperty("useSSL", false); // hikari.addDataSourceProperty("requireSSL", false); // hikari.addDataSourceProperty("verifyServerCertificate", false); // hikari.addDataSourceProperty("user", config.getString("MySQL.Username")); // hikari.addDataSourceProperty("password", config.getString("MySQL.Password")); // // hikari.setUsername(config.getString("MySQL.Username")); // hikari.setPassword(config.getString("MySQL.Password")); // // new DatabaseUpdater(handler, hikari, plugin).runTaskAsynchronously(plugin); // } // // @Override // public void reload() { // new DataDownloader(handler, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void shutdown() { // if (hikari != null) { // hikari.close(); // } // } // // @Override // public void load(Player player, boolean loggedIn) { // new PlayerLoader(player.getUniqueId(), plugin, handler, hikari, loggedIn).runTaskAsynchronously(plugin); // } // // @Override // public void save(PlayerData... playerData) { // new PlayerSaver(playerData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void save(GroupData... groupData) { // new GroupSaver(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void savePriority(boolean playerTag, String key, final int priority) { // if (playerTag) { // UUIDFetcher.lookupUUID(key, plugin, uuid -> { // if (uuid != null) { // new PlayerPriority(uuid, priority, hikari).runTaskAsynchronously(plugin); // } else { // plugin.getLogger().severe("An error has occurred while looking for UUID."); // } // }); // } else { // new GroupPriority(key, priority, hikari).runTaskAsynchronously(plugin); // } // } // // @Override // public void delete(GroupData groupData) { // new GroupDeleter(groupData.getGroupName(), hikari).runTaskAsynchronously(plugin); // } // // @Override // public void add(GroupData groupData) { // new GroupAdd(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void clear(UUID uuid, String targetName) { // new PlayerDeleter(uuid, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void orderGroups(CommandSender commandSender, List<String> order) { // String formatted = Arrays.toString(order.toArray()); // formatted = formatted.substring(1, formatted.length() - 1).replace(",", ""); // new GroupConfigUpdater("order", formatted, hikari).runTaskAsynchronously(handler.getPlugin()); // } // // } // Path: src/main/java/com/nametagedit/plugin/storage/database/tasks/GroupDeleter.java import com.nametagedit.plugin.storage.database.DatabaseConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.AllArgsConstructor; import org.bukkit.scheduler.BukkitRunnable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; package com.nametagedit.plugin.storage.database.tasks; @AllArgsConstructor public class GroupDeleter extends BukkitRunnable { private final String groupName; private final HikariDataSource hikari; @Override public void run() { try (Connection connection = hikari.getConnection()) {
final String QUERY = "DELETE FROM " + DatabaseConfig.TABLE_GROUPS + " WHERE `name`=?";
sgtcaze/NametagEdit
src/main/java/com/nametagedit/plugin/storage/database/tasks/PlayerDeleter.java
// Path: src/main/java/com/nametagedit/plugin/storage/database/DatabaseConfig.java // public class DatabaseConfig implements AbstractConfig { // // private NametagEdit plugin; // private NametagHandler handler; // private HikariDataSource hikari; // // // These are used if the user wants to customize the // // schema structure. Perhaps more cosmetic. // public static String TABLE_GROUPS; // public static String TABLE_PLAYERS; // public static String TABLE_CONFIG; // // public DatabaseConfig(NametagEdit plugin, NametagHandler handler, Configuration config) { // this.plugin = plugin; // this.handler = handler; // TABLE_GROUPS = "`" + config.getString("MySQL.GroupsTable", "nte_groups") + "`"; // TABLE_PLAYERS = "`" + config.getString("MySQL.PlayersTable", "nte_players") + "`"; // TABLE_CONFIG = "`" + config.getString("MySQL.ConfigTable", "nte_config") + "`"; // } // // @Override // public void load() { // FileConfiguration config = handler.getConfig(); // shutdown(); // hikari = new HikariDataSource(); // hikari.setMaximumPoolSize(config.getInt("MinimumPoolSize", 10)); // hikari.setPoolName("NametagEdit Pool"); // // String port = "3306"; // // if (config.isSet("MySQL.Port")) { // port = config.getString("MySQL.Port"); // } // // hikari.setJdbcUrl("jdbc:mysql://" + config.getString("MySQL.Hostname") + ":" + port + "/" + config.getString("MySQL.Database")); // hikari.addDataSourceProperty("useSSL", false); // hikari.addDataSourceProperty("requireSSL", false); // hikari.addDataSourceProperty("verifyServerCertificate", false); // hikari.addDataSourceProperty("user", config.getString("MySQL.Username")); // hikari.addDataSourceProperty("password", config.getString("MySQL.Password")); // // hikari.setUsername(config.getString("MySQL.Username")); // hikari.setPassword(config.getString("MySQL.Password")); // // new DatabaseUpdater(handler, hikari, plugin).runTaskAsynchronously(plugin); // } // // @Override // public void reload() { // new DataDownloader(handler, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void shutdown() { // if (hikari != null) { // hikari.close(); // } // } // // @Override // public void load(Player player, boolean loggedIn) { // new PlayerLoader(player.getUniqueId(), plugin, handler, hikari, loggedIn).runTaskAsynchronously(plugin); // } // // @Override // public void save(PlayerData... playerData) { // new PlayerSaver(playerData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void save(GroupData... groupData) { // new GroupSaver(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void savePriority(boolean playerTag, String key, final int priority) { // if (playerTag) { // UUIDFetcher.lookupUUID(key, plugin, uuid -> { // if (uuid != null) { // new PlayerPriority(uuid, priority, hikari).runTaskAsynchronously(plugin); // } else { // plugin.getLogger().severe("An error has occurred while looking for UUID."); // } // }); // } else { // new GroupPriority(key, priority, hikari).runTaskAsynchronously(plugin); // } // } // // @Override // public void delete(GroupData groupData) { // new GroupDeleter(groupData.getGroupName(), hikari).runTaskAsynchronously(plugin); // } // // @Override // public void add(GroupData groupData) { // new GroupAdd(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void clear(UUID uuid, String targetName) { // new PlayerDeleter(uuid, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void orderGroups(CommandSender commandSender, List<String> order) { // String formatted = Arrays.toString(order.toArray()); // formatted = formatted.substring(1, formatted.length() - 1).replace(",", ""); // new GroupConfigUpdater("order", formatted, hikari).runTaskAsynchronously(handler.getPlugin()); // } // // }
import com.nametagedit.plugin.storage.database.DatabaseConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.AllArgsConstructor; import org.bukkit.scheduler.BukkitRunnable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.UUID;
package com.nametagedit.plugin.storage.database.tasks; @AllArgsConstructor public class PlayerDeleter extends BukkitRunnable { private final UUID uuid; private final HikariDataSource hikari; @Override public void run() { try (Connection connection = hikari.getConnection()) {
// Path: src/main/java/com/nametagedit/plugin/storage/database/DatabaseConfig.java // public class DatabaseConfig implements AbstractConfig { // // private NametagEdit plugin; // private NametagHandler handler; // private HikariDataSource hikari; // // // These are used if the user wants to customize the // // schema structure. Perhaps more cosmetic. // public static String TABLE_GROUPS; // public static String TABLE_PLAYERS; // public static String TABLE_CONFIG; // // public DatabaseConfig(NametagEdit plugin, NametagHandler handler, Configuration config) { // this.plugin = plugin; // this.handler = handler; // TABLE_GROUPS = "`" + config.getString("MySQL.GroupsTable", "nte_groups") + "`"; // TABLE_PLAYERS = "`" + config.getString("MySQL.PlayersTable", "nte_players") + "`"; // TABLE_CONFIG = "`" + config.getString("MySQL.ConfigTable", "nte_config") + "`"; // } // // @Override // public void load() { // FileConfiguration config = handler.getConfig(); // shutdown(); // hikari = new HikariDataSource(); // hikari.setMaximumPoolSize(config.getInt("MinimumPoolSize", 10)); // hikari.setPoolName("NametagEdit Pool"); // // String port = "3306"; // // if (config.isSet("MySQL.Port")) { // port = config.getString("MySQL.Port"); // } // // hikari.setJdbcUrl("jdbc:mysql://" + config.getString("MySQL.Hostname") + ":" + port + "/" + config.getString("MySQL.Database")); // hikari.addDataSourceProperty("useSSL", false); // hikari.addDataSourceProperty("requireSSL", false); // hikari.addDataSourceProperty("verifyServerCertificate", false); // hikari.addDataSourceProperty("user", config.getString("MySQL.Username")); // hikari.addDataSourceProperty("password", config.getString("MySQL.Password")); // // hikari.setUsername(config.getString("MySQL.Username")); // hikari.setPassword(config.getString("MySQL.Password")); // // new DatabaseUpdater(handler, hikari, plugin).runTaskAsynchronously(plugin); // } // // @Override // public void reload() { // new DataDownloader(handler, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void shutdown() { // if (hikari != null) { // hikari.close(); // } // } // // @Override // public void load(Player player, boolean loggedIn) { // new PlayerLoader(player.getUniqueId(), plugin, handler, hikari, loggedIn).runTaskAsynchronously(plugin); // } // // @Override // public void save(PlayerData... playerData) { // new PlayerSaver(playerData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void save(GroupData... groupData) { // new GroupSaver(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void savePriority(boolean playerTag, String key, final int priority) { // if (playerTag) { // UUIDFetcher.lookupUUID(key, plugin, uuid -> { // if (uuid != null) { // new PlayerPriority(uuid, priority, hikari).runTaskAsynchronously(plugin); // } else { // plugin.getLogger().severe("An error has occurred while looking for UUID."); // } // }); // } else { // new GroupPriority(key, priority, hikari).runTaskAsynchronously(plugin); // } // } // // @Override // public void delete(GroupData groupData) { // new GroupDeleter(groupData.getGroupName(), hikari).runTaskAsynchronously(plugin); // } // // @Override // public void add(GroupData groupData) { // new GroupAdd(groupData, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void clear(UUID uuid, String targetName) { // new PlayerDeleter(uuid, hikari).runTaskAsynchronously(plugin); // } // // @Override // public void orderGroups(CommandSender commandSender, List<String> order) { // String formatted = Arrays.toString(order.toArray()); // formatted = formatted.substring(1, formatted.length() - 1).replace(",", ""); // new GroupConfigUpdater("order", formatted, hikari).runTaskAsynchronously(handler.getPlugin()); // } // // } // Path: src/main/java/com/nametagedit/plugin/storage/database/tasks/PlayerDeleter.java import com.nametagedit.plugin.storage.database.DatabaseConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.AllArgsConstructor; import org.bukkit.scheduler.BukkitRunnable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.UUID; package com.nametagedit.plugin.storage.database.tasks; @AllArgsConstructor public class PlayerDeleter extends BukkitRunnable { private final UUID uuid; private final HikariDataSource hikari; @Override public void run() { try (Connection connection = hikari.getConnection()) {
final String QUERY = "DELETE FROM " + DatabaseConfig.TABLE_PLAYERS + " WHERE `uuid`=?";
google/tweakr
android/tweakr/src/main/java/com/google/tweakr/TweakrRepo.java
// Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // }
import com.google.tweakr.types.ValueType;
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr; /** * A repo to store Tweaks and manipulate them with a UI, then notify the registry via * {@link OnChangeListener}. */ public interface TweakrRepo { String FIELD_SEPARATOR = ":"; interface OnChangeListener { /** * Called when the value changes in the UI. * * @param name fully-qualified name of the member. * @param value the new value to be set. */ void onFieldChanged(String name, Object value); } /** * Registers a listener to be notified whenever a value changes in the UI. */ void addListener(OnChangeListener listener); /** * Removes a listener added with {@link #addListener(OnChangeListener)} */ void removeListener(OnChangeListener listener); /** * Add a new Tweak. * @param name fully-qualified name of the tweak: may be a path of parent objects to the actual * field's name, separated by {@link #FIELD_SEPARATOR}. * @param targetId monotonically increasing ID of the target object. * @param valueType ValueType for converting the UI value before passing it to * {@link OnChangeListener#onFieldChanged}. * @param initialValue Initial value of the field as it exists in the target object. * @param tweakMetadata Metadata from the annotation for the UI to display. */
// Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // Path: android/tweakr/src/main/java/com/google/tweakr/TweakrRepo.java import com.google.tweakr.types.ValueType; // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr; /** * A repo to store Tweaks and manipulate them with a UI, then notify the registry via * {@link OnChangeListener}. */ public interface TweakrRepo { String FIELD_SEPARATOR = ":"; interface OnChangeListener { /** * Called when the value changes in the UI. * * @param name fully-qualified name of the member. * @param value the new value to be set. */ void onFieldChanged(String name, Object value); } /** * Registers a listener to be notified whenever a value changes in the UI. */ void addListener(OnChangeListener listener); /** * Removes a listener added with {@link #addListener(OnChangeListener)} */ void removeListener(OnChangeListener listener); /** * Add a new Tweak. * @param name fully-qualified name of the tweak: may be a path of parent objects to the actual * field's name, separated by {@link #FIELD_SEPARATOR}. * @param targetId monotonically increasing ID of the target object. * @param valueType ValueType for converting the UI value before passing it to * {@link OnChangeListener#onFieldChanged}. * @param initialValue Initial value of the field as it exists in the target object. * @param tweakMetadata Metadata from the annotation for the UI to display. */
void add(String name, int targetId, ValueType valueType, Object initialValue, TweakMetadata tweakMetadata);
google/tweakr
android/tweakr-firebase/src/main/java/com/google/tweakr/TweakrFirebaseRepo.java
// Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // }
import androidx.annotation.NonNull; import android.util.Log; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.tweakr.types.ValueType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture;
* Returns the name of the root-level collection in the database to add all Tweaks. * * Override this if you are using the same database for multiple apps. */ @NonNull protected String getRootCollectionKey() { return TABLE_TWEAKR; } /** * Returns the user's sub-collection key. Use this if you want each user to be able to Tweak * their own set of values, which will not change the other users' values. * * @return an alphanumeric identifier that is unique per user. */ public CompletableFuture<String> getUserKey() { return CompletableFuture.completedFuture("default"); } @Override public void addListener(OnChangeListener listener) { listeners.add(listener); } @Override public void removeListener(OnChangeListener listener) { listeners.remove(listener); } @Override
// Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // Path: android/tweakr-firebase/src/main/java/com/google/tweakr/TweakrFirebaseRepo.java import androidx.annotation.NonNull; import android.util.Log; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.tweakr.types.ValueType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; * Returns the name of the root-level collection in the database to add all Tweaks. * * Override this if you are using the same database for multiple apps. */ @NonNull protected String getRootCollectionKey() { return TABLE_TWEAKR; } /** * Returns the user's sub-collection key. Use this if you want each user to be able to Tweak * their own set of values, which will not change the other users' values. * * @return an alphanumeric identifier that is unique per user. */ public CompletableFuture<String> getUserKey() { return CompletableFuture.completedFuture("default"); } @Override public void addListener(OnChangeListener listener) { listeners.add(listener); } @Override public void removeListener(OnChangeListener listener) { listeners.remove(listener); } @Override
public void add(String name, int targetId, ValueType valueType, Object initialValue, TweakMetadata tweakMetadata) {
google/tweakr
android/tweakr/src/main/java/com/google/tweakr/TweakrRegistry.java
// Path: android/tweakr/src/main/java/com/google/tweakr/collections/FieldMap.java // public class FieldMap<K> extends MemberMap<K, Field> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws IllegalAccessException { // Object target = holder.target.get(); // holder.member.set(target, value); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/collections/MethodMap.java // public class MethodMap<K> extends MemberMap<K, Method> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws InvocationTargetException, IllegalAccessException { // Object target = holder.target.get(); // // if (holder.member.getParameterTypes().length > 0) { // holder.member.invoke(target, value); // } else { // holder.member.invoke(target); // } // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueTypeConverter.java // public interface ValueTypeConverter { // // ValueType getType(Class<?> fieldType); // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // }
import static com.google.tweakr.TweakrRepo.FIELD_SEPARATOR; import android.util.Log; import androidx.annotation.NonNull; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.collections.FieldMap; import com.google.tweakr.collections.MethodMap; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.ValueTypeConverter; import com.google.tweakr.types.VoidValueType; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier;
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr; /** * Keeps track of all the Tweaks registered so far and applies changes to each target's Tweaks when * they change in the repo. */ class TweakrRegistry implements TweakrRepo.OnChangeListener { private static final String TAG = "TweakrRegistry"; private static TweakrRegistry singleton; public synchronized static TweakrRegistry get(TweakrRepo repo) { if (singleton == null) { singleton = new TweakrRegistry(repo); } return singleton; } private final TweakrRepo repo;
// Path: android/tweakr/src/main/java/com/google/tweakr/collections/FieldMap.java // public class FieldMap<K> extends MemberMap<K, Field> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws IllegalAccessException { // Object target = holder.target.get(); // holder.member.set(target, value); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/collections/MethodMap.java // public class MethodMap<K> extends MemberMap<K, Method> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws InvocationTargetException, IllegalAccessException { // Object target = holder.target.get(); // // if (holder.member.getParameterTypes().length > 0) { // holder.member.invoke(target, value); // } else { // holder.member.invoke(target); // } // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueTypeConverter.java // public interface ValueTypeConverter { // // ValueType getType(Class<?> fieldType); // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // } // Path: android/tweakr/src/main/java/com/google/tweakr/TweakrRegistry.java import static com.google.tweakr.TweakrRepo.FIELD_SEPARATOR; import android.util.Log; import androidx.annotation.NonNull; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.collections.FieldMap; import com.google.tweakr.collections.MethodMap; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.ValueTypeConverter; import com.google.tweakr.types.VoidValueType; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr; /** * Keeps track of all the Tweaks registered so far and applies changes to each target's Tweaks when * they change in the repo. */ class TweakrRegistry implements TweakrRepo.OnChangeListener { private static final String TAG = "TweakrRegistry"; private static TweakrRegistry singleton; public synchronized static TweakrRegistry get(TweakrRepo repo) { if (singleton == null) { singleton = new TweakrRegistry(repo); } return singleton; } private final TweakrRepo repo;
private final FieldMap<String> fields = new FieldMap<>();
google/tweakr
android/tweakr/src/main/java/com/google/tweakr/TweakrRegistry.java
// Path: android/tweakr/src/main/java/com/google/tweakr/collections/FieldMap.java // public class FieldMap<K> extends MemberMap<K, Field> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws IllegalAccessException { // Object target = holder.target.get(); // holder.member.set(target, value); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/collections/MethodMap.java // public class MethodMap<K> extends MemberMap<K, Method> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws InvocationTargetException, IllegalAccessException { // Object target = holder.target.get(); // // if (holder.member.getParameterTypes().length > 0) { // holder.member.invoke(target, value); // } else { // holder.member.invoke(target); // } // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueTypeConverter.java // public interface ValueTypeConverter { // // ValueType getType(Class<?> fieldType); // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // }
import static com.google.tweakr.TweakrRepo.FIELD_SEPARATOR; import android.util.Log; import androidx.annotation.NonNull; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.collections.FieldMap; import com.google.tweakr.collections.MethodMap; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.ValueTypeConverter; import com.google.tweakr.types.VoidValueType; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier;
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr; /** * Keeps track of all the Tweaks registered so far and applies changes to each target's Tweaks when * they change in the repo. */ class TweakrRegistry implements TweakrRepo.OnChangeListener { private static final String TAG = "TweakrRegistry"; private static TweakrRegistry singleton; public synchronized static TweakrRegistry get(TweakrRepo repo) { if (singleton == null) { singleton = new TweakrRegistry(repo); } return singleton; } private final TweakrRepo repo; private final FieldMap<String> fields = new FieldMap<>();
// Path: android/tweakr/src/main/java/com/google/tweakr/collections/FieldMap.java // public class FieldMap<K> extends MemberMap<K, Field> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws IllegalAccessException { // Object target = holder.target.get(); // holder.member.set(target, value); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/collections/MethodMap.java // public class MethodMap<K> extends MemberMap<K, Method> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws InvocationTargetException, IllegalAccessException { // Object target = holder.target.get(); // // if (holder.member.getParameterTypes().length > 0) { // holder.member.invoke(target, value); // } else { // holder.member.invoke(target); // } // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueTypeConverter.java // public interface ValueTypeConverter { // // ValueType getType(Class<?> fieldType); // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // } // Path: android/tweakr/src/main/java/com/google/tweakr/TweakrRegistry.java import static com.google.tweakr.TweakrRepo.FIELD_SEPARATOR; import android.util.Log; import androidx.annotation.NonNull; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.collections.FieldMap; import com.google.tweakr.collections.MethodMap; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.ValueTypeConverter; import com.google.tweakr.types.VoidValueType; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr; /** * Keeps track of all the Tweaks registered so far and applies changes to each target's Tweaks when * they change in the repo. */ class TweakrRegistry implements TweakrRepo.OnChangeListener { private static final String TAG = "TweakrRegistry"; private static TweakrRegistry singleton; public synchronized static TweakrRegistry get(TweakrRepo repo) { if (singleton == null) { singleton = new TweakrRegistry(repo); } return singleton; } private final TweakrRepo repo; private final FieldMap<String> fields = new FieldMap<>();
private final MethodMap<String> methods = new MethodMap<>();
google/tweakr
android/tweakr/src/main/java/com/google/tweakr/TweakrRegistry.java
// Path: android/tweakr/src/main/java/com/google/tweakr/collections/FieldMap.java // public class FieldMap<K> extends MemberMap<K, Field> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws IllegalAccessException { // Object target = holder.target.get(); // holder.member.set(target, value); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/collections/MethodMap.java // public class MethodMap<K> extends MemberMap<K, Method> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws InvocationTargetException, IllegalAccessException { // Object target = holder.target.get(); // // if (holder.member.getParameterTypes().length > 0) { // holder.member.invoke(target, value); // } else { // holder.member.invoke(target); // } // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueTypeConverter.java // public interface ValueTypeConverter { // // ValueType getType(Class<?> fieldType); // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // }
import static com.google.tweakr.TweakrRepo.FIELD_SEPARATOR; import android.util.Log; import androidx.annotation.NonNull; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.collections.FieldMap; import com.google.tweakr.collections.MethodMap; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.ValueTypeConverter; import com.google.tweakr.types.VoidValueType; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier;
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr; /** * Keeps track of all the Tweaks registered so far and applies changes to each target's Tweaks when * they change in the repo. */ class TweakrRegistry implements TweakrRepo.OnChangeListener { private static final String TAG = "TweakrRegistry"; private static TweakrRegistry singleton; public synchronized static TweakrRegistry get(TweakrRepo repo) { if (singleton == null) { singleton = new TweakrRegistry(repo); } return singleton; } private final TweakrRepo repo; private final FieldMap<String> fields = new FieldMap<>(); private final MethodMap<String> methods = new MethodMap<>(); private int currentTargetId = 0;
// Path: android/tweakr/src/main/java/com/google/tweakr/collections/FieldMap.java // public class FieldMap<K> extends MemberMap<K, Field> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws IllegalAccessException { // Object target = holder.target.get(); // holder.member.set(target, value); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/collections/MethodMap.java // public class MethodMap<K> extends MemberMap<K, Method> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws InvocationTargetException, IllegalAccessException { // Object target = holder.target.get(); // // if (holder.member.getParameterTypes().length > 0) { // holder.member.invoke(target, value); // } else { // holder.member.invoke(target); // } // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueTypeConverter.java // public interface ValueTypeConverter { // // ValueType getType(Class<?> fieldType); // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // } // Path: android/tweakr/src/main/java/com/google/tweakr/TweakrRegistry.java import static com.google.tweakr.TweakrRepo.FIELD_SEPARATOR; import android.util.Log; import androidx.annotation.NonNull; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.collections.FieldMap; import com.google.tweakr.collections.MethodMap; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.ValueTypeConverter; import com.google.tweakr.types.VoidValueType; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr; /** * Keeps track of all the Tweaks registered so far and applies changes to each target's Tweaks when * they change in the repo. */ class TweakrRegistry implements TweakrRepo.OnChangeListener { private static final String TAG = "TweakrRegistry"; private static TweakrRegistry singleton; public synchronized static TweakrRegistry get(TweakrRepo repo) { if (singleton == null) { singleton = new TweakrRegistry(repo); } return singleton; } private final TweakrRepo repo; private final FieldMap<String> fields = new FieldMap<>(); private final MethodMap<String> methods = new MethodMap<>(); private int currentTargetId = 0;
private ValueTypeConverter typeConverter;
google/tweakr
android/tweakr/src/main/java/com/google/tweakr/TweakrRegistry.java
// Path: android/tweakr/src/main/java/com/google/tweakr/collections/FieldMap.java // public class FieldMap<K> extends MemberMap<K, Field> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws IllegalAccessException { // Object target = holder.target.get(); // holder.member.set(target, value); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/collections/MethodMap.java // public class MethodMap<K> extends MemberMap<K, Method> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws InvocationTargetException, IllegalAccessException { // Object target = holder.target.get(); // // if (holder.member.getParameterTypes().length > 0) { // holder.member.invoke(target, value); // } else { // holder.member.invoke(target); // } // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueTypeConverter.java // public interface ValueTypeConverter { // // ValueType getType(Class<?> fieldType); // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // }
import static com.google.tweakr.TweakrRepo.FIELD_SEPARATOR; import android.util.Log; import androidx.annotation.NonNull; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.collections.FieldMap; import com.google.tweakr.collections.MethodMap; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.ValueTypeConverter; import com.google.tweakr.types.VoidValueType; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier;
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr; /** * Keeps track of all the Tweaks registered so far and applies changes to each target's Tweaks when * they change in the repo. */ class TweakrRegistry implements TweakrRepo.OnChangeListener { private static final String TAG = "TweakrRegistry"; private static TweakrRegistry singleton; public synchronized static TweakrRegistry get(TweakrRepo repo) { if (singleton == null) { singleton = new TweakrRegistry(repo); } return singleton; } private final TweakrRepo repo; private final FieldMap<String> fields = new FieldMap<>(); private final MethodMap<String> methods = new MethodMap<>(); private int currentTargetId = 0; private ValueTypeConverter typeConverter; protected TweakrRegistry(TweakrRepo repo) { this.repo = repo;
// Path: android/tweakr/src/main/java/com/google/tweakr/collections/FieldMap.java // public class FieldMap<K> extends MemberMap<K, Field> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws IllegalAccessException { // Object target = holder.target.get(); // holder.member.set(target, value); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/collections/MethodMap.java // public class MethodMap<K> extends MemberMap<K, Method> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws InvocationTargetException, IllegalAccessException { // Object target = holder.target.get(); // // if (holder.member.getParameterTypes().length > 0) { // holder.member.invoke(target, value); // } else { // holder.member.invoke(target); // } // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueTypeConverter.java // public interface ValueTypeConverter { // // ValueType getType(Class<?> fieldType); // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // } // Path: android/tweakr/src/main/java/com/google/tweakr/TweakrRegistry.java import static com.google.tweakr.TweakrRepo.FIELD_SEPARATOR; import android.util.Log; import androidx.annotation.NonNull; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.collections.FieldMap; import com.google.tweakr.collections.MethodMap; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.ValueTypeConverter; import com.google.tweakr.types.VoidValueType; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr; /** * Keeps track of all the Tweaks registered so far and applies changes to each target's Tweaks when * they change in the repo. */ class TweakrRegistry implements TweakrRepo.OnChangeListener { private static final String TAG = "TweakrRegistry"; private static TweakrRegistry singleton; public synchronized static TweakrRegistry get(TweakrRepo repo) { if (singleton == null) { singleton = new TweakrRegistry(repo); } return singleton; } private final TweakrRepo repo; private final FieldMap<String> fields = new FieldMap<>(); private final MethodMap<String> methods = new MethodMap<>(); private int currentTargetId = 0; private ValueTypeConverter typeConverter; protected TweakrRegistry(TweakrRepo repo) { this.repo = repo;
typeConverter = new DefaultValueTypeConverter();
google/tweakr
android/tweakr/src/main/java/com/google/tweakr/TweakrRegistry.java
// Path: android/tweakr/src/main/java/com/google/tweakr/collections/FieldMap.java // public class FieldMap<K> extends MemberMap<K, Field> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws IllegalAccessException { // Object target = holder.target.get(); // holder.member.set(target, value); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/collections/MethodMap.java // public class MethodMap<K> extends MemberMap<K, Method> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws InvocationTargetException, IllegalAccessException { // Object target = holder.target.get(); // // if (holder.member.getParameterTypes().length > 0) { // holder.member.invoke(target, value); // } else { // holder.member.invoke(target); // } // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueTypeConverter.java // public interface ValueTypeConverter { // // ValueType getType(Class<?> fieldType); // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // }
import static com.google.tweakr.TweakrRepo.FIELD_SEPARATOR; import android.util.Log; import androidx.annotation.NonNull; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.collections.FieldMap; import com.google.tweakr.collections.MethodMap; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.ValueTypeConverter; import com.google.tweakr.types.VoidValueType; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier;
if (childName.equals(method.getName())) { if (paramName == null) { return method; } else { Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 1) { if (paramName.equals(parameterTypes[0].getSimpleName())) { return method; } } } } } } throw new NoSuchMethodException(); } private Field getChildField(Object target, String fieldName) throws NoSuchFieldException, IllegalAccessException { Field field = target.getClass().getField(fieldName); if ((field.getModifiers() & Modifier.PUBLIC) == 0) { throw new IllegalAccessException(); } return field; } private void registerField(Object target, Field field, String name, Tweak annotation) { fields.add(name, target, field); // Register with firebase.
// Path: android/tweakr/src/main/java/com/google/tweakr/collections/FieldMap.java // public class FieldMap<K> extends MemberMap<K, Field> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws IllegalAccessException { // Object target = holder.target.get(); // holder.member.set(target, value); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/collections/MethodMap.java // public class MethodMap<K> extends MemberMap<K, Method> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws InvocationTargetException, IllegalAccessException { // Object target = holder.target.get(); // // if (holder.member.getParameterTypes().length > 0) { // holder.member.invoke(target, value); // } else { // holder.member.invoke(target); // } // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueTypeConverter.java // public interface ValueTypeConverter { // // ValueType getType(Class<?> fieldType); // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // } // Path: android/tweakr/src/main/java/com/google/tweakr/TweakrRegistry.java import static com.google.tweakr.TweakrRepo.FIELD_SEPARATOR; import android.util.Log; import androidx.annotation.NonNull; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.collections.FieldMap; import com.google.tweakr.collections.MethodMap; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.ValueTypeConverter; import com.google.tweakr.types.VoidValueType; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; if (childName.equals(method.getName())) { if (paramName == null) { return method; } else { Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 1) { if (paramName.equals(parameterTypes[0].getSimpleName())) { return method; } } } } } } throw new NoSuchMethodException(); } private Field getChildField(Object target, String fieldName) throws NoSuchFieldException, IllegalAccessException { Field field = target.getClass().getField(fieldName); if ((field.getModifiers() & Modifier.PUBLIC) == 0) { throw new IllegalAccessException(); } return field; } private void registerField(Object target, Field field, String name, Tweak annotation) { fields.add(name, target, field); // Register with firebase.
ValueType valueType = getCustomValueType(annotation);
google/tweakr
android/tweakr/src/main/java/com/google/tweakr/TweakrRegistry.java
// Path: android/tweakr/src/main/java/com/google/tweakr/collections/FieldMap.java // public class FieldMap<K> extends MemberMap<K, Field> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws IllegalAccessException { // Object target = holder.target.get(); // holder.member.set(target, value); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/collections/MethodMap.java // public class MethodMap<K> extends MemberMap<K, Method> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws InvocationTargetException, IllegalAccessException { // Object target = holder.target.get(); // // if (holder.member.getParameterTypes().length > 0) { // holder.member.invoke(target, value); // } else { // holder.member.invoke(target); // } // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueTypeConverter.java // public interface ValueTypeConverter { // // ValueType getType(Class<?> fieldType); // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // }
import static com.google.tweakr.TweakrRepo.FIELD_SEPARATOR; import android.util.Log; import androidx.annotation.NonNull; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.collections.FieldMap; import com.google.tweakr.collections.MethodMap; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.ValueTypeConverter; import com.google.tweakr.types.VoidValueType; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier;
return annotation.valueType().newInstance(); } catch (IllegalAccessException|InstantiationException e) { Log.e(TAG, "Could not create custom ValueType", e); } } return null; } @NonNull private String buildName(Object target, Member field, String targetPrefix) { String name = field.getName(); String targetClass = target.getClass().getSimpleName(); if (!TextUtils.isEmpty(targetClass)) { name = targetClass + FIELD_SEPARATOR + name; } if (!TextUtils.isEmpty(targetPrefix)) { name = targetPrefix + FIELD_SEPARATOR + name; } return name; } private void registerMethod(Object target, Method method, String name, Tweak annotation) { methods.add(name, target, method); // Register with firebase. ValueType valueType = getCustomValueType(annotation); if (valueType == null) { Class<?>[] parameterTypes = method.getParameterTypes(); valueType = parameterTypes.length > 0 ? typeConverter.getType(parameterTypes[0])
// Path: android/tweakr/src/main/java/com/google/tweakr/collections/FieldMap.java // public class FieldMap<K> extends MemberMap<K, Field> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws IllegalAccessException { // Object target = holder.target.get(); // holder.member.set(target, value); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/collections/MethodMap.java // public class MethodMap<K> extends MemberMap<K, Method> { // // @Override // protected void setValue(MemberHolder holder, Object value) throws InvocationTargetException, IllegalAccessException { // Object target = holder.target.get(); // // if (holder.member.getParameterTypes().length > 0) { // holder.member.invoke(target, value); // } else { // holder.member.invoke(target); // } // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueTypeConverter.java // public interface ValueTypeConverter { // // ValueType getType(Class<?> fieldType); // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // } // Path: android/tweakr/src/main/java/com/google/tweakr/TweakrRegistry.java import static com.google.tweakr.TweakrRepo.FIELD_SEPARATOR; import android.util.Log; import androidx.annotation.NonNull; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.collections.FieldMap; import com.google.tweakr.collections.MethodMap; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.ValueTypeConverter; import com.google.tweakr.types.VoidValueType; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; return annotation.valueType().newInstance(); } catch (IllegalAccessException|InstantiationException e) { Log.e(TAG, "Could not create custom ValueType", e); } } return null; } @NonNull private String buildName(Object target, Member field, String targetPrefix) { String name = field.getName(); String targetClass = target.getClass().getSimpleName(); if (!TextUtils.isEmpty(targetClass)) { name = targetClass + FIELD_SEPARATOR + name; } if (!TextUtils.isEmpty(targetPrefix)) { name = targetPrefix + FIELD_SEPARATOR + name; } return name; } private void registerMethod(Object target, Method method, String name, Tweak annotation) { methods.add(name, target, method); // Register with firebase. ValueType valueType = getCustomValueType(annotation); if (valueType == null) { Class<?>[] parameterTypes = method.getParameterTypes(); valueType = parameterTypes.length > 0 ? typeConverter.getType(parameterTypes[0])
: new VoidValueType();
google/tweakr
android/tweakr/src/test/java/com/google/tweakr/TweakrRegistryTest.java
// Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // }
import static org.mockito.Mockito.verify; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.VoidValueType; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull;
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class TweakrRegistryTest { private static final String TEST_STRING = "this is a test"; private static final int TEST_INT = 134426; private static final Float TEST_FLOAT = 434.324f; private enum TestEnum { SOMETHING, SOMETHING_ELSE } @Mock public TweakrRepo repo; private TweakrRegistry registry; @Before public void setup() { MockitoAnnotations.initMocks(this); registry = new TweakrRegistry(repo); } @Test public void tweakString() { Object testObject = new Object() { @Tweak public String testField = TEST_STRING; }; registry.register(testObject, null);
// Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // } // Path: android/tweakr/src/test/java/com/google/tweakr/TweakrRegistryTest.java import static org.mockito.Mockito.verify; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.VoidValueType; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class TweakrRegistryTest { private static final String TEST_STRING = "this is a test"; private static final int TEST_INT = 134426; private static final Float TEST_FLOAT = 434.324f; private enum TestEnum { SOMETHING, SOMETHING_ELSE } @Mock public TweakrRepo repo; private TweakrRegistry registry; @Before public void setup() { MockitoAnnotations.initMocks(this); registry = new TweakrRegistry(repo); } @Test public void tweakString() { Object testObject = new Object() { @Tweak public String testField = TEST_STRING; }; registry.register(testObject, null);
ValueType valueType = new DefaultValueTypeConverter().getType(String.class);
google/tweakr
android/tweakr/src/test/java/com/google/tweakr/TweakrRegistryTest.java
// Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // }
import static org.mockito.Mockito.verify; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.VoidValueType; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull;
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class TweakrRegistryTest { private static final String TEST_STRING = "this is a test"; private static final int TEST_INT = 134426; private static final Float TEST_FLOAT = 434.324f; private enum TestEnum { SOMETHING, SOMETHING_ELSE } @Mock public TweakrRepo repo; private TweakrRegistry registry; @Before public void setup() { MockitoAnnotations.initMocks(this); registry = new TweakrRegistry(repo); } @Test public void tweakString() { Object testObject = new Object() { @Tweak public String testField = TEST_STRING; }; registry.register(testObject, null);
// Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // } // Path: android/tweakr/src/test/java/com/google/tweakr/TweakrRegistryTest.java import static org.mockito.Mockito.verify; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.VoidValueType; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class TweakrRegistryTest { private static final String TEST_STRING = "this is a test"; private static final int TEST_INT = 134426; private static final Float TEST_FLOAT = 434.324f; private enum TestEnum { SOMETHING, SOMETHING_ELSE } @Mock public TweakrRepo repo; private TweakrRegistry registry; @Before public void setup() { MockitoAnnotations.initMocks(this); registry = new TweakrRegistry(repo); } @Test public void tweakString() { Object testObject = new Object() { @Tweak public String testField = TEST_STRING; }; registry.register(testObject, null);
ValueType valueType = new DefaultValueTypeConverter().getType(String.class);
google/tweakr
android/tweakr/src/test/java/com/google/tweakr/TweakrRegistryTest.java
// Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // }
import static org.mockito.Mockito.verify; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.VoidValueType; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull;
public void tweakEnumMethod() { Object testObject = new Object() { @Tweak public void setTest(TestEnum p) { } public TestEnum getTest() { return TestEnum.SOMETHING_ELSE; } }; registry.register(testObject, null); ValueType valueType = new DefaultValueTypeConverter().getType(TestEnum.class); verify(repo).add(eq("setTest"), eq(1), eq(valueType), eq(TestEnum.SOMETHING_ELSE), any()); } @Test public void tweakVoidMethod() { Object testObject = new Object() { @Tweak public void setTest() { } }; registry.register(testObject, null);
// Path: android/tweakr/src/main/java/com/google/tweakr/types/DefaultValueTypeConverter.java // public class DefaultValueTypeConverter implements ValueTypeConverter { // // @Override // public ValueType getType(Class<?> fieldType) { // if (fieldType.isArray()) { // return new ArrayValueType(getType(fieldType.getComponentType())); // } // // if (fieldType == float.class || fieldType == double.class || fieldType == Float.class || fieldType == Double.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_FLOAT); // } else if (fieldType == int.class || fieldType == long.class || fieldType == Integer.class || fieldType == Long.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_INT); // } else if (fieldType == boolean.class || fieldType == Boolean.class) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_BOOLEAN); // } else if (fieldType.isAssignableFrom(String.class)) { // return new PrimitiveValueType(PrimitiveValueType.TYPE_STRING); // } else if (fieldType.isEnum()) { // return new EnumValueType(fieldType); // } // // return new PrimitiveValueType(PrimitiveValueType.TYPE_UNKNOWN); // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // // Path: android/tweakr/src/main/java/com/google/tweakr/types/VoidValueType.java // public class VoidValueType implements ValueType { // // @Override // public String getName() { // return "void"; // } // // @Override // public Object getDefault() { // return null; // } // // @Override // public Object convert(Object newValue) { // return null; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ValueType that = (ValueType) o; // return getName().equals(that.getName()); // } // // @Override // public int hashCode() { // return Objects.hash(getName()); // } // } // Path: android/tweakr/src/test/java/com/google/tweakr/TweakrRegistryTest.java import static org.mockito.Mockito.verify; import com.google.tweakr.annotations.Tweak; import com.google.tweakr.types.DefaultValueTypeConverter; import com.google.tweakr.types.ValueType; import com.google.tweakr.types.VoidValueType; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; public void tweakEnumMethod() { Object testObject = new Object() { @Tweak public void setTest(TestEnum p) { } public TestEnum getTest() { return TestEnum.SOMETHING_ELSE; } }; registry.register(testObject, null); ValueType valueType = new DefaultValueTypeConverter().getType(TestEnum.class); verify(repo).add(eq("setTest"), eq(1), eq(valueType), eq(TestEnum.SOMETHING_ELSE), any()); } @Test public void tweakVoidMethod() { Object testObject = new Object() { @Tweak public void setTest() { } }; registry.register(testObject, null);
ValueType valueType = new VoidValueType();
google/tweakr
android-sample/app/src/main/java/com/google/tweakr/sample/MainActivity.java
// Path: android/tweakr/src/main/java/com/google/tweakr/Tweakr.java // public class Tweakr { // // private static TweakrRepo repo; // // /** // * Returns the current repo used for this session. // */ // public static synchronized TweakrRepo getRepo() { // if (repo == null) { // throw new IllegalStateException("Must call TweakrRepo.setRepo() first."); // } // return repo; // } // // /** // * Optionally sets the repo to be used for this session. // * // * You must set this before any other calls to methods in this class (e.g. // * {@link #register(Object)}). Best practice is to set it in your {@link Application#onCreate()} // * // */ // public static synchronized void setRepo(TweakrRepo repo) { // if (Tweakr.repo != null) { // throw new IllegalStateException("Repo has already been set. You may only setRepo once, before any calls to register() or addListener()"); // } // Tweakr.repo = repo; // } // // /** // * {@see #register(Object, String)} // */ // public static void register(Object target) { // register(target, null); // } // // /** // * Registers all members of target that are annotated with // * {@link com.google.tweakr.annotations.Tweak}. // * // * Any annotated fields with children must be non-null at the time of registration. // * // * @param target the object containing members to register. // * @param namePrefix An optional prefix for each Tweak. Use this if you want to differentiate // * multiple objects in the UI: instead of changing a value and changing all // * objects that share that member, you can add a unique namePrefix for each // * object (or group of objects) so that the changes only affect a subset of // * the targets. // */ // public static void register(Object target, String namePrefix) { // TweakrRegistry.get(getRepo()).register(target, namePrefix); // } // // /** // * Registers all members of target that are annotated with // * {@link com.google.tweakr.annotations.Tweak}. // * // * Any annotated fields with children must be non-null at the time of registration. // * // * @param target the object containing members to register. // * @param clazz the type of object to gather fields from. Use this in superclasses, since Tweakr // * will only gather the declared fields of the given class, not inherited fields. // * @param namePrefix An optional prefix for each Tweak. Use this if you want to differentiate // * multiple objects in the UI: instead of changing a value and changing all // * objects that share that member, you can add a unique namePrefix for each // * object (or group of objects) so that the changes only affect a subset of // * the targets. // */ // public <T> void register(T target, Class<? extends T> clazz, String namePrefix) { // TweakrRegistry.get(getRepo()).register(target, clazz, namePrefix); // } // // /** // * {@see TweakrRepo#addListener} // */ // public static void addListener(TweakrRepo.OnChangeListener listener) { // getRepo().addListener(listener); // } // /** // * {@see TweakrRepo#removeListener} // */ // public static void removeListener(TweakrRepo.OnChangeListener listener) { // getRepo().removeListener(listener); // } // }
import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.TextView; import com.google.tweakr.Tweakr; import com.google.tweakr.annotations.Tweak;
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr.sample; //import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends Activity { @Tweak(child ="setText(CharSequence)") public TextView introText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); introText = findViewById(R.id.text); // Make sure to register AFTER you have set all your View fields!
// Path: android/tweakr/src/main/java/com/google/tweakr/Tweakr.java // public class Tweakr { // // private static TweakrRepo repo; // // /** // * Returns the current repo used for this session. // */ // public static synchronized TweakrRepo getRepo() { // if (repo == null) { // throw new IllegalStateException("Must call TweakrRepo.setRepo() first."); // } // return repo; // } // // /** // * Optionally sets the repo to be used for this session. // * // * You must set this before any other calls to methods in this class (e.g. // * {@link #register(Object)}). Best practice is to set it in your {@link Application#onCreate()} // * // */ // public static synchronized void setRepo(TweakrRepo repo) { // if (Tweakr.repo != null) { // throw new IllegalStateException("Repo has already been set. You may only setRepo once, before any calls to register() or addListener()"); // } // Tweakr.repo = repo; // } // // /** // * {@see #register(Object, String)} // */ // public static void register(Object target) { // register(target, null); // } // // /** // * Registers all members of target that are annotated with // * {@link com.google.tweakr.annotations.Tweak}. // * // * Any annotated fields with children must be non-null at the time of registration. // * // * @param target the object containing members to register. // * @param namePrefix An optional prefix for each Tweak. Use this if you want to differentiate // * multiple objects in the UI: instead of changing a value and changing all // * objects that share that member, you can add a unique namePrefix for each // * object (or group of objects) so that the changes only affect a subset of // * the targets. // */ // public static void register(Object target, String namePrefix) { // TweakrRegistry.get(getRepo()).register(target, namePrefix); // } // // /** // * Registers all members of target that are annotated with // * {@link com.google.tweakr.annotations.Tweak}. // * // * Any annotated fields with children must be non-null at the time of registration. // * // * @param target the object containing members to register. // * @param clazz the type of object to gather fields from. Use this in superclasses, since Tweakr // * will only gather the declared fields of the given class, not inherited fields. // * @param namePrefix An optional prefix for each Tweak. Use this if you want to differentiate // * multiple objects in the UI: instead of changing a value and changing all // * objects that share that member, you can add a unique namePrefix for each // * object (or group of objects) so that the changes only affect a subset of // * the targets. // */ // public <T> void register(T target, Class<? extends T> clazz, String namePrefix) { // TweakrRegistry.get(getRepo()).register(target, clazz, namePrefix); // } // // /** // * {@see TweakrRepo#addListener} // */ // public static void addListener(TweakrRepo.OnChangeListener listener) { // getRepo().addListener(listener); // } // /** // * {@see TweakrRepo#removeListener} // */ // public static void removeListener(TweakrRepo.OnChangeListener listener) { // getRepo().removeListener(listener); // } // } // Path: android-sample/app/src/main/java/com/google/tweakr/sample/MainActivity.java import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.TextView; import com.google.tweakr.Tweakr; import com.google.tweakr.annotations.Tweak; // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr.sample; //import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends Activity { @Tweak(child ="setText(CharSequence)") public TextView introText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); introText = findViewById(R.id.text); // Make sure to register AFTER you have set all your View fields!
Tweakr.register(this);
google/tweakr
android/tweakr/src/main/java/com/google/tweakr/annotations/Tweak.java
// Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // }
import com.google.tweakr.types.ValueType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD;
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr.annotations; /** * Add this annotation to any field or method you want to alter in the Tweakr UI. * * Most primitive types are supported automatically. If you want to handle a custom type, you will * need to implement {@link com.google.tweakr.types.ValueType} and either specify it in the * {@link #valueType()} attribute, or register your own * {@link com.google.tweakr.types.ValueTypeConverter} to return your custom ValueType whenever it * encounters a field using your type. * * If annotating a method, that method will be called with the updated value whenever you alter it * in the UI. If the method is a setter, it will automatically try to derive the initial value from * the corresponding getter (if it can find it). * * Only methods that take 0 or 1 parameters are currently supported. */ @Retention(RetentionPolicy.RUNTIME) @Target({METHOD,FIELD}) public @interface Tweak { /** * If specified, Tweaks a child member of the annotated object instead of the object itself. * * If the member is a property, Tweakr will automatically call the getters and setters as * appropriate, e.g.: * * if child="text", Tweakr will call "getText()" and "setText()". * * If there are multiple overloads of the method that take different parameters, you may * specify which overload to use by appending the parameter type in parenthesis, e.g.: * * child="setText(CharSequence)" or child="setText(int)" * * Only methods that take 0 or 1 parameters are currently supported. */ String child() default ""; /** * If specified, uses the given {@link com.google.tweakr.types.ValueType} instead of one * provided by the registered {@link com.google.tweakr.types.ValueTypeConverter}. This is * helpful if you want to specify a custom UI to tweak types that otherwise already have a * default UI. * * e.g. to present a color picker UI for an "int" field instead of the default number slider, * use `@Tweak(valueType = ColorValueType.class)` * */
// Path: android/tweakr/src/main/java/com/google/tweakr/types/ValueType.java // public interface ValueType { // /** // * Simple name of the type. Used to select an appropriate UI. // */ // String getName(); // // /** // * A default value if one cannot be determined. // */ // Object getDefault(); // // /** // * Safely convert a value from Firebase into the correct type. // */ // Object convert(Object newValue); // // /** // * For enum fields or other fields you want to restrict to only certain choices. // * // * @return An array of String representations of all possible values to choose from. // */ // default List<String> getPossibleValues() { // return null; // } // } // Path: android/tweakr/src/main/java/com/google/tweakr/annotations/Tweak.java import com.google.tweakr.types.ValueType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.tweakr.annotations; /** * Add this annotation to any field or method you want to alter in the Tweakr UI. * * Most primitive types are supported automatically. If you want to handle a custom type, you will * need to implement {@link com.google.tweakr.types.ValueType} and either specify it in the * {@link #valueType()} attribute, or register your own * {@link com.google.tweakr.types.ValueTypeConverter} to return your custom ValueType whenever it * encounters a field using your type. * * If annotating a method, that method will be called with the updated value whenever you alter it * in the UI. If the method is a setter, it will automatically try to derive the initial value from * the corresponding getter (if it can find it). * * Only methods that take 0 or 1 parameters are currently supported. */ @Retention(RetentionPolicy.RUNTIME) @Target({METHOD,FIELD}) public @interface Tweak { /** * If specified, Tweaks a child member of the annotated object instead of the object itself. * * If the member is a property, Tweakr will automatically call the getters and setters as * appropriate, e.g.: * * if child="text", Tweakr will call "getText()" and "setText()". * * If there are multiple overloads of the method that take different parameters, you may * specify which overload to use by appending the parameter type in parenthesis, e.g.: * * child="setText(CharSequence)" or child="setText(int)" * * Only methods that take 0 or 1 parameters are currently supported. */ String child() default ""; /** * If specified, uses the given {@link com.google.tweakr.types.ValueType} instead of one * provided by the registered {@link com.google.tweakr.types.ValueTypeConverter}. This is * helpful if you want to specify a custom UI to tweak types that otherwise already have a * default UI. * * e.g. to present a color picker UI for an "int" field instead of the default number slider, * use `@Tweak(valueType = ColorValueType.class)` * */
Class<? extends ValueType> valueType() default ValueType.class;
dynamid/jooflux
src/main/java/fr/insalyon/telecom/jooflux/internal/jmx/JooFluxManagement.java
// Path: src/main/java/fr/insalyon/telecom/jooflux/internal/Aspects.java // public class Aspects { // // public static MethodHandle before(MethodHandle target, MethodHandle beforeFilter) { // MethodType targetType = target.type(); // MethodType filterType = beforeFilter.type(); // int parameterCount = targetType.parameterCount(); // // if (filterType.parameterCount() != 1 && !filterType.parameterType(0).equals(Object[].class)) { // throw new IllegalArgumentException("beforeFilter must have a single argument of type Object[]"); // } // if (!filterType.returnType().equals(Object[].class)) { // throw new IllegalArgumentException("beforeFilter must have a Object[] return type"); // } // // MethodHandle spreader = target.asSpreader(Object[].class, parameterCount); // MethodHandle filter = filterArguments(spreader, 0, beforeFilter); // MethodHandle collector = filter.asCollector(Object[].class, parameterCount); // // return collector.asType(targetType); // // } // // public static MethodHandle after(MethodHandle target, MethodHandle afterFilter) { // MethodType targetType = target.type(); // MethodType filterType = afterFilter.type(); // // if (filterType.parameterCount() != 1 && !filterType.parameterType(0).equals(Object.class)) { // throw new IllegalArgumentException("afterFilter must have a single argument of type Object"); // } // if (!filterType.returnType().equals(Object.class)) { // throw new IllegalArgumentException("afterFilter must have a Object return type"); // } // // MethodHandle asObject = target.asType(targetType.changeReturnType(Object.class)); // MethodHandle filter = filterReturnValue(asObject, afterFilter); // // return filter.asType(targetType); // } // } // // Path: src/main/java/fr/insalyon/telecom/jooflux/internal/CallSiteRegistry.java // public class CallSiteRegistry { // // private CallSiteRegistry() { // super(); // } // // // Thread-safe thanks to the JVM internals! // private static class CallSiteRegistrySingletonHolder { // private static final CallSiteRegistry instance = new CallSiteRegistry(); // } // // public static CallSiteRegistry getInstance() { // return CallSiteRegistrySingletonHolder.instance; // } // // private final ConcurrentHashMap<String, Registration> registry = new ConcurrentHashMap<>(); // // public void put(String target, String type, CallSite callSite) { // registry.putIfAbsent(target, new Registration(target, type)); // registry.get(target).getCallSites().add(callSite); // } // // public int numberOfRegisteredCallSites() { // return registry.size(); // } // // public Set<String> callSiteKeys() { // return registry.keySet(); // } // // public Registration callSiteRegistrationFor(String key) { // return registry.get(key); // } // // public String callSiteTypeFor(String key) { // return registry.get(key).getType(); // } // // public Set<CallSite> callSitesFor(String key) { // return registry.get(key).getCallSites(); // } // }
import fr.insalyon.telecom.jooflux.internal.Aspects; import fr.insalyon.telecom.jooflux.internal.CallSiteRegistry; import org.pmw.tinylog.Logger; import java.lang.invoke.CallSite; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.util.Set;
throw new IllegalArgumentException("Wrong method type: " + methodType); } if (handle != null) { Set<CallSite> sites = registry.callSitesFor(oldTarget); if (sites != null) { for (CallSite site : sites) { site.setTarget(handle); } } else { throw new RuntimeException("There are no call sites for: " + oldTarget); } } else { throw new RuntimeException("Could not get the method handle: " + cls + "." + newMethodName + ":" + newTypeName); } } catch (Throwable t) { t.printStackTrace(); } } @Override public void applyBeforeAspect(String callSitesKey, String aspectClass, String aspectMethod) { try { Class<?> klass = getClass().getClassLoader().loadClass(aspectClass); MethodHandles.Lookup lookup = MethodHandles.lookup(); MethodHandle handle = lookup.findStatic(klass, aspectMethod, MethodType.methodType(Object[].class, Object[].class)); Set<CallSite> callSites = registry.callSitesFor(callSitesKey); if (callSites == null) { throw new IllegalArgumentException("No call sites have been registered for key: " + callSitesKey); } for (CallSite callSite : callSites) {
// Path: src/main/java/fr/insalyon/telecom/jooflux/internal/Aspects.java // public class Aspects { // // public static MethodHandle before(MethodHandle target, MethodHandle beforeFilter) { // MethodType targetType = target.type(); // MethodType filterType = beforeFilter.type(); // int parameterCount = targetType.parameterCount(); // // if (filterType.parameterCount() != 1 && !filterType.parameterType(0).equals(Object[].class)) { // throw new IllegalArgumentException("beforeFilter must have a single argument of type Object[]"); // } // if (!filterType.returnType().equals(Object[].class)) { // throw new IllegalArgumentException("beforeFilter must have a Object[] return type"); // } // // MethodHandle spreader = target.asSpreader(Object[].class, parameterCount); // MethodHandle filter = filterArguments(spreader, 0, beforeFilter); // MethodHandle collector = filter.asCollector(Object[].class, parameterCount); // // return collector.asType(targetType); // // } // // public static MethodHandle after(MethodHandle target, MethodHandle afterFilter) { // MethodType targetType = target.type(); // MethodType filterType = afterFilter.type(); // // if (filterType.parameterCount() != 1 && !filterType.parameterType(0).equals(Object.class)) { // throw new IllegalArgumentException("afterFilter must have a single argument of type Object"); // } // if (!filterType.returnType().equals(Object.class)) { // throw new IllegalArgumentException("afterFilter must have a Object return type"); // } // // MethodHandle asObject = target.asType(targetType.changeReturnType(Object.class)); // MethodHandle filter = filterReturnValue(asObject, afterFilter); // // return filter.asType(targetType); // } // } // // Path: src/main/java/fr/insalyon/telecom/jooflux/internal/CallSiteRegistry.java // public class CallSiteRegistry { // // private CallSiteRegistry() { // super(); // } // // // Thread-safe thanks to the JVM internals! // private static class CallSiteRegistrySingletonHolder { // private static final CallSiteRegistry instance = new CallSiteRegistry(); // } // // public static CallSiteRegistry getInstance() { // return CallSiteRegistrySingletonHolder.instance; // } // // private final ConcurrentHashMap<String, Registration> registry = new ConcurrentHashMap<>(); // // public void put(String target, String type, CallSite callSite) { // registry.putIfAbsent(target, new Registration(target, type)); // registry.get(target).getCallSites().add(callSite); // } // // public int numberOfRegisteredCallSites() { // return registry.size(); // } // // public Set<String> callSiteKeys() { // return registry.keySet(); // } // // public Registration callSiteRegistrationFor(String key) { // return registry.get(key); // } // // public String callSiteTypeFor(String key) { // return registry.get(key).getType(); // } // // public Set<CallSite> callSitesFor(String key) { // return registry.get(key).getCallSites(); // } // } // Path: src/main/java/fr/insalyon/telecom/jooflux/internal/jmx/JooFluxManagement.java import fr.insalyon.telecom.jooflux.internal.Aspects; import fr.insalyon.telecom.jooflux.internal.CallSiteRegistry; import org.pmw.tinylog.Logger; import java.lang.invoke.CallSite; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.util.Set; throw new IllegalArgumentException("Wrong method type: " + methodType); } if (handle != null) { Set<CallSite> sites = registry.callSitesFor(oldTarget); if (sites != null) { for (CallSite site : sites) { site.setTarget(handle); } } else { throw new RuntimeException("There are no call sites for: " + oldTarget); } } else { throw new RuntimeException("Could not get the method handle: " + cls + "." + newMethodName + ":" + newTypeName); } } catch (Throwable t) { t.printStackTrace(); } } @Override public void applyBeforeAspect(String callSitesKey, String aspectClass, String aspectMethod) { try { Class<?> klass = getClass().getClassLoader().loadClass(aspectClass); MethodHandles.Lookup lookup = MethodHandles.lookup(); MethodHandle handle = lookup.findStatic(klass, aspectMethod, MethodType.methodType(Object[].class, Object[].class)); Set<CallSite> callSites = registry.callSitesFor(callSitesKey); if (callSites == null) { throw new IllegalArgumentException("No call sites have been registered for key: " + callSitesKey); } for (CallSite callSite : callSites) {
callSite.setTarget(Aspects.before(callSite.getTarget(), handle));
dynamid/jooflux
src/main/java/fr/insalyon/telecom/jooflux/InvokeMethodTransformer.java
// Path: src/main/java/fr/insalyon/telecom/jooflux/internal/JooFluxUtils.java // public class JooFluxUtils { // // public static final boolean INTERCEPT_CONSTRUCTOR = false; // public static final boolean INTERCEPT_INVOKESTATIC = true; // public static final boolean INTERCEPT_INVOKEVIRTUAL = true; // public static final boolean INTERCEPT_INVOKEINTERFACE = true; // public static final boolean INTERCEPT_INVOKESPECIAL = false; // // public static Class<?> classDefinition(MethodHandles.Lookup lookup, String name) throws ClassNotFoundException { // ClassLoader classLoader = lookup.lookupClass().getClassLoader(); // return Class.forName(name, true, classLoader); // } // // public static enum InvocationType { // INVOKECONSTRUCTOR("constructor"), // INVOKESTATIC("static"), // INVOKEVIRTUAL("virtual"), // INVOKEINTERFACE("virtual"), // INVOKESPECIAL("special"); // // private final String command; // // private InvocationType(String command) { // this.command = command; // } // // public String command() { // return command; // } // } // // private static final Map<InvocationType, Boolean> REGISTER = new HashMap<InvocationType, Boolean>() { // { // put(InvocationType.INVOKECONSTRUCTOR, true); // put(InvocationType.INVOKESTATIC, true); // put(InvocationType.INVOKEVIRTUAL, true); // put(InvocationType.INVOKEINTERFACE, true); // put(InvocationType.INVOKESPECIAL, true); // } // }; // // public static String extractPackageName(String name) { // return name.split("\\.")[0].replace('/', '.'); // } // // public static String extractMethodName(String name) { // return name.split("\\.")[1]; // } // // public static void registerCallSite(CallSite callSite, InvocationType invocationType, String name, String type) { // if (REGISTER.get(invocationType)) { // Logger.info("Registered:" + name + ":" + type + " => " + callSite.getTarget().toString()); // CallSiteRegistry.getInstance().put(callSiteId(name, type), invocationType.command(), callSite); // } // } // // private static String callSiteId(String name, String type) { // return name + ":" + type; // } // // public static CallSite makeCallSiteAndRegister(InvocationType invocationType, String name, String type, MethodHandle methodHandle) { // VolatileCallSite callSite = new VolatileCallSite(methodHandle); // if (REGISTER.get(invocationType)) { // Logger.info("Registered:" + name + ":" + type + " => " + methodHandle.toString()); // CallSiteRegistry.getInstance().put(callSiteId(name, type), invocationType.command(), callSite); // } // return callSite; // } // }
import fr.insalyon.telecom.jooflux.internal.JooFluxUtils; import org.objectweb.asm.Handle; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.*; import org.pmw.tinylog.Logger; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List;
/* * JooFlux * * Copyright (c) 2012 Institut National des Sciences Appliquées de Lyon (INSA-Lyon) * Copyright (c) 2012 Julien Ponge, INSA-Lyon * Copyright (c) 2012 Frédéric Le Mouël, INSA-Lyon * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package fr.insalyon.telecom.jooflux; public class InvokeMethodTransformer extends MethodTransformer { private static final String BOOTSTRAP_CLASS = "fr/insalyon/telecom/jooflux/InvokeBootstrap"; private static final String BOOTSTRAP_SIGNATURE = "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;"; private static long totalMethodTransformed; public InvokeMethodTransformer(MethodTransformer methodTransformer) { super(methodTransformer); } @Override public void transform(MethodNode methodNode) { @SuppressWarnings("unchecked") Iterator<AbstractInsnNode> iterator = methodNode.instructions.iterator(); while (iterator.hasNext()) { AbstractInsnNode insnNode = iterator.next(); if (!(insnNode instanceof MethodInsnNode)) { continue; } MethodInsnNode methodInsnNode = (MethodInsnNode) insnNode; if (!InvokeClassFilter.isAllowed(methodInsnNode.owner)) { Logger.info("Filtered (method): " + methodInsnNode.owner + "#" + methodInsnNode.name); continue; }
// Path: src/main/java/fr/insalyon/telecom/jooflux/internal/JooFluxUtils.java // public class JooFluxUtils { // // public static final boolean INTERCEPT_CONSTRUCTOR = false; // public static final boolean INTERCEPT_INVOKESTATIC = true; // public static final boolean INTERCEPT_INVOKEVIRTUAL = true; // public static final boolean INTERCEPT_INVOKEINTERFACE = true; // public static final boolean INTERCEPT_INVOKESPECIAL = false; // // public static Class<?> classDefinition(MethodHandles.Lookup lookup, String name) throws ClassNotFoundException { // ClassLoader classLoader = lookup.lookupClass().getClassLoader(); // return Class.forName(name, true, classLoader); // } // // public static enum InvocationType { // INVOKECONSTRUCTOR("constructor"), // INVOKESTATIC("static"), // INVOKEVIRTUAL("virtual"), // INVOKEINTERFACE("virtual"), // INVOKESPECIAL("special"); // // private final String command; // // private InvocationType(String command) { // this.command = command; // } // // public String command() { // return command; // } // } // // private static final Map<InvocationType, Boolean> REGISTER = new HashMap<InvocationType, Boolean>() { // { // put(InvocationType.INVOKECONSTRUCTOR, true); // put(InvocationType.INVOKESTATIC, true); // put(InvocationType.INVOKEVIRTUAL, true); // put(InvocationType.INVOKEINTERFACE, true); // put(InvocationType.INVOKESPECIAL, true); // } // }; // // public static String extractPackageName(String name) { // return name.split("\\.")[0].replace('/', '.'); // } // // public static String extractMethodName(String name) { // return name.split("\\.")[1]; // } // // public static void registerCallSite(CallSite callSite, InvocationType invocationType, String name, String type) { // if (REGISTER.get(invocationType)) { // Logger.info("Registered:" + name + ":" + type + " => " + callSite.getTarget().toString()); // CallSiteRegistry.getInstance().put(callSiteId(name, type), invocationType.command(), callSite); // } // } // // private static String callSiteId(String name, String type) { // return name + ":" + type; // } // // public static CallSite makeCallSiteAndRegister(InvocationType invocationType, String name, String type, MethodHandle methodHandle) { // VolatileCallSite callSite = new VolatileCallSite(methodHandle); // if (REGISTER.get(invocationType)) { // Logger.info("Registered:" + name + ":" + type + " => " + methodHandle.toString()); // CallSiteRegistry.getInstance().put(callSiteId(name, type), invocationType.command(), callSite); // } // return callSite; // } // } // Path: src/main/java/fr/insalyon/telecom/jooflux/InvokeMethodTransformer.java import fr.insalyon.telecom.jooflux.internal.JooFluxUtils; import org.objectweb.asm.Handle; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.*; import org.pmw.tinylog.Logger; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; /* * JooFlux * * Copyright (c) 2012 Institut National des Sciences Appliquées de Lyon (INSA-Lyon) * Copyright (c) 2012 Julien Ponge, INSA-Lyon * Copyright (c) 2012 Frédéric Le Mouël, INSA-Lyon * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package fr.insalyon.telecom.jooflux; public class InvokeMethodTransformer extends MethodTransformer { private static final String BOOTSTRAP_CLASS = "fr/insalyon/telecom/jooflux/InvokeBootstrap"; private static final String BOOTSTRAP_SIGNATURE = "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;"; private static long totalMethodTransformed; public InvokeMethodTransformer(MethodTransformer methodTransformer) { super(methodTransformer); } @Override public void transform(MethodNode methodNode) { @SuppressWarnings("unchecked") Iterator<AbstractInsnNode> iterator = methodNode.instructions.iterator(); while (iterator.hasNext()) { AbstractInsnNode insnNode = iterator.next(); if (!(insnNode instanceof MethodInsnNode)) { continue; } MethodInsnNode methodInsnNode = (MethodInsnNode) insnNode; if (!InvokeClassFilter.isAllowed(methodInsnNode.owner)) { Logger.info("Filtered (method): " + methodInsnNode.owner + "#" + methodInsnNode.name); continue; }
if (JooFluxUtils.INTERCEPT_CONSTRUCTOR && isInvokeConstructor(methodInsnNode)) {
dynamid/jooflux
src/main/java/fr/insalyon/telecom/jooflux/tcp/WorkerRunnable.java
// Path: src/main/java/fr/insalyon/telecom/jooflux/internal/jmx/JooFluxManagement.java // public class JooFluxManagement implements JooFluxManagementMXBean { // // private CallSiteRegistry registry = CallSiteRegistry.getInstance(); // // @Override // public String getName() { // return "JooFlux managed bean"; // } // // @Override // public int getNumberOfRegisteredCallSites() { // return registry.numberOfRegisteredCallSites(); // } // // @Override // public Set<String> getRegisteredCallSiteKeys() { // return registry.callSiteKeys(); // } // // @Override // public String getCallSiteType(String target) { // return registry.callSiteTypeFor(target); // } // // @Override // public void changeCallSiteTarget(String methodType, String oldTarget, String newTarget) { // String[] split = newTarget.split("\\."); // String newClassName = split[0].replaceAll("/", "."); // split = split[1].split(":"); // String newMethodName = split[0]; // String newTypeName = split[1]; // // split = oldTarget.split("\\."); // String oldClassName = split[0].replaceAll("/", "."); // split = split[1].split(":"); // String oldMethodName = split[0]; // String oldTypeName = split[1]; // // Logger.trace(oldClassName + " -> " + newClassName); // Logger.trace(oldMethodName + " -> " + newMethodName); // Logger.trace(oldTypeName + " -> " + newTypeName); // // try { // Class<?> cls = getClass().getClassLoader().loadClass(newClassName); // MethodType mt = MethodType.fromMethodDescriptorString(newTypeName, null); // MethodHandles.Lookup lookup = MethodHandles.lookup(); // MethodHandle handle = null; // switch (methodType) { // case "static": // handle = lookup.findStatic(cls, newMethodName, mt); // break; // case "virtual": // handle = lookup.findVirtual(cls, newMethodName, mt); // // System.out.println(handle); // // MethodType mttmp = handle.type(); // // handle = handle.asType(mttmp.changeParameterType(0, Class.forName(oldClassName))); // // System.out.println(handle); // break; // default: // throw new IllegalArgumentException("Wrong method type: " + methodType); // } // if (handle != null) { // Set<CallSite> sites = registry.callSitesFor(oldTarget); // if (sites != null) { // for (CallSite site : sites) { // site.setTarget(handle); // } // } else { // throw new RuntimeException("There are no call sites for: " + oldTarget); // } // } else { // throw new RuntimeException("Could not get the method handle: " + cls + "." + newMethodName + ":" + newTypeName); // } // } catch (Throwable t) { // t.printStackTrace(); // } // } // // @Override // public void applyBeforeAspect(String callSitesKey, String aspectClass, String aspectMethod) { // try { // Class<?> klass = getClass().getClassLoader().loadClass(aspectClass); // MethodHandles.Lookup lookup = MethodHandles.lookup(); // MethodHandle handle = lookup.findStatic(klass, aspectMethod, MethodType.methodType(Object[].class, Object[].class)); // Set<CallSite> callSites = registry.callSitesFor(callSitesKey); // if (callSites == null) { // throw new IllegalArgumentException("No call sites have been registered for key: " + callSitesKey); // } // for (CallSite callSite : callSites) { // callSite.setTarget(Aspects.before(callSite.getTarget(), handle)); // } // } catch (Throwable t) { // t.printStackTrace(); // } // } // // @Override // public void applyAfterAspect(String callSitesKey, String aspectClass, String aspectMethod) { // try { // Class<?> klass = getClass().getClassLoader().loadClass(aspectClass); // MethodHandles.Lookup lookup = MethodHandles.lookup(); // MethodHandle handle = lookup.findStatic(klass, aspectMethod, MethodType.methodType(Object.class, Object.class)); // Set<CallSite> callSites = registry.callSitesFor(callSitesKey); // if (callSites == null) { // throw new IllegalArgumentException("No call sites have been registered for key: " + callSitesKey); // } // for (CallSite callSite : callSites) { // callSite.setTarget(Aspects.after(callSite.getTarget(), handle)); // } // } catch (Throwable t) { // t.printStackTrace(); // } // } // }
import fr.insalyon.telecom.jooflux.internal.jmx.JooFluxManagement; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.Set;
/* * JooFlux * * Copyright (c) 2012 Institut National des Sciences Appliquées de Lyon (INSA-Lyon) * Copyright (c) 2012 Julien Ponge, INSA-Lyon * Copyright (c) 2012 Frédéric Le Mouël, INSA-Lyon * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package fr.insalyon.telecom.jooflux.tcp; public class WorkerRunnable implements Runnable { protected final static String END_OF_INSTRUCTION = "-QUIT-"; protected SocketChannel socketChannel = null;
// Path: src/main/java/fr/insalyon/telecom/jooflux/internal/jmx/JooFluxManagement.java // public class JooFluxManagement implements JooFluxManagementMXBean { // // private CallSiteRegistry registry = CallSiteRegistry.getInstance(); // // @Override // public String getName() { // return "JooFlux managed bean"; // } // // @Override // public int getNumberOfRegisteredCallSites() { // return registry.numberOfRegisteredCallSites(); // } // // @Override // public Set<String> getRegisteredCallSiteKeys() { // return registry.callSiteKeys(); // } // // @Override // public String getCallSiteType(String target) { // return registry.callSiteTypeFor(target); // } // // @Override // public void changeCallSiteTarget(String methodType, String oldTarget, String newTarget) { // String[] split = newTarget.split("\\."); // String newClassName = split[0].replaceAll("/", "."); // split = split[1].split(":"); // String newMethodName = split[0]; // String newTypeName = split[1]; // // split = oldTarget.split("\\."); // String oldClassName = split[0].replaceAll("/", "."); // split = split[1].split(":"); // String oldMethodName = split[0]; // String oldTypeName = split[1]; // // Logger.trace(oldClassName + " -> " + newClassName); // Logger.trace(oldMethodName + " -> " + newMethodName); // Logger.trace(oldTypeName + " -> " + newTypeName); // // try { // Class<?> cls = getClass().getClassLoader().loadClass(newClassName); // MethodType mt = MethodType.fromMethodDescriptorString(newTypeName, null); // MethodHandles.Lookup lookup = MethodHandles.lookup(); // MethodHandle handle = null; // switch (methodType) { // case "static": // handle = lookup.findStatic(cls, newMethodName, mt); // break; // case "virtual": // handle = lookup.findVirtual(cls, newMethodName, mt); // // System.out.println(handle); // // MethodType mttmp = handle.type(); // // handle = handle.asType(mttmp.changeParameterType(0, Class.forName(oldClassName))); // // System.out.println(handle); // break; // default: // throw new IllegalArgumentException("Wrong method type: " + methodType); // } // if (handle != null) { // Set<CallSite> sites = registry.callSitesFor(oldTarget); // if (sites != null) { // for (CallSite site : sites) { // site.setTarget(handle); // } // } else { // throw new RuntimeException("There are no call sites for: " + oldTarget); // } // } else { // throw new RuntimeException("Could not get the method handle: " + cls + "." + newMethodName + ":" + newTypeName); // } // } catch (Throwable t) { // t.printStackTrace(); // } // } // // @Override // public void applyBeforeAspect(String callSitesKey, String aspectClass, String aspectMethod) { // try { // Class<?> klass = getClass().getClassLoader().loadClass(aspectClass); // MethodHandles.Lookup lookup = MethodHandles.lookup(); // MethodHandle handle = lookup.findStatic(klass, aspectMethod, MethodType.methodType(Object[].class, Object[].class)); // Set<CallSite> callSites = registry.callSitesFor(callSitesKey); // if (callSites == null) { // throw new IllegalArgumentException("No call sites have been registered for key: " + callSitesKey); // } // for (CallSite callSite : callSites) { // callSite.setTarget(Aspects.before(callSite.getTarget(), handle)); // } // } catch (Throwable t) { // t.printStackTrace(); // } // } // // @Override // public void applyAfterAspect(String callSitesKey, String aspectClass, String aspectMethod) { // try { // Class<?> klass = getClass().getClassLoader().loadClass(aspectClass); // MethodHandles.Lookup lookup = MethodHandles.lookup(); // MethodHandle handle = lookup.findStatic(klass, aspectMethod, MethodType.methodType(Object.class, Object.class)); // Set<CallSite> callSites = registry.callSitesFor(callSitesKey); // if (callSites == null) { // throw new IllegalArgumentException("No call sites have been registered for key: " + callSitesKey); // } // for (CallSite callSite : callSites) { // callSite.setTarget(Aspects.after(callSite.getTarget(), handle)); // } // } catch (Throwable t) { // t.printStackTrace(); // } // } // } // Path: src/main/java/fr/insalyon/telecom/jooflux/tcp/WorkerRunnable.java import fr.insalyon.telecom.jooflux.internal.jmx.JooFluxManagement; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.Set; /* * JooFlux * * Copyright (c) 2012 Institut National des Sciences Appliquées de Lyon (INSA-Lyon) * Copyright (c) 2012 Julien Ponge, INSA-Lyon * Copyright (c) 2012 Frédéric Le Mouël, INSA-Lyon * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package fr.insalyon.telecom.jooflux.tcp; public class WorkerRunnable implements Runnable { protected final static String END_OF_INSTRUCTION = "-QUIT-"; protected SocketChannel socketChannel = null;
private JooFluxManagement jooFluxManagement;
IceReaper/DesktopAdventuresToolkit
src/net/eiveo/original/sections/todo/not_converted_yet/ZNAM.java
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // }
import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer;
package net.eiveo.original.sections.todo.not_converted_yet; public class ZNAM { private Map<Short, String> names = new LinkedHashMap<>();
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // } // Path: src/net/eiveo/original/sections/todo/not_converted_yet/ZNAM.java import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer; package net.eiveo.original.sections.todo.not_converted_yet; public class ZNAM { private Map<Short, String> names = new LinkedHashMap<>();
public static ZNAM read(SmartByteBuffer data) throws Exception {
IceReaper/DesktopAdventuresToolkit
src/net/eiveo/original/sections/todo/not_converted_yet/ZNAM.java
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // }
import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer;
package net.eiveo.original.sections.todo.not_converted_yet; public class ZNAM { private Map<Short, String> names = new LinkedHashMap<>(); public static ZNAM read(SmartByteBuffer data) throws Exception { ZNAM instance = new ZNAM(); int length = data.getInt(); int lengthStart = data.position(); while (true) { short zoneId = data.getShort(); if (zoneId == -1) { break; } else { int nameStart = data.position(); instance.names.put(zoneId, data.getString()); // Filled with trash - bug data.position(nameStart + 16); } } if (lengthStart + length != data.position()) { throw new Exception("Length mismatch."); } return instance; }
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // } // Path: src/net/eiveo/original/sections/todo/not_converted_yet/ZNAM.java import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer; package net.eiveo.original.sections.todo.not_converted_yet; public class ZNAM { private Map<Short, String> names = new LinkedHashMap<>(); public static ZNAM read(SmartByteBuffer data) throws Exception { ZNAM instance = new ZNAM(); int length = data.getInt(); int lengthStart = data.position(); while (true) { short zoneId = data.getShort(); if (zoneId == -1) { break; } else { int nameStart = data.position(); instance.names.put(zoneId, data.getString()); // Filled with trash - bug data.position(nameStart + 16); } } if (lengthStart + length != data.position()) { throw new Exception("Length mismatch."); } return instance; }
public void write(SmartByteArrayOutputStream outputStream) {
IceReaper/DesktopAdventuresToolkit
src/net/eiveo/original/sections/todo/determine_values/IZAX.java
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // }
import java.util.ArrayList; import java.util.List; import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer;
package net.eiveo.original.sections.todo.determine_values; public class IZAX { private short unk1; private List<Character> characters = new ArrayList<>(); private List<Short> tileId1 = new ArrayList<>(); private List<Short> tileId2 = new ArrayList<>();
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // } // Path: src/net/eiveo/original/sections/todo/determine_values/IZAX.java import java.util.ArrayList; import java.util.List; import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer; package net.eiveo.original.sections.todo.determine_values; public class IZAX { private short unk1; private List<Character> characters = new ArrayList<>(); private List<Short> tileId1 = new ArrayList<>(); private List<Short> tileId2 = new ArrayList<>();
public static IZAX read(SmartByteBuffer data, boolean isYoda) throws Exception {
IceReaper/DesktopAdventuresToolkit
src/net/eiveo/original/sections/todo/determine_values/IZAX.java
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // }
import java.util.ArrayList; import java.util.List; import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer;
package net.eiveo.original.sections.todo.determine_values; public class IZAX { private short unk1; private List<Character> characters = new ArrayList<>(); private List<Short> tileId1 = new ArrayList<>(); private List<Short> tileId2 = new ArrayList<>(); public static IZAX read(SmartByteBuffer data, boolean isYoda) throws Exception { IZAX instance = new IZAX(); // Somehow IZAX includes identifier and the length int into the length. int length = data.getInt() - 8; int lengthStart = data.position(); instance.unk1 = data.getShort(); // TODO 0 or 1 short amount = data.getShort(); for (int j = 0; j < amount; j++) { instance.characters.add(Character.read(data, isYoda)); } amount = data.getShort(); for (int j = 0; j < amount; j++) { instance.tileId1.add(data.getShort()); } if (isYoda) { amount = data.getShort(); for (int j = 0; j < amount; j++) { instance.tileId2.add(data.getShort()); } } if (lengthStart + length != data.position()) { throw new Exception("Length mismatch."); } return instance; }
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // } // Path: src/net/eiveo/original/sections/todo/determine_values/IZAX.java import java.util.ArrayList; import java.util.List; import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer; package net.eiveo.original.sections.todo.determine_values; public class IZAX { private short unk1; private List<Character> characters = new ArrayList<>(); private List<Short> tileId1 = new ArrayList<>(); private List<Short> tileId2 = new ArrayList<>(); public static IZAX read(SmartByteBuffer data, boolean isYoda) throws Exception { IZAX instance = new IZAX(); // Somehow IZAX includes identifier and the length int into the length. int length = data.getInt() - 8; int lengthStart = data.position(); instance.unk1 = data.getShort(); // TODO 0 or 1 short amount = data.getShort(); for (int j = 0; j < amount; j++) { instance.characters.add(Character.read(data, isYoda)); } amount = data.getShort(); for (int j = 0; j < amount; j++) { instance.tileId1.add(data.getShort()); } if (isYoda) { amount = data.getShort(); for (int j = 0; j < amount; j++) { instance.tileId2.add(data.getShort()); } } if (lengthStart + length != data.position()) { throw new Exception("Length mismatch."); } return instance; }
public void write(SmartByteArrayOutputStream outputStream, boolean isYoda) {
IceReaper/DesktopAdventuresToolkit
src/net/eiveo/original/sections/todo/not_converted_yet/ANAM.java
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // }
import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer;
package net.eiveo.original.sections.todo.not_converted_yet; public class ANAM { private Map<Short, Map<Short, String>> names = new LinkedHashMap<>();
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // } // Path: src/net/eiveo/original/sections/todo/not_converted_yet/ANAM.java import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer; package net.eiveo.original.sections.todo.not_converted_yet; public class ANAM { private Map<Short, Map<Short, String>> names = new LinkedHashMap<>();
public static ANAM read(SmartByteBuffer data) throws Exception {
IceReaper/DesktopAdventuresToolkit
src/net/eiveo/original/sections/todo/not_converted_yet/ANAM.java
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // }
import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer;
package net.eiveo.original.sections.todo.not_converted_yet; public class ANAM { private Map<Short, Map<Short, String>> names = new LinkedHashMap<>(); public static ANAM read(SmartByteBuffer data) throws Exception { ANAM instance = new ANAM(); int length = data.getInt(); int lengthStart = data.position(); while (true) { short zoneId = data.getShort(); if (zoneId == -1) { break; } else { Map<Short, String> names = new LinkedHashMap<>(); instance.names.put(zoneId, names); while (true) { short actionId = data.getShort(); if (actionId == -1) { break; } else { names.put(actionId, data.getString(-1, 16).trim()); } } } } if (lengthStart + length != data.position()) { throw new Exception("Length mismatch."); } return instance; }
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // } // Path: src/net/eiveo/original/sections/todo/not_converted_yet/ANAM.java import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer; package net.eiveo.original.sections.todo.not_converted_yet; public class ANAM { private Map<Short, Map<Short, String>> names = new LinkedHashMap<>(); public static ANAM read(SmartByteBuffer data) throws Exception { ANAM instance = new ANAM(); int length = data.getInt(); int lengthStart = data.position(); while (true) { short zoneId = data.getShort(); if (zoneId == -1) { break; } else { Map<Short, String> names = new LinkedHashMap<>(); instance.names.put(zoneId, names); while (true) { short actionId = data.getShort(); if (actionId == -1) { break; } else { names.put(actionId, data.getString(-1, 16).trim()); } } } } if (lengthStart + length != data.position()) { throw new Exception("Length mismatch."); } return instance; }
public void write(SmartByteArrayOutputStream outputStream) {
IceReaper/DesktopAdventuresToolkit
src/net/eiveo/original/sections/STUP.java
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // }
import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer;
package net.eiveo.original.sections; public class STUP { public byte[] image = new byte[9 * 32 * 9 * 32];
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // } // Path: src/net/eiveo/original/sections/STUP.java import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer; package net.eiveo.original.sections; public class STUP { public byte[] image = new byte[9 * 32 * 9 * 32];
public static STUP read(SmartByteBuffer data) throws Exception {
IceReaper/DesktopAdventuresToolkit
src/net/eiveo/original/sections/STUP.java
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // }
import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer;
package net.eiveo.original.sections; public class STUP { public byte[] image = new byte[9 * 32 * 9 * 32]; public static STUP read(SmartByteBuffer data) throws Exception { STUP instance = new STUP(); int length = data.getInt(); int lengthStart = data.position(); data.get(instance.image); if (lengthStart + length != data.position()) { throw new Exception("Length mismatch."); } return instance; }
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // } // Path: src/net/eiveo/original/sections/STUP.java import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer; package net.eiveo.original.sections; public class STUP { public byte[] image = new byte[9 * 32 * 9 * 32]; public static STUP read(SmartByteBuffer data) throws Exception { STUP instance = new STUP(); int length = data.getInt(); int lengthStart = data.position(); data.get(instance.image); if (lengthStart + length != data.position()) { throw new Exception("Length mismatch."); } return instance; }
public void write(SmartByteArrayOutputStream outputStream) {
IceReaper/DesktopAdventuresToolkit
src/net/eiveo/original/sections/todo/determine_values/IZX4.java
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // }
import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer;
package net.eiveo.original.sections.todo.determine_values; public class IZX4 { private short unk;
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // } // Path: src/net/eiveo/original/sections/todo/determine_values/IZX4.java import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer; package net.eiveo.original.sections.todo.determine_values; public class IZX4 { private short unk;
public static IZX4 read(SmartByteBuffer data) throws Exception {
IceReaper/DesktopAdventuresToolkit
src/net/eiveo/original/sections/todo/determine_values/IZX4.java
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // }
import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer;
package net.eiveo.original.sections.todo.determine_values; public class IZX4 { private short unk; public static IZX4 read(SmartByteBuffer data) throws Exception { IZX4 instance = new IZX4(); int length = data.getInt(); int lengthStart = data.position(); instance.unk = data.getShort(); // TODO mostly 1, sometimes 0 if (lengthStart + length != data.position()) { throw new Exception("Length mismatch."); } return instance; }
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // } // Path: src/net/eiveo/original/sections/todo/determine_values/IZX4.java import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer; package net.eiveo.original.sections.todo.determine_values; public class IZX4 { private short unk; public static IZX4 read(SmartByteBuffer data) throws Exception { IZX4 instance = new IZX4(); int length = data.getInt(); int lengthStart = data.position(); instance.unk = data.getShort(); // TODO mostly 1, sometimes 0 if (lengthStart + length != data.position()) { throw new Exception("Length mismatch."); } return instance; }
public void write(SmartByteArrayOutputStream outputStream) {
IceReaper/DesktopAdventuresToolkit
src/net/eiveo/original/sections/todo/determine_values/IACT.java
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // }
import java.util.ArrayList; import java.util.List; import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer;
package net.eiveo.original.sections.todo.determine_values; public class IACT { private List<Condition> conditions = new ArrayList<>(); private List<Action> actions = new ArrayList<>();
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // } // Path: src/net/eiveo/original/sections/todo/determine_values/IACT.java import java.util.ArrayList; import java.util.List; import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer; package net.eiveo.original.sections.todo.determine_values; public class IACT { private List<Condition> conditions = new ArrayList<>(); private List<Action> actions = new ArrayList<>();
public static IACT read(SmartByteBuffer data, boolean isYoda) throws Exception {
IceReaper/DesktopAdventuresToolkit
src/net/eiveo/original/sections/todo/determine_values/IACT.java
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // }
import java.util.ArrayList; import java.util.List; import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer;
package net.eiveo.original.sections.todo.determine_values; public class IACT { private List<Condition> conditions = new ArrayList<>(); private List<Action> actions = new ArrayList<>(); public static IACT read(SmartByteBuffer data, boolean isYoda) throws Exception { IACT instance = new IACT(); // TODO: https://github.com/cyco/DeskFun/blob/master/dfengine/include/Action.hpp // https://github.com/a-kr/jsyoda/blob/master/yodesk_decompiler/GenView/Script.cs int length = data.getInt(); int lengthStart = data.position(); short amount = data.getShort(); for (int i = 0; i < amount; i++) { instance.conditions.add(Condition.read(data)); } amount = data.getShort(); for (int i = 0; i < amount; i++) { instance.actions.add(Action.read(data)); } if (isYoda && lengthStart + length != data.position()) { throw new Exception("Length mismatch."); } return instance; }
// Path: src/net/eiveo/utils/SmartByteArrayOutputStream.java // public class SmartByteArrayOutputStream { // private List<ByteArrayOutputStream> sections = new ArrayList<>(); // private ByteArrayOutputStream section; // // public SmartByteArrayOutputStream() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public void sectionStart() { // this.section = new ByteArrayOutputStream(); // this.sections.add(this.section); // } // // public byte[] sectionEnd() { // byte[] result = this.section.toByteArray(); // sections.remove(sections.size() - 1); // this.section = sections.get(sections.size() - 1); // return result; // } // // public byte[] toByteArray() { // return this.section.toByteArray(); // } // // public void write(String string) { // for (byte byteData : string.getBytes()) { // this.section.write(byteData); // } // } // // public void write(byte value) { // this.section.write(value); // } // // public void write(byte[] value) { // for (byte byteData : value) { // this.section.write(byteData); // } // } // // public void write(short value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8) // }) { // this.section.write(byteData); // } // } // // public void write(int value) { // for (byte byteData : new byte[] { // (byte) value, // (byte)(value >> 8), // (byte)(value >> 16), // (byte)(value >> 24) // }) { // this.section.write(byteData); // } // } // } // // Path: src/net/eiveo/utils/SmartByteBuffer.java // public class SmartByteBuffer { // private ByteBuffer byteBuffer; // // public int capacity() { // return this.byteBuffer.capacity(); // } // // public byte get() { // return this.byteBuffer.get(); // } // // public void get(byte[] dst) { // this.byteBuffer.get(dst); // } // // public int getInt() { // return this.byteBuffer.getInt(); // } // // public short getShort() { // return this.byteBuffer.getShort(); // } // // public String getString() { // String string = ""; // // while (true) { // byte character = this.get(); // if ((character & 0xff) == 0) { // break; // } else { // string += new String(new byte[] { character }); // } // } // // return string; // } // // public String getString(int index, int length) { // byte[] output = new byte[length]; // if (index > -1) { // this.position(index); // } // this.byteBuffer.get(output); // return new String(output); // } // // public void order(ByteOrder bo) { // this.byteBuffer.order(bo); // } // // public int position() { // return this.byteBuffer.position(); // } // // public void position(int newPosition) { // this.byteBuffer.position(newPosition); // } // // public static SmartByteBuffer wrap(byte[] array) { // SmartByteBuffer instance = new SmartByteBuffer(); // instance.byteBuffer = ByteBuffer.wrap(array); // return instance; // } // } // Path: src/net/eiveo/original/sections/todo/determine_values/IACT.java import java.util.ArrayList; import java.util.List; import net.eiveo.utils.SmartByteArrayOutputStream; import net.eiveo.utils.SmartByteBuffer; package net.eiveo.original.sections.todo.determine_values; public class IACT { private List<Condition> conditions = new ArrayList<>(); private List<Action> actions = new ArrayList<>(); public static IACT read(SmartByteBuffer data, boolean isYoda) throws Exception { IACT instance = new IACT(); // TODO: https://github.com/cyco/DeskFun/blob/master/dfengine/include/Action.hpp // https://github.com/a-kr/jsyoda/blob/master/yodesk_decompiler/GenView/Script.cs int length = data.getInt(); int lengthStart = data.position(); short amount = data.getShort(); for (int i = 0; i < amount; i++) { instance.conditions.add(Condition.read(data)); } amount = data.getShort(); for (int i = 0; i < amount; i++) { instance.actions.add(Action.read(data)); } if (isYoda && lengthStart + length != data.position()) { throw new Exception("Length mismatch."); } return instance; }
public void write(SmartByteArrayOutputStream outputStream, boolean isYoda) {