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
vbier/habpanelviewer
app/src/main/java/de/vier_bier/habpanelviewer/openhab/average/AveragePropagator.java
// Path: app/src/main/java/de/vier_bier/habpanelviewer/openhab/FutureState.java // public class FutureState extends ItemState implements Delayed { // private final int delayInMillis; // private long origin = System.currentTimeMillis(); // // public FutureState(String item, int interval, String state) { // super(item, state); // // delayInMillis = interval * 1000; // // resetTime(); // } // // public void resetTime() { // origin = System.currentTimeMillis(); // } // // @Override // public long getDelay(@NonNull TimeUnit timeUnit) { // return timeUnit.convert(delayInMillis - (System.currentTimeMillis() - origin), TimeUnit.MILLISECONDS); // } // // @Override // public int compareTo(@NonNull Delayed delayed) { // if (delayed == this) { // return 0; // } // // return Long.compare(getDelay(TimeUnit.MILLISECONDS), delayed.getDelay(TimeUnit.MILLISECONDS)); // } // // @Override // public boolean equals(Object obj) { // return obj instanceof FutureState && mItemName.equals(((FutureState) obj).mItemName); // } // }
import java.util.HashMap; import java.util.concurrent.BlockingQueue; import java.util.concurrent.DelayQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import de.vier_bier.habpanelviewer.openhab.FutureState;
package de.vier_bier.habpanelviewer.openhab.average; /** * Thread that does cyclic propagation of state averages or timed state updates */ public class AveragePropagator extends Thread { private final IStatePropagator mStatePropagator; private final AtomicBoolean mRunning = new AtomicBoolean(true); private final BlockingQueue<Average> mAvgQueue = new DelayQueue<>(); private final HashMap<String, Average> mAverages = new HashMap<>();
// Path: app/src/main/java/de/vier_bier/habpanelviewer/openhab/FutureState.java // public class FutureState extends ItemState implements Delayed { // private final int delayInMillis; // private long origin = System.currentTimeMillis(); // // public FutureState(String item, int interval, String state) { // super(item, state); // // delayInMillis = interval * 1000; // // resetTime(); // } // // public void resetTime() { // origin = System.currentTimeMillis(); // } // // @Override // public long getDelay(@NonNull TimeUnit timeUnit) { // return timeUnit.convert(delayInMillis - (System.currentTimeMillis() - origin), TimeUnit.MILLISECONDS); // } // // @Override // public int compareTo(@NonNull Delayed delayed) { // if (delayed == this) { // return 0; // } // // return Long.compare(getDelay(TimeUnit.MILLISECONDS), delayed.getDelay(TimeUnit.MILLISECONDS)); // } // // @Override // public boolean equals(Object obj) { // return obj instanceof FutureState && mItemName.equals(((FutureState) obj).mItemName); // } // } // Path: app/src/main/java/de/vier_bier/habpanelviewer/openhab/average/AveragePropagator.java import java.util.HashMap; import java.util.concurrent.BlockingQueue; import java.util.concurrent.DelayQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import de.vier_bier.habpanelviewer.openhab.FutureState; package de.vier_bier.habpanelviewer.openhab.average; /** * Thread that does cyclic propagation of state averages or timed state updates */ public class AveragePropagator extends Thread { private final IStatePropagator mStatePropagator; private final AtomicBoolean mRunning = new AtomicBoolean(true); private final BlockingQueue<Average> mAvgQueue = new DelayQueue<>(); private final HashMap<String, Average> mAverages = new HashMap<>();
private final BlockingQueue<FutureState> mFutureStateQueue = new DelayQueue<>();
vbier/habpanelviewer
app/src/main/java/de/vier_bier/habpanelviewer/connection/ConnectionStatistics.java
// Path: app/src/main/java/de/vier_bier/habpanelviewer/status/ApplicationStatus.java // public class ApplicationStatus { // private final ArrayList<StatusItem> mValues = new ArrayList<>(); // private final HashMap<String, StatusItem> mIndices = new HashMap<>(); // // public synchronized void set(String key, String value) { // StatusItem item = mIndices.get(key); // if (item == null) { // item = new StatusItem(key, value); // mValues.add(item); // mIndices.put(key, item); // } else { // item.setValue(value); // } // } // // int getItemCount() { // return mValues.size(); // } // // StatusItem getItem(int i) { // return mValues.get(i); // } // }
import android.content.Context; import android.content.res.Resources; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import de.vier_bier.habpanelviewer.R; import de.vier_bier.habpanelviewer.status.ApplicationStatus;
package de.vier_bier.habpanelviewer.connection; /** * Holds information about online/offline times. */ public class ConnectionStatistics { private final Context mCtx; private final long mStartTime = System.currentTimeMillis(); private State mState = State.DISCONNECTED; private long mLastOnlineTime = -1; private long mLastOfflineTime = mStartTime; private long mOfflinePeriods = 0; private long mOfflineMillis = 0; private long mOfflineMaxMillis = 0; private long mOfflineAverage = 0; private long mOnlinePeriods = 0; private long mOnlineMillis = 0; private long mOnlineMaxMillis = 0; private long mOnlineAverage = 0; public ConnectionStatistics(Context context) { mCtx = context; EventBus.getDefault().register(this); } @Subscribe(threadMode = ThreadMode.MAIN)
// Path: app/src/main/java/de/vier_bier/habpanelviewer/status/ApplicationStatus.java // public class ApplicationStatus { // private final ArrayList<StatusItem> mValues = new ArrayList<>(); // private final HashMap<String, StatusItem> mIndices = new HashMap<>(); // // public synchronized void set(String key, String value) { // StatusItem item = mIndices.get(key); // if (item == null) { // item = new StatusItem(key, value); // mValues.add(item); // mIndices.put(key, item); // } else { // item.setValue(value); // } // } // // int getItemCount() { // return mValues.size(); // } // // StatusItem getItem(int i) { // return mValues.get(i); // } // } // Path: app/src/main/java/de/vier_bier/habpanelviewer/connection/ConnectionStatistics.java import android.content.Context; import android.content.res.Resources; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import de.vier_bier.habpanelviewer.R; import de.vier_bier.habpanelviewer.status.ApplicationStatus; package de.vier_bier.habpanelviewer.connection; /** * Holds information about online/offline times. */ public class ConnectionStatistics { private final Context mCtx; private final long mStartTime = System.currentTimeMillis(); private State mState = State.DISCONNECTED; private long mLastOnlineTime = -1; private long mLastOfflineTime = mStartTime; private long mOfflinePeriods = 0; private long mOfflineMillis = 0; private long mOfflineMaxMillis = 0; private long mOfflineAverage = 0; private long mOnlinePeriods = 0; private long mOnlineMillis = 0; private long mOnlineMaxMillis = 0; private long mOnlineAverage = 0; public ConnectionStatistics(Context context) { mCtx = context; EventBus.getDefault().register(this); } @Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(ApplicationStatus status) {
vbier/habpanelviewer
app/src/main/java/de/vier_bier/habpanelviewer/preferences/ItemValidator.java
// Path: app/src/main/java/de/vier_bier/habpanelviewer/connection/OkHttpClientFactory.java // public class OkHttpClientFactory { // private static OkHttpClientFactory ourInstance; // // public Credentials mCred = null; // private String mHost; // private String mRealm; // // public static synchronized OkHttpClientFactory getInstance() { // if (ourInstance == null) { // ourInstance = new OkHttpClientFactory(); // } // return ourInstance; // } // // public OkHttpClient create() { // OkHttpClient.Builder builder = new OkHttpClient.Builder().readTimeout(0, TimeUnit.SECONDS); // // builder.sslSocketFactory(CertificateManager.getInstance().getSocketFactory(), // CertificateManager.getInstance().getTrustManager()) // .hostnameVerifier((s, session) -> { // try { // Certificate[] certificates = session.getPeerCertificates(); // for (Certificate certificate : certificates) { // if (!(certificate instanceof X509Certificate)) { // return false; // } // if (CertificateManager.getInstance().isTrusted((X509Certificate) certificate)) { // return true; // } // } // } catch (SSLException e) { // // return false; // } // return false; // }); // // if (mCred != null) { // // create a copy so it can not be nulled again // Credentials copy = new Credentials(mCred.getUserName(), mCred.getPassword()); // // final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>(); // final BasicAuthenticator basicAuthenticator = new BasicAuthenticator(copy); // final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(copy); // // // note that all auth schemes should be registered as lowercase! // DispatchingAuthenticator authenticator = new DispatchingAuthenticator.Builder() // .with("digest", digestAuthenticator) // .with("basic", basicAuthenticator) // .build(); // // builder.authenticator(new CachingAuthenticatorDecorator(authenticator, authCache)) // .addInterceptor(new AuthenticationCacheInterceptor(authCache)); // } // // return builder.build(); // } // // public void setAuth(String user, String pass) { // mCred = new Credentials(user, pass); // } // // public void removeAuth() { // mCred = null; // } // // public void setHost(String host) { // mHost = host; // } // // public void setRealm(String realm) { // mRealm = realm; // } // // public String getHost() { // return mHost; // } // // public String getRealm() { // return mRealm; // } // }
import android.util.Log; import org.jetbrains.annotations.NotNull; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; import de.vier_bier.habpanelviewer.connection.OkHttpClientFactory; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody;
package de.vier_bier.habpanelviewer.preferences; class ItemValidator { private static final String TAG = "HPV-ItemValidator"; private final List<String> mNames = new ArrayList<>(); void setServerUrl(String serverUrl, ValidationStateListener l) {
// Path: app/src/main/java/de/vier_bier/habpanelviewer/connection/OkHttpClientFactory.java // public class OkHttpClientFactory { // private static OkHttpClientFactory ourInstance; // // public Credentials mCred = null; // private String mHost; // private String mRealm; // // public static synchronized OkHttpClientFactory getInstance() { // if (ourInstance == null) { // ourInstance = new OkHttpClientFactory(); // } // return ourInstance; // } // // public OkHttpClient create() { // OkHttpClient.Builder builder = new OkHttpClient.Builder().readTimeout(0, TimeUnit.SECONDS); // // builder.sslSocketFactory(CertificateManager.getInstance().getSocketFactory(), // CertificateManager.getInstance().getTrustManager()) // .hostnameVerifier((s, session) -> { // try { // Certificate[] certificates = session.getPeerCertificates(); // for (Certificate certificate : certificates) { // if (!(certificate instanceof X509Certificate)) { // return false; // } // if (CertificateManager.getInstance().isTrusted((X509Certificate) certificate)) { // return true; // } // } // } catch (SSLException e) { // // return false; // } // return false; // }); // // if (mCred != null) { // // create a copy so it can not be nulled again // Credentials copy = new Credentials(mCred.getUserName(), mCred.getPassword()); // // final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>(); // final BasicAuthenticator basicAuthenticator = new BasicAuthenticator(copy); // final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(copy); // // // note that all auth schemes should be registered as lowercase! // DispatchingAuthenticator authenticator = new DispatchingAuthenticator.Builder() // .with("digest", digestAuthenticator) // .with("basic", basicAuthenticator) // .build(); // // builder.authenticator(new CachingAuthenticatorDecorator(authenticator, authCache)) // .addInterceptor(new AuthenticationCacheInterceptor(authCache)); // } // // return builder.build(); // } // // public void setAuth(String user, String pass) { // mCred = new Credentials(user, pass); // } // // public void removeAuth() { // mCred = null; // } // // public void setHost(String host) { // mHost = host; // } // // public void setRealm(String realm) { // mRealm = realm; // } // // public String getHost() { // return mHost; // } // // public String getRealm() { // return mRealm; // } // } // Path: app/src/main/java/de/vier_bier/habpanelviewer/preferences/ItemValidator.java import android.util.Log; import org.jetbrains.annotations.NotNull; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; import de.vier_bier.habpanelviewer.connection.OkHttpClientFactory; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; package de.vier_bier.habpanelviewer.preferences; class ItemValidator { private static final String TAG = "HPV-ItemValidator"; private final List<String> mNames = new ArrayList<>(); void setServerUrl(String serverUrl, ValidationStateListener l) {
OkHttpClient client = OkHttpClientFactory.getInstance().create();
jbush001/WaveView
src/test/java/BitValueTest.java
// Path: src/main/java/waveview/wavedata/BitValue.java // public enum BitValue { // ZERO, // ONE, // X, // Z; // // private static final BitValue[] ORDINAL_TABLE = BitValue.values(); // // public static BitValue fromChar(char c) { // switch (c) { // case '0': // return ZERO; // case '1': // return ONE; // case 'x': // case 'X': // return X; // case 'z': // case 'Z': // return Z; // default: // throw new NumberFormatException("unknown digit " + c); // } // } // // public char toChar() { // switch (this) { // case ZERO: // return '0'; // case ONE: // return '1'; // case X: // return 'x'; // case Z: // return 'z'; // } // // return ' '; // Unreachable? // } // // public static BitValue fromInt(int i) { // if (i == 0) { // return ZERO; // } else { // return ONE; // } // } // // public int toInt() { // return (this == ONE) ? 1 : 0; // } // // public static BitValue fromOrdinal(int ord) { // return ORDINAL_TABLE[ord]; // } // // public BitValue invert() { // switch (this) { // case ZERO: // return ONE; // case ONE: // return ZERO; // case X: // return X; // case Z: // return X; // default: // return X; // Shouldn't happen // } // } // // public int compare(BitValue other) { // if (this == ONE && other == ZERO) { // return 1; // } else if (this == ZERO && other == ONE) { // return -1; // } else { // // Either these are equal, or there is an X and Z, which match // // everything. // return 0; // } // } // }
import static org.junit.Assert.assertEquals; import org.junit.Test; import waveview.wavedata.BitValue;
// // Copyright 2016 Jeff Bush // // 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. // public class BitValueTest { @Test public void fromChar() {
// Path: src/main/java/waveview/wavedata/BitValue.java // public enum BitValue { // ZERO, // ONE, // X, // Z; // // private static final BitValue[] ORDINAL_TABLE = BitValue.values(); // // public static BitValue fromChar(char c) { // switch (c) { // case '0': // return ZERO; // case '1': // return ONE; // case 'x': // case 'X': // return X; // case 'z': // case 'Z': // return Z; // default: // throw new NumberFormatException("unknown digit " + c); // } // } // // public char toChar() { // switch (this) { // case ZERO: // return '0'; // case ONE: // return '1'; // case X: // return 'x'; // case Z: // return 'z'; // } // // return ' '; // Unreachable? // } // // public static BitValue fromInt(int i) { // if (i == 0) { // return ZERO; // } else { // return ONE; // } // } // // public int toInt() { // return (this == ONE) ? 1 : 0; // } // // public static BitValue fromOrdinal(int ord) { // return ORDINAL_TABLE[ord]; // } // // public BitValue invert() { // switch (this) { // case ZERO: // return ONE; // case ONE: // return ZERO; // case X: // return X; // case Z: // return X; // default: // return X; // Shouldn't happen // } // } // // public int compare(BitValue other) { // if (this == ONE && other == ZERO) { // return 1; // } else if (this == ZERO && other == ONE) { // return -1; // } else { // // Either these are equal, or there is an X and Z, which match // // everything. // return 0; // } // } // } // Path: src/test/java/BitValueTest.java import static org.junit.Assert.assertEquals; import org.junit.Test; import waveview.wavedata.BitValue; // // Copyright 2016 Jeff Bush // // 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. // public class BitValueTest { @Test public void fromChar() {
assertEquals(BitValue.ZERO, BitValue.fromChar('0'));
jbush001/WaveView
src/test/java/ProgressInputStreamTest.java
// Path: src/main/java/waveview/wavedata/ProgressInputStream.java // public final class ProgressInputStream extends InputStream { // private long totalRead; // private long lastProgressUpdate; // private final long updateInterval; // private final InputStream wrapped; // private final Listener listener; // // public interface Listener { // void updateProgress(long totalRead) throws IOException; // } // // public ProgressInputStream(InputStream wrapped, Listener listener, long updateInterval) { // this.wrapped = wrapped; // this.listener = listener; // this.updateInterval = updateInterval; // } // // @Override // public void close() throws IOException { // wrapped.close(); // } // // @Override // public int read() throws IOException { // int got = wrapped.read(); // if (got != -1) { // totalRead++; // maybeNotifyListener(); // } // // return got; // } // // @Override // public int read(byte[] b) throws IOException { // int got = wrapped.read(b); // if (got != -1) { // totalRead += got; // maybeNotifyListener(); // } // // return got; // } // // @Override // public int read(byte[] b, int off, int len) throws IOException { // int got = wrapped.read(b, off, len); // if (got != -1) { // totalRead += got; // maybeNotifyListener(); // } // // return got; // } // // public long getTotalRead() { // return totalRead; // } // // private void maybeNotifyListener() throws IOException { // if (totalRead - lastProgressUpdate >= updateInterval) { // listener.updateProgress(totalRead); // lastProgressUpdate = totalRead; // } // } // }
import waveview.wavedata.ProgressInputStream; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; import java.io.InputStream; import java.util.Random; import org.junit.Before; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer;
// // Copyright 2018 Jeff Bush // // 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. // public class ProgressInputStreamTest { private static final int UPDATE_INTERVAL = 10; private final InputStream inputStream = mock(InputStream.class);
// Path: src/main/java/waveview/wavedata/ProgressInputStream.java // public final class ProgressInputStream extends InputStream { // private long totalRead; // private long lastProgressUpdate; // private final long updateInterval; // private final InputStream wrapped; // private final Listener listener; // // public interface Listener { // void updateProgress(long totalRead) throws IOException; // } // // public ProgressInputStream(InputStream wrapped, Listener listener, long updateInterval) { // this.wrapped = wrapped; // this.listener = listener; // this.updateInterval = updateInterval; // } // // @Override // public void close() throws IOException { // wrapped.close(); // } // // @Override // public int read() throws IOException { // int got = wrapped.read(); // if (got != -1) { // totalRead++; // maybeNotifyListener(); // } // // return got; // } // // @Override // public int read(byte[] b) throws IOException { // int got = wrapped.read(b); // if (got != -1) { // totalRead += got; // maybeNotifyListener(); // } // // return got; // } // // @Override // public int read(byte[] b, int off, int len) throws IOException { // int got = wrapped.read(b, off, len); // if (got != -1) { // totalRead += got; // maybeNotifyListener(); // } // // return got; // } // // public long getTotalRead() { // return totalRead; // } // // private void maybeNotifyListener() throws IOException { // if (totalRead - lastProgressUpdate >= updateInterval) { // listener.updateProgress(totalRead); // lastProgressUpdate = totalRead; // } // } // } // Path: src/test/java/ProgressInputStreamTest.java import waveview.wavedata.ProgressInputStream; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; import java.io.InputStream; import java.util.Random; import org.junit.Before; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; // // Copyright 2018 Jeff Bush // // 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. // public class ProgressInputStreamTest { private static final int UPDATE_INTERVAL = 10; private final InputStream inputStream = mock(InputStream.class);
private ProgressInputStream progressInputStream;
jbush001/WaveView
src/main/java/waveview/FindView.java
// Path: src/main/java/waveview/search/SearchFormatException.java // public class SearchFormatException extends Exception { // private final int startOffset; // private final int endOffset; // // SearchFormatException(String what, int startOffset, int endOffset) { // super(what); // this.startOffset = startOffset; // this.endOffset = endOffset; // } // // public int getStartOffset() { // return startOffset; // } // // public int getEndOffset() { // return endOffset; // } // }
import javax.swing.text.DefaultHighlighter; import javax.swing.text.Highlighter; import waveview.search.SearchFormatException; import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException;
JPanel findContainer = new JPanel(); findContainer.setLayout(new FlowLayout(FlowLayout.LEFT)); findContainer.add(findLabel); findContainer.add(new JScrollPane(searchExprTextArea)); add(findContainer, BorderLayout.CENTER); JPanel buttonContainer = new JPanel(); buttonContainer.setLayout(new FlowLayout(FlowLayout.RIGHT)); buttonContainer.add(prevButton); buttonContainer.add(nextButton); add(buttonContainer, BorderLayout.SOUTH); } /// Called when the user changes the search string. // The next time the user hits next/prev, will regenerate the Search object. private void invalidateSearch() { needToParseSearch = true; // When the user begins editing, remove the error highlights // so they don't leave boogers all over the place. errorHighlighter.removeAllHighlights(); } /// If the user changed the search string, try to parse it and generate /// a new Search object. If the search string is invalid, highlight the /// position of the error and pop up an error message. private void parseSearchIfNeeded() { if (needToParseSearch) { try { mainWindow.setSearch(searchExprTextArea.getText());
// Path: src/main/java/waveview/search/SearchFormatException.java // public class SearchFormatException extends Exception { // private final int startOffset; // private final int endOffset; // // SearchFormatException(String what, int startOffset, int endOffset) { // super(what); // this.startOffset = startOffset; // this.endOffset = endOffset; // } // // public int getStartOffset() { // return startOffset; // } // // public int getEndOffset() { // return endOffset; // } // } // Path: src/main/java/waveview/FindView.java import javax.swing.text.DefaultHighlighter; import javax.swing.text.Highlighter; import waveview.search.SearchFormatException; import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; JPanel findContainer = new JPanel(); findContainer.setLayout(new FlowLayout(FlowLayout.LEFT)); findContainer.add(findLabel); findContainer.add(new JScrollPane(searchExprTextArea)); add(findContainer, BorderLayout.CENTER); JPanel buttonContainer = new JPanel(); buttonContainer.setLayout(new FlowLayout(FlowLayout.RIGHT)); buttonContainer.add(prevButton); buttonContainer.add(nextButton); add(buttonContainer, BorderLayout.SOUTH); } /// Called when the user changes the search string. // The next time the user hits next/prev, will regenerate the Search object. private void invalidateSearch() { needToParseSearch = true; // When the user begins editing, remove the error highlights // so they don't leave boogers all over the place. errorHighlighter.removeAllHighlights(); } /// If the user changed the search string, try to parse it and generate /// a new Search object. If the search string is invalid, highlight the /// position of the error and pop up an error message. private void parseSearchIfNeeded() { if (needToParseSearch) { try { mainWindow.setSearch(searchExprTextArea.getText());
} catch (SearchFormatException exc) {
jbush001/WaveView
src/main/java/waveview/WaveformPresentationModel.java
// Path: src/main/java/waveview/wavedata/NetDataModel.java // public final class NetDataModel { // private final String shortName; // private final String fullName; // private TransitionVector transitionVector; // private final String decoderName; // private final String[] decoderInputNets; // private String[] decoderParameters; // // public NetDataModel(String shortName, String fullName, // TransitionVector transitionVector) { // this.shortName = shortName; // this.fullName = fullName; // this.transitionVector = transitionVector; // decoderName = ""; // decoderInputNets = new String[0]; // } // // public NetDataModel(String shortName, String fullName, // String decoderName, String[] decoderInputNets, // String[] decoderParameters, // TransitionVector transitionVector) { // this.shortName = shortName; // this.fullName = fullName; // this.transitionVector = transitionVector; // this.decoderName = decoderName; // this.decoderParameters = decoderParameters.clone(); // this.decoderInputNets = decoderInputNets.clone(); // } // // public String getFullName() { // return fullName; // } // // public String getShortName() { // return shortName; // } // // public String getDecoderName() { // return decoderName; // } // // public String[] getDecoderInputNets() { // return decoderInputNets.clone(); // } // // public String[] getDecoderParams() { // return decoderParameters.clone(); // } // // public TransitionVector getTransitionVector() { // return transitionVector; // } // // public void setTransitionVector(TransitionVector transitionVector) { // this.transitionVector = transitionVector; // } // // public Iterator<Transition> findTransition(long timestamp) { // return transitionVector.findTransition(timestamp); // } // // public long getMaxTimestamp() { // return transitionVector.getMaxTimestamp(); // } // // public int getWidth() { // return transitionVector.getWidth(); // } // } // // Path: src/main/java/waveview/wavedata/SortedArrayList.java // public final class SortedArrayList<T extends SortedArrayList.Keyed> { // private final List<T> list = new ArrayList<>(); // // public interface Keyed { long getKey(); } // // public int size() { // return list.size(); // } // // public void clear() { // list.clear(); // } // // public T get(int index) { // return list.get(index); // } // // public void remove(int index) { // list.remove(index); // } // // public boolean add(T value) { // long key = ((Keyed) value).getKey(); // for (int i = 0;; i++) { // if (i == size() || ((Keyed) get(i)).getKey() > key) { // list.add(i, value); // break; // } // } // // return true; // } // // public Iterator<T> find(long key) { // return new SortedArrayListIterator(findIndex(key)); // } // // /// @param key key value to search for // /// @returns index into array of element that matches key. If an // /// element isn't at this timestamp, return the element before the // /// timestamp. If the key is before the first element, return 0. // public int findIndex(long key) { // // Binary search // int low = 0; // Lowest possible index // int high = size() - 1; // Highest possible index // // while (low <= high) { // int mid = (low + high) >>> 1; // long midKey = ((Keyed) get(mid)).getKey(); // if (key < midKey) { // high = mid - 1; // } else if (key > midKey) { // low = mid + 1; // } else { // return mid; // } // } // // // No exact match. Low is equal to the index the transition would be // // at if it existed. We want to return the transition before the // // timestamp. If low == 0, this is before the first transition: // // return 0. // if (low == 0) { // return 0; // } // // return low - 1; // } // // private class SortedArrayListIterator implements Iterator<T> { // private int index; // // SortedArrayListIterator(int index) { // this.index = index; // } // // @Override // public boolean hasNext() { // return index < SortedArrayList.this.size(); // } // // @Override // public T next() { // if (!hasNext()) { // throw new NoSuchElementException(); // } // // T val = SortedArrayList.this.get(index); // index++; // return val; // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // } // }
import java.util.ArrayList; import java.util.List; import waveview.wavedata.NetDataModel; import waveview.wavedata.SortedArrayList;
// // Copyright 2011-2012 Jeff Bush // // 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 waveview; /// /// Contains visible state for a waveform capture (e.g. Cursor position, scale, /// visible nets, etc.) /// public final class WaveformPresentationModel { private final List<Listener> listeners = new ArrayList<>(); private final List<NetPresentationModel> visibleNets = new ArrayList<>(); private final List<NetSet> netSets = new ArrayList<>(); private long cursorPosition; private long selectionStart; private double horizontalScale; // Pixels per time units private boolean adjustingCursor;
// Path: src/main/java/waveview/wavedata/NetDataModel.java // public final class NetDataModel { // private final String shortName; // private final String fullName; // private TransitionVector transitionVector; // private final String decoderName; // private final String[] decoderInputNets; // private String[] decoderParameters; // // public NetDataModel(String shortName, String fullName, // TransitionVector transitionVector) { // this.shortName = shortName; // this.fullName = fullName; // this.transitionVector = transitionVector; // decoderName = ""; // decoderInputNets = new String[0]; // } // // public NetDataModel(String shortName, String fullName, // String decoderName, String[] decoderInputNets, // String[] decoderParameters, // TransitionVector transitionVector) { // this.shortName = shortName; // this.fullName = fullName; // this.transitionVector = transitionVector; // this.decoderName = decoderName; // this.decoderParameters = decoderParameters.clone(); // this.decoderInputNets = decoderInputNets.clone(); // } // // public String getFullName() { // return fullName; // } // // public String getShortName() { // return shortName; // } // // public String getDecoderName() { // return decoderName; // } // // public String[] getDecoderInputNets() { // return decoderInputNets.clone(); // } // // public String[] getDecoderParams() { // return decoderParameters.clone(); // } // // public TransitionVector getTransitionVector() { // return transitionVector; // } // // public void setTransitionVector(TransitionVector transitionVector) { // this.transitionVector = transitionVector; // } // // public Iterator<Transition> findTransition(long timestamp) { // return transitionVector.findTransition(timestamp); // } // // public long getMaxTimestamp() { // return transitionVector.getMaxTimestamp(); // } // // public int getWidth() { // return transitionVector.getWidth(); // } // } // // Path: src/main/java/waveview/wavedata/SortedArrayList.java // public final class SortedArrayList<T extends SortedArrayList.Keyed> { // private final List<T> list = new ArrayList<>(); // // public interface Keyed { long getKey(); } // // public int size() { // return list.size(); // } // // public void clear() { // list.clear(); // } // // public T get(int index) { // return list.get(index); // } // // public void remove(int index) { // list.remove(index); // } // // public boolean add(T value) { // long key = ((Keyed) value).getKey(); // for (int i = 0;; i++) { // if (i == size() || ((Keyed) get(i)).getKey() > key) { // list.add(i, value); // break; // } // } // // return true; // } // // public Iterator<T> find(long key) { // return new SortedArrayListIterator(findIndex(key)); // } // // /// @param key key value to search for // /// @returns index into array of element that matches key. If an // /// element isn't at this timestamp, return the element before the // /// timestamp. If the key is before the first element, return 0. // public int findIndex(long key) { // // Binary search // int low = 0; // Lowest possible index // int high = size() - 1; // Highest possible index // // while (low <= high) { // int mid = (low + high) >>> 1; // long midKey = ((Keyed) get(mid)).getKey(); // if (key < midKey) { // high = mid - 1; // } else if (key > midKey) { // low = mid + 1; // } else { // return mid; // } // } // // // No exact match. Low is equal to the index the transition would be // // at if it existed. We want to return the transition before the // // timestamp. If low == 0, this is before the first transition: // // return 0. // if (low == 0) { // return 0; // } // // return low - 1; // } // // private class SortedArrayListIterator implements Iterator<T> { // private int index; // // SortedArrayListIterator(int index) { // this.index = index; // } // // @Override // public boolean hasNext() { // return index < SortedArrayList.this.size(); // } // // @Override // public T next() { // if (!hasNext()) { // throw new NoSuchElementException(); // } // // T val = SortedArrayList.this.get(index); // index++; // return val; // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // } // } // Path: src/main/java/waveview/WaveformPresentationModel.java import java.util.ArrayList; import java.util.List; import waveview.wavedata.NetDataModel; import waveview.wavedata.SortedArrayList; // // Copyright 2011-2012 Jeff Bush // // 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 waveview; /// /// Contains visible state for a waveform capture (e.g. Cursor position, scale, /// visible nets, etc.) /// public final class WaveformPresentationModel { private final List<Listener> listeners = new ArrayList<>(); private final List<NetPresentationModel> visibleNets = new ArrayList<>(); private final List<NetSet> netSets = new ArrayList<>(); private long cursorPosition; private long selectionStart; private double horizontalScale; // Pixels per time units private boolean adjustingCursor;
private final SortedArrayList<Marker> markers = new SortedArrayList<>();
jbush001/WaveView
src/main/java/waveview/WaveformPresentationModel.java
// Path: src/main/java/waveview/wavedata/NetDataModel.java // public final class NetDataModel { // private final String shortName; // private final String fullName; // private TransitionVector transitionVector; // private final String decoderName; // private final String[] decoderInputNets; // private String[] decoderParameters; // // public NetDataModel(String shortName, String fullName, // TransitionVector transitionVector) { // this.shortName = shortName; // this.fullName = fullName; // this.transitionVector = transitionVector; // decoderName = ""; // decoderInputNets = new String[0]; // } // // public NetDataModel(String shortName, String fullName, // String decoderName, String[] decoderInputNets, // String[] decoderParameters, // TransitionVector transitionVector) { // this.shortName = shortName; // this.fullName = fullName; // this.transitionVector = transitionVector; // this.decoderName = decoderName; // this.decoderParameters = decoderParameters.clone(); // this.decoderInputNets = decoderInputNets.clone(); // } // // public String getFullName() { // return fullName; // } // // public String getShortName() { // return shortName; // } // // public String getDecoderName() { // return decoderName; // } // // public String[] getDecoderInputNets() { // return decoderInputNets.clone(); // } // // public String[] getDecoderParams() { // return decoderParameters.clone(); // } // // public TransitionVector getTransitionVector() { // return transitionVector; // } // // public void setTransitionVector(TransitionVector transitionVector) { // this.transitionVector = transitionVector; // } // // public Iterator<Transition> findTransition(long timestamp) { // return transitionVector.findTransition(timestamp); // } // // public long getMaxTimestamp() { // return transitionVector.getMaxTimestamp(); // } // // public int getWidth() { // return transitionVector.getWidth(); // } // } // // Path: src/main/java/waveview/wavedata/SortedArrayList.java // public final class SortedArrayList<T extends SortedArrayList.Keyed> { // private final List<T> list = new ArrayList<>(); // // public interface Keyed { long getKey(); } // // public int size() { // return list.size(); // } // // public void clear() { // list.clear(); // } // // public T get(int index) { // return list.get(index); // } // // public void remove(int index) { // list.remove(index); // } // // public boolean add(T value) { // long key = ((Keyed) value).getKey(); // for (int i = 0;; i++) { // if (i == size() || ((Keyed) get(i)).getKey() > key) { // list.add(i, value); // break; // } // } // // return true; // } // // public Iterator<T> find(long key) { // return new SortedArrayListIterator(findIndex(key)); // } // // /// @param key key value to search for // /// @returns index into array of element that matches key. If an // /// element isn't at this timestamp, return the element before the // /// timestamp. If the key is before the first element, return 0. // public int findIndex(long key) { // // Binary search // int low = 0; // Lowest possible index // int high = size() - 1; // Highest possible index // // while (low <= high) { // int mid = (low + high) >>> 1; // long midKey = ((Keyed) get(mid)).getKey(); // if (key < midKey) { // high = mid - 1; // } else if (key > midKey) { // low = mid + 1; // } else { // return mid; // } // } // // // No exact match. Low is equal to the index the transition would be // // at if it existed. We want to return the transition before the // // timestamp. If low == 0, this is before the first transition: // // return 0. // if (low == 0) { // return 0; // } // // return low - 1; // } // // private class SortedArrayListIterator implements Iterator<T> { // private int index; // // SortedArrayListIterator(int index) { // this.index = index; // } // // @Override // public boolean hasNext() { // return index < SortedArrayList.this.size(); // } // // @Override // public T next() { // if (!hasNext()) { // throw new NoSuchElementException(); // } // // T val = SortedArrayList.this.get(index); // index++; // return val; // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // } // }
import java.util.ArrayList; import java.util.List; import waveview.wavedata.NetDataModel; import waveview.wavedata.SortedArrayList;
} public void addListener(Listener listener) { listeners.add(listener); } // @param scale Pixels per time unit public void setHorizontalScale(double scale) { horizontalScale = scale; minorTickInterval = (int) Math.pow(10, Math.ceil(Math.log10(DrawMetrics.MIN_MINOR_TICK_H_SPACE / scale))); if (minorTickInterval <= 0) { minorTickInterval = 1; } for (Listener listener : listeners) { listener.scaleChanged(scale); } } // @returns Pixels per time unit public double getHorizontalScale() { return horizontalScale; } // @returns Duration between horizontal ticks, in time units public long getMinorTickInterval() { return minorTickInterval; }
// Path: src/main/java/waveview/wavedata/NetDataModel.java // public final class NetDataModel { // private final String shortName; // private final String fullName; // private TransitionVector transitionVector; // private final String decoderName; // private final String[] decoderInputNets; // private String[] decoderParameters; // // public NetDataModel(String shortName, String fullName, // TransitionVector transitionVector) { // this.shortName = shortName; // this.fullName = fullName; // this.transitionVector = transitionVector; // decoderName = ""; // decoderInputNets = new String[0]; // } // // public NetDataModel(String shortName, String fullName, // String decoderName, String[] decoderInputNets, // String[] decoderParameters, // TransitionVector transitionVector) { // this.shortName = shortName; // this.fullName = fullName; // this.transitionVector = transitionVector; // this.decoderName = decoderName; // this.decoderParameters = decoderParameters.clone(); // this.decoderInputNets = decoderInputNets.clone(); // } // // public String getFullName() { // return fullName; // } // // public String getShortName() { // return shortName; // } // // public String getDecoderName() { // return decoderName; // } // // public String[] getDecoderInputNets() { // return decoderInputNets.clone(); // } // // public String[] getDecoderParams() { // return decoderParameters.clone(); // } // // public TransitionVector getTransitionVector() { // return transitionVector; // } // // public void setTransitionVector(TransitionVector transitionVector) { // this.transitionVector = transitionVector; // } // // public Iterator<Transition> findTransition(long timestamp) { // return transitionVector.findTransition(timestamp); // } // // public long getMaxTimestamp() { // return transitionVector.getMaxTimestamp(); // } // // public int getWidth() { // return transitionVector.getWidth(); // } // } // // Path: src/main/java/waveview/wavedata/SortedArrayList.java // public final class SortedArrayList<T extends SortedArrayList.Keyed> { // private final List<T> list = new ArrayList<>(); // // public interface Keyed { long getKey(); } // // public int size() { // return list.size(); // } // // public void clear() { // list.clear(); // } // // public T get(int index) { // return list.get(index); // } // // public void remove(int index) { // list.remove(index); // } // // public boolean add(T value) { // long key = ((Keyed) value).getKey(); // for (int i = 0;; i++) { // if (i == size() || ((Keyed) get(i)).getKey() > key) { // list.add(i, value); // break; // } // } // // return true; // } // // public Iterator<T> find(long key) { // return new SortedArrayListIterator(findIndex(key)); // } // // /// @param key key value to search for // /// @returns index into array of element that matches key. If an // /// element isn't at this timestamp, return the element before the // /// timestamp. If the key is before the first element, return 0. // public int findIndex(long key) { // // Binary search // int low = 0; // Lowest possible index // int high = size() - 1; // Highest possible index // // while (low <= high) { // int mid = (low + high) >>> 1; // long midKey = ((Keyed) get(mid)).getKey(); // if (key < midKey) { // high = mid - 1; // } else if (key > midKey) { // low = mid + 1; // } else { // return mid; // } // } // // // No exact match. Low is equal to the index the transition would be // // at if it existed. We want to return the transition before the // // timestamp. If low == 0, this is before the first transition: // // return 0. // if (low == 0) { // return 0; // } // // return low - 1; // } // // private class SortedArrayListIterator implements Iterator<T> { // private int index; // // SortedArrayListIterator(int index) { // this.index = index; // } // // @Override // public boolean hasNext() { // return index < SortedArrayList.this.size(); // } // // @Override // public T next() { // if (!hasNext()) { // throw new NoSuchElementException(); // } // // T val = SortedArrayList.this.get(index); // index++; // return val; // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // } // } // Path: src/main/java/waveview/WaveformPresentationModel.java import java.util.ArrayList; import java.util.List; import waveview.wavedata.NetDataModel; import waveview.wavedata.SortedArrayList; } public void addListener(Listener listener) { listeners.add(listener); } // @param scale Pixels per time unit public void setHorizontalScale(double scale) { horizontalScale = scale; minorTickInterval = (int) Math.pow(10, Math.ceil(Math.log10(DrawMetrics.MIN_MINOR_TICK_H_SPACE / scale))); if (minorTickInterval <= 0) { minorTickInterval = 1; } for (Listener listener : listeners) { listener.scaleChanged(scale); } } // @returns Pixels per time unit public double getHorizontalScale() { return horizontalScale; } // @returns Duration between horizontal ticks, in time units public long getMinorTickInterval() { return minorTickInterval; }
public void addNet(NetDataModel netDataModel) {
malafeev/JFTClient
src/main/java/org/jftclient/tree/LocalTree.java
// Path: src/main/java/org/jftclient/config/dao/ConfigDao.java // public interface ConfigDao extends CrudRepository<Config, Long> { // // @Query("select c from Config c where c.id = 1") // Config get(); // }
import java.io.File; import java.util.Collections; import org.jftclient.config.dao.ConfigDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.control.TreeItem;
package org.jftclient.tree; /** * @author sergei.malafeev */ @Component public class LocalTree implements Tree { @Autowired
// Path: src/main/java/org/jftclient/config/dao/ConfigDao.java // public interface ConfigDao extends CrudRepository<Config, Long> { // // @Query("select c from Config c where c.id = 1") // Config get(); // } // Path: src/main/java/org/jftclient/tree/LocalTree.java import java.io.File; import java.util.Collections; import org.jftclient.config.dao.ConfigDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.control.TreeItem; package org.jftclient.tree; /** * @author sergei.malafeev */ @Component public class LocalTree implements Tree { @Autowired
private ConfigDao configDao;
malafeev/JFTClient
src/main/java/org/jftclient/HostCell.java
// Path: src/main/java/org/jftclient/config/dao/HostDao.java // public interface HostDao extends CrudRepository<Host, Long> { // // @Query("select h from Host h where h.hostname = :name") // Host getHostByName(@Param("name") String name); // // @Query("select h from Host h") // List<Host> getAll(); // // @Query("select h.hostname from Host h") // List<String> getHostNames(); // } // // Path: src/main/java/org/jftclient/config/domain/Host.java // @Entity // public class Host implements Comparable<Host> { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private long id; // private String username; // private String hostname; // private String password; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getHostname() { // return hostname; // } // // public void setHostname(String hostname) { // this.hostname = hostname; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Host host = (Host) o; // // if (hostname != null ? !hostname.equals(host.hostname) : host.hostname != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = hostname != null ? hostname.hashCode() : 0; // result = 31 * result; // return result; // } // // @Override // public int compareTo(Host o) { // return hostname.compareTo(o.getHostname()); // } // }
import org.jftclient.config.dao.HostDao; import org.jftclient.config.domain.Host; import javafx.scene.control.ComboBox; import javafx.scene.control.ContextMenu; import javafx.scene.control.ListCell; import javafx.scene.control.MenuItem;
package org.jftclient; /** * @author sergei.malafeev */ public class HostCell extends ListCell<String> { private ContextMenu contextMenu;
// Path: src/main/java/org/jftclient/config/dao/HostDao.java // public interface HostDao extends CrudRepository<Host, Long> { // // @Query("select h from Host h where h.hostname = :name") // Host getHostByName(@Param("name") String name); // // @Query("select h from Host h") // List<Host> getAll(); // // @Query("select h.hostname from Host h") // List<String> getHostNames(); // } // // Path: src/main/java/org/jftclient/config/domain/Host.java // @Entity // public class Host implements Comparable<Host> { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private long id; // private String username; // private String hostname; // private String password; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getHostname() { // return hostname; // } // // public void setHostname(String hostname) { // this.hostname = hostname; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Host host = (Host) o; // // if (hostname != null ? !hostname.equals(host.hostname) : host.hostname != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = hostname != null ? hostname.hashCode() : 0; // result = 31 * result; // return result; // } // // @Override // public int compareTo(Host o) { // return hostname.compareTo(o.getHostname()); // } // } // Path: src/main/java/org/jftclient/HostCell.java import org.jftclient.config.dao.HostDao; import org.jftclient.config.domain.Host; import javafx.scene.control.ComboBox; import javafx.scene.control.ContextMenu; import javafx.scene.control.ListCell; import javafx.scene.control.MenuItem; package org.jftclient; /** * @author sergei.malafeev */ public class HostCell extends ListCell<String> { private ContextMenu contextMenu;
private HostDao hostDao;
malafeev/JFTClient
src/main/java/org/jftclient/HostCell.java
// Path: src/main/java/org/jftclient/config/dao/HostDao.java // public interface HostDao extends CrudRepository<Host, Long> { // // @Query("select h from Host h where h.hostname = :name") // Host getHostByName(@Param("name") String name); // // @Query("select h from Host h") // List<Host> getAll(); // // @Query("select h.hostname from Host h") // List<String> getHostNames(); // } // // Path: src/main/java/org/jftclient/config/domain/Host.java // @Entity // public class Host implements Comparable<Host> { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private long id; // private String username; // private String hostname; // private String password; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getHostname() { // return hostname; // } // // public void setHostname(String hostname) { // this.hostname = hostname; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Host host = (Host) o; // // if (hostname != null ? !hostname.equals(host.hostname) : host.hostname != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = hostname != null ? hostname.hashCode() : 0; // result = 31 * result; // return result; // } // // @Override // public int compareTo(Host o) { // return hostname.compareTo(o.getHostname()); // } // }
import org.jftclient.config.dao.HostDao; import org.jftclient.config.domain.Host; import javafx.scene.control.ComboBox; import javafx.scene.control.ContextMenu; import javafx.scene.control.ListCell; import javafx.scene.control.MenuItem;
package org.jftclient; /** * @author sergei.malafeev */ public class HostCell extends ListCell<String> { private ContextMenu contextMenu; private HostDao hostDao; private ComboBox<String> hostField; public HostCell(HostDao hostDao, ComboBox<String> hostField) { this.hostDao = hostDao; this.hostField = hostField; MenuItem deleteMenu = new MenuItem("Delete"); deleteMenu.setOnAction(event -> deleteItems()); contextMenu = new ContextMenu(); contextMenu.getItems().addAll(deleteMenu); } @Override public void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (!empty && item != null) { setContextMenu(contextMenu); } setText(item == null ? null : item); setGraphic(null); } private void deleteItems() { for (String host : getListView().getSelectionModel().getSelectedItems()) {
// Path: src/main/java/org/jftclient/config/dao/HostDao.java // public interface HostDao extends CrudRepository<Host, Long> { // // @Query("select h from Host h where h.hostname = :name") // Host getHostByName(@Param("name") String name); // // @Query("select h from Host h") // List<Host> getAll(); // // @Query("select h.hostname from Host h") // List<String> getHostNames(); // } // // Path: src/main/java/org/jftclient/config/domain/Host.java // @Entity // public class Host implements Comparable<Host> { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private long id; // private String username; // private String hostname; // private String password; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getHostname() { // return hostname; // } // // public void setHostname(String hostname) { // this.hostname = hostname; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Host host = (Host) o; // // if (hostname != null ? !hostname.equals(host.hostname) : host.hostname != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = hostname != null ? hostname.hashCode() : 0; // result = 31 * result; // return result; // } // // @Override // public int compareTo(Host o) { // return hostname.compareTo(o.getHostname()); // } // } // Path: src/main/java/org/jftclient/HostCell.java import org.jftclient.config.dao.HostDao; import org.jftclient.config.domain.Host; import javafx.scene.control.ComboBox; import javafx.scene.control.ContextMenu; import javafx.scene.control.ListCell; import javafx.scene.control.MenuItem; package org.jftclient; /** * @author sergei.malafeev */ public class HostCell extends ListCell<String> { private ContextMenu contextMenu; private HostDao hostDao; private ComboBox<String> hostField; public HostCell(HostDao hostDao, ComboBox<String> hostField) { this.hostDao = hostDao; this.hostField = hostField; MenuItem deleteMenu = new MenuItem("Delete"); deleteMenu.setOnAction(event -> deleteItems()); contextMenu = new ContextMenu(); contextMenu.getItems().addAll(deleteMenu); } @Override public void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (!empty && item != null) { setContextMenu(contextMenu); } setText(item == null ? null : item); setGraphic(null); } private void deleteItems() { for (String host : getListView().getSelectionModel().getSelectedItems()) {
Host h = hostDao.getHostByName(host);
malafeev/JFTClient
src/test/java/org/jftclient/tree/LocalTreeTest.java
// Path: src/main/java/org/jftclient/config/dao/ConfigDao.java // public interface ConfigDao extends CrudRepository<Config, Long> { // // @Query("select c from Config c where c.id = 1") // Config get(); // } // // Path: src/main/java/org/jftclient/config/domain/Config.java // @Entity // public class Config { // @Id // private long id = 1L; // private boolean showHiddenFiles; // private boolean savePasswords; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public boolean isShowHiddenFiles() { // return showHiddenFiles; // } // // public void setShowHiddenFiles(boolean showHiddenFiles) { // this.showHiddenFiles = showHiddenFiles; // } // // public boolean isSavePasswords() { // return savePasswords; // } // // public void setSavePasswords(boolean savePasswords) { // this.savePasswords = savePasswords; // } // }
import org.jftclient.config.dao.ConfigDao; import org.jftclient.config.domain.Config; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import javafx.scene.control.TreeItem; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue;
package org.jftclient.tree; @Test public class LocalTreeTest { @Mock(name = "configDao")
// Path: src/main/java/org/jftclient/config/dao/ConfigDao.java // public interface ConfigDao extends CrudRepository<Config, Long> { // // @Query("select c from Config c where c.id = 1") // Config get(); // } // // Path: src/main/java/org/jftclient/config/domain/Config.java // @Entity // public class Config { // @Id // private long id = 1L; // private boolean showHiddenFiles; // private boolean savePasswords; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public boolean isShowHiddenFiles() { // return showHiddenFiles; // } // // public void setShowHiddenFiles(boolean showHiddenFiles) { // this.showHiddenFiles = showHiddenFiles; // } // // public boolean isSavePasswords() { // return savePasswords; // } // // public void setSavePasswords(boolean savePasswords) { // this.savePasswords = savePasswords; // } // } // Path: src/test/java/org/jftclient/tree/LocalTreeTest.java import org.jftclient.config.dao.ConfigDao; import org.jftclient.config.domain.Config; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import javafx.scene.control.TreeItem; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; package org.jftclient.tree; @Test public class LocalTreeTest { @Mock(name = "configDao")
private ConfigDao configDao;
malafeev/JFTClient
src/test/java/org/jftclient/tree/LocalTreeTest.java
// Path: src/main/java/org/jftclient/config/dao/ConfigDao.java // public interface ConfigDao extends CrudRepository<Config, Long> { // // @Query("select c from Config c where c.id = 1") // Config get(); // } // // Path: src/main/java/org/jftclient/config/domain/Config.java // @Entity // public class Config { // @Id // private long id = 1L; // private boolean showHiddenFiles; // private boolean savePasswords; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public boolean isShowHiddenFiles() { // return showHiddenFiles; // } // // public void setShowHiddenFiles(boolean showHiddenFiles) { // this.showHiddenFiles = showHiddenFiles; // } // // public boolean isSavePasswords() { // return savePasswords; // } // // public void setSavePasswords(boolean savePasswords) { // this.savePasswords = savePasswords; // } // }
import org.jftclient.config.dao.ConfigDao; import org.jftclient.config.domain.Config; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import javafx.scene.control.TreeItem; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue;
package org.jftclient.tree; @Test public class LocalTreeTest { @Mock(name = "configDao") private ConfigDao configDao; @InjectMocks private LocalTree localTree; @BeforeMethod public void setUp() { MockitoAnnotations.initMocks(this);
// Path: src/main/java/org/jftclient/config/dao/ConfigDao.java // public interface ConfigDao extends CrudRepository<Config, Long> { // // @Query("select c from Config c where c.id = 1") // Config get(); // } // // Path: src/main/java/org/jftclient/config/domain/Config.java // @Entity // public class Config { // @Id // private long id = 1L; // private boolean showHiddenFiles; // private boolean savePasswords; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public boolean isShowHiddenFiles() { // return showHiddenFiles; // } // // public void setShowHiddenFiles(boolean showHiddenFiles) { // this.showHiddenFiles = showHiddenFiles; // } // // public boolean isSavePasswords() { // return savePasswords; // } // // public void setSavePasswords(boolean savePasswords) { // this.savePasswords = savePasswords; // } // } // Path: src/test/java/org/jftclient/tree/LocalTreeTest.java import org.jftclient.config.dao.ConfigDao; import org.jftclient.config.domain.Config; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import javafx.scene.control.TreeItem; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; package org.jftclient.tree; @Test public class LocalTreeTest { @Mock(name = "configDao") private ConfigDao configDao; @InjectMocks private LocalTree localTree; @BeforeMethod public void setUp() { MockitoAnnotations.initMocks(this);
when(configDao.get()).thenReturn(new Config());
domkowald/tagrecommender
src/file/stemming/englishStemmer.java
// Path: src/file/stemming/Among.java // public class Among { // public Among (String s, int substring_i, int result, // String methodname, SnowballProgram methodobject) { // this.s_size = s.length(); // this.s = s.toCharArray(); // this.substring_i = substring_i; // this.result = result; // this.methodobject = methodobject; // if (methodname.length() == 0) { // this.method = null; // } else { // try { // this.method = methodobject.getClass(). // getDeclaredMethod(methodname, new Class[0]); // } catch (NoSuchMethodException e) { // throw new RuntimeException(e); // } // } // } // // public final int s_size; /* search string */ // public final char[] s; /* search string */ // public final int substring_i; /* index to longest matching substring */ // public final int result; /* result of the lookup */ // public final Method method; /* method to use if substring matches */ // public final SnowballProgram methodobject; /* object to invoke method on */ // };
import file.stemming.Among;
/** * This class was automatically generated by a Snowball to Java compiler * It implements the stemming algorithm defined by a snowball script. */ package file.stemming; public class englishStemmer extends SnowballStemmer { private static final long serialVersionUID = 1L; private final static englishStemmer methodObject = new englishStemmer ();
// Path: src/file/stemming/Among.java // public class Among { // public Among (String s, int substring_i, int result, // String methodname, SnowballProgram methodobject) { // this.s_size = s.length(); // this.s = s.toCharArray(); // this.substring_i = substring_i; // this.result = result; // this.methodobject = methodobject; // if (methodname.length() == 0) { // this.method = null; // } else { // try { // this.method = methodobject.getClass(). // getDeclaredMethod(methodname, new Class[0]); // } catch (NoSuchMethodException e) { // throw new RuntimeException(e); // } // } // } // // public final int s_size; /* search string */ // public final char[] s; /* search string */ // public final int substring_i; /* index to longest matching substring */ // public final int result; /* result of the lookup */ // public final Method method; /* method to use if substring matches */ // public final SnowballProgram methodobject; /* object to invoke method on */ // }; // Path: src/file/stemming/englishStemmer.java import file.stemming.Among; /** * This class was automatically generated by a Snowball to Java compiler * It implements the stemming algorithm defined by a snowball script. */ package file.stemming; public class englishStemmer extends SnowballStemmer { private static final long serialVersionUID = 1L; private final static englishStemmer methodObject = new englishStemmer ();
private final static Among a_0[] = {
yasikstudio/devrank
devrank-job/src/main/java/com/yasikstudio/devrank/DevRank.java
// Path: devrank-job/src/main/java/com/yasikstudio/devrank/merge/DataMergeJob.java // public class DataMergeJob implements Tool { // // private Configuration configuration; // // @Override // public int run(String[] args) throws Exception { // Options options = new Options(); // options.addOption("h", "help", false, "Help"); // options.addOption("i", "inputPath", true, "Input Path"); // options.addOption("o", "outputPath", true, "Output Path"); // // HelpFormatter formatter = new HelpFormatter(); // if (args.length == 0) { // formatter.printHelp(getClass().getName(), options, true); // return 0; // } // CommandLineParser parser = new PosixParser(); // CommandLine cmd = parser.parse(options, args); // if (cmd.hasOption('h')) { // formatter.printHelp(getClass().getName(), options, true); // return 0; // } // // String inputPath = cmd.getOptionValue("inputPath"); // String outputPath = cmd.getOptionValue("outputPath"); // // String jobname = "devrank-job-merge-" + System.currentTimeMillis(); // Job job = new Job(getConf(), jobname); // job.setJarByClass(DataMergeJob.class); // // job.setMapperClass(DataMergeMapper.class); // job.setCombinerClass(DataMergeCombiner.class); // job.setReducerClass(DataMergeReducer.class); // // job.setMapOutputKeyClass(Text.class); // job.setMapOutputValueClass(UserRecord.class); // job.setOutputKeyClass(Text.class); // job.setOutputValueClass(NullWritable.class); // // FileInputFormat.addInputPath(job, new Path(inputPath)); // FileOutputFormat.setOutputPath(job, new Path(outputPath)); // // return job.waitForCompletion(true) ? 0 : 1; // } // // @Override // public Configuration getConf() { // return configuration; // } // // @Override // public void setConf(Configuration configuration) { // this.configuration = configuration; // } // } // // Path: devrank-job/src/main/java/com/yasikstudio/devrank/rank/DeveloperRankJob.java // public class DeveloperRankJob implements Tool { // // private Configuration configuration; // // @Override // public int run(String[] args) throws Exception { // Options options = new Options(); // options.addOption("h", "help", false, "Help"); // options.addOption("i", "inputPath", true, "Input Path"); // options.addOption("o", "outputPath", true, "Output Path"); // options.addOption("w", "workers", true, "Number of workers"); // options.addOption("s", "supersteps", true, "Number of supersteps"); // options.addOption("r", "ratioOptions", true, "followings,forks,pulls,stars,watches"); // // HelpFormatter formatter = new HelpFormatter(); // if (args.length == 0) { // formatter.printHelp(getClass().getName(), options, true); // return 0; // } // CommandLineParser parser = new PosixParser(); // CommandLine cmd = parser.parse(options, args); // if (cmd.hasOption('h')) { // formatter.printHelp(getClass().getName(), options, true); // return 0; // } // // int workers = Integer.parseInt(cmd.getOptionValue('w', "1")); // long supersteps = Long.parseLong(cmd.getOptionValue('s', "10")); // String inputPath = cmd.getOptionValue("inputPath"); // String outputPath = cmd.getOptionValue("outputPath"); // String ratio = cmd.getOptionValue("ratioOptions", "1,1,1,1,1"); // // configuration.setLong("superstep", supersteps); // configuration.setStrings("ratioOptions", ratio); // // String jobname = "devrank-job-rank-" + System.currentTimeMillis(); // GiraphJob job = new GiraphJob(getConf(), jobname); // GiraphConfiguration giraphConf = job.getConfiguration(); // giraphConf.setVertexClass(DeveloperRankVertex.class); // giraphConf.setVertexInputFormatClass(DeveloperRankVertexInputFormat.class); // giraphConf.setVertexOutputFormatClass(DeveloperRankVertexOutputFormat.class); // GiraphFileInputFormat.addVertexInputPath(job.getConfiguration(), new Path(inputPath)); // FileOutputFormat.setOutputPath(job.getInternalJob(), new Path(outputPath)); // giraphConf.setWorkerConfiguration(workers, workers, 100.0f); // return job.run(true) ? 0 : -1; // } // // @Override // public Configuration getConf() { // return configuration; // } // // @Override // public void setConf(Configuration configuration) { // this.configuration = configuration; // } // }
import java.util.HashMap; import java.util.Map; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import com.google.common.base.Joiner; import com.yasikstudio.devrank.merge.DataMergeJob; import com.yasikstudio.devrank.rank.DeveloperRankJob;
package com.yasikstudio.devrank; public class DevRank { private static Map<String, Class<?>> jobs = new HashMap<String, Class<?>>(); static {
// Path: devrank-job/src/main/java/com/yasikstudio/devrank/merge/DataMergeJob.java // public class DataMergeJob implements Tool { // // private Configuration configuration; // // @Override // public int run(String[] args) throws Exception { // Options options = new Options(); // options.addOption("h", "help", false, "Help"); // options.addOption("i", "inputPath", true, "Input Path"); // options.addOption("o", "outputPath", true, "Output Path"); // // HelpFormatter formatter = new HelpFormatter(); // if (args.length == 0) { // formatter.printHelp(getClass().getName(), options, true); // return 0; // } // CommandLineParser parser = new PosixParser(); // CommandLine cmd = parser.parse(options, args); // if (cmd.hasOption('h')) { // formatter.printHelp(getClass().getName(), options, true); // return 0; // } // // String inputPath = cmd.getOptionValue("inputPath"); // String outputPath = cmd.getOptionValue("outputPath"); // // String jobname = "devrank-job-merge-" + System.currentTimeMillis(); // Job job = new Job(getConf(), jobname); // job.setJarByClass(DataMergeJob.class); // // job.setMapperClass(DataMergeMapper.class); // job.setCombinerClass(DataMergeCombiner.class); // job.setReducerClass(DataMergeReducer.class); // // job.setMapOutputKeyClass(Text.class); // job.setMapOutputValueClass(UserRecord.class); // job.setOutputKeyClass(Text.class); // job.setOutputValueClass(NullWritable.class); // // FileInputFormat.addInputPath(job, new Path(inputPath)); // FileOutputFormat.setOutputPath(job, new Path(outputPath)); // // return job.waitForCompletion(true) ? 0 : 1; // } // // @Override // public Configuration getConf() { // return configuration; // } // // @Override // public void setConf(Configuration configuration) { // this.configuration = configuration; // } // } // // Path: devrank-job/src/main/java/com/yasikstudio/devrank/rank/DeveloperRankJob.java // public class DeveloperRankJob implements Tool { // // private Configuration configuration; // // @Override // public int run(String[] args) throws Exception { // Options options = new Options(); // options.addOption("h", "help", false, "Help"); // options.addOption("i", "inputPath", true, "Input Path"); // options.addOption("o", "outputPath", true, "Output Path"); // options.addOption("w", "workers", true, "Number of workers"); // options.addOption("s", "supersteps", true, "Number of supersteps"); // options.addOption("r", "ratioOptions", true, "followings,forks,pulls,stars,watches"); // // HelpFormatter formatter = new HelpFormatter(); // if (args.length == 0) { // formatter.printHelp(getClass().getName(), options, true); // return 0; // } // CommandLineParser parser = new PosixParser(); // CommandLine cmd = parser.parse(options, args); // if (cmd.hasOption('h')) { // formatter.printHelp(getClass().getName(), options, true); // return 0; // } // // int workers = Integer.parseInt(cmd.getOptionValue('w', "1")); // long supersteps = Long.parseLong(cmd.getOptionValue('s', "10")); // String inputPath = cmd.getOptionValue("inputPath"); // String outputPath = cmd.getOptionValue("outputPath"); // String ratio = cmd.getOptionValue("ratioOptions", "1,1,1,1,1"); // // configuration.setLong("superstep", supersteps); // configuration.setStrings("ratioOptions", ratio); // // String jobname = "devrank-job-rank-" + System.currentTimeMillis(); // GiraphJob job = new GiraphJob(getConf(), jobname); // GiraphConfiguration giraphConf = job.getConfiguration(); // giraphConf.setVertexClass(DeveloperRankVertex.class); // giraphConf.setVertexInputFormatClass(DeveloperRankVertexInputFormat.class); // giraphConf.setVertexOutputFormatClass(DeveloperRankVertexOutputFormat.class); // GiraphFileInputFormat.addVertexInputPath(job.getConfiguration(), new Path(inputPath)); // FileOutputFormat.setOutputPath(job.getInternalJob(), new Path(outputPath)); // giraphConf.setWorkerConfiguration(workers, workers, 100.0f); // return job.run(true) ? 0 : -1; // } // // @Override // public Configuration getConf() { // return configuration; // } // // @Override // public void setConf(Configuration configuration) { // this.configuration = configuration; // } // } // Path: devrank-job/src/main/java/com/yasikstudio/devrank/DevRank.java import java.util.HashMap; import java.util.Map; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import com.google.common.base.Joiner; import com.yasikstudio.devrank.merge.DataMergeJob; import com.yasikstudio.devrank.rank.DeveloperRankJob; package com.yasikstudio.devrank; public class DevRank { private static Map<String, Class<?>> jobs = new HashMap<String, Class<?>>(); static {
jobs.put("rank", DeveloperRankJob.class);
yasikstudio/devrank
devrank-job/src/main/java/com/yasikstudio/devrank/DevRank.java
// Path: devrank-job/src/main/java/com/yasikstudio/devrank/merge/DataMergeJob.java // public class DataMergeJob implements Tool { // // private Configuration configuration; // // @Override // public int run(String[] args) throws Exception { // Options options = new Options(); // options.addOption("h", "help", false, "Help"); // options.addOption("i", "inputPath", true, "Input Path"); // options.addOption("o", "outputPath", true, "Output Path"); // // HelpFormatter formatter = new HelpFormatter(); // if (args.length == 0) { // formatter.printHelp(getClass().getName(), options, true); // return 0; // } // CommandLineParser parser = new PosixParser(); // CommandLine cmd = parser.parse(options, args); // if (cmd.hasOption('h')) { // formatter.printHelp(getClass().getName(), options, true); // return 0; // } // // String inputPath = cmd.getOptionValue("inputPath"); // String outputPath = cmd.getOptionValue("outputPath"); // // String jobname = "devrank-job-merge-" + System.currentTimeMillis(); // Job job = new Job(getConf(), jobname); // job.setJarByClass(DataMergeJob.class); // // job.setMapperClass(DataMergeMapper.class); // job.setCombinerClass(DataMergeCombiner.class); // job.setReducerClass(DataMergeReducer.class); // // job.setMapOutputKeyClass(Text.class); // job.setMapOutputValueClass(UserRecord.class); // job.setOutputKeyClass(Text.class); // job.setOutputValueClass(NullWritable.class); // // FileInputFormat.addInputPath(job, new Path(inputPath)); // FileOutputFormat.setOutputPath(job, new Path(outputPath)); // // return job.waitForCompletion(true) ? 0 : 1; // } // // @Override // public Configuration getConf() { // return configuration; // } // // @Override // public void setConf(Configuration configuration) { // this.configuration = configuration; // } // } // // Path: devrank-job/src/main/java/com/yasikstudio/devrank/rank/DeveloperRankJob.java // public class DeveloperRankJob implements Tool { // // private Configuration configuration; // // @Override // public int run(String[] args) throws Exception { // Options options = new Options(); // options.addOption("h", "help", false, "Help"); // options.addOption("i", "inputPath", true, "Input Path"); // options.addOption("o", "outputPath", true, "Output Path"); // options.addOption("w", "workers", true, "Number of workers"); // options.addOption("s", "supersteps", true, "Number of supersteps"); // options.addOption("r", "ratioOptions", true, "followings,forks,pulls,stars,watches"); // // HelpFormatter formatter = new HelpFormatter(); // if (args.length == 0) { // formatter.printHelp(getClass().getName(), options, true); // return 0; // } // CommandLineParser parser = new PosixParser(); // CommandLine cmd = parser.parse(options, args); // if (cmd.hasOption('h')) { // formatter.printHelp(getClass().getName(), options, true); // return 0; // } // // int workers = Integer.parseInt(cmd.getOptionValue('w', "1")); // long supersteps = Long.parseLong(cmd.getOptionValue('s', "10")); // String inputPath = cmd.getOptionValue("inputPath"); // String outputPath = cmd.getOptionValue("outputPath"); // String ratio = cmd.getOptionValue("ratioOptions", "1,1,1,1,1"); // // configuration.setLong("superstep", supersteps); // configuration.setStrings("ratioOptions", ratio); // // String jobname = "devrank-job-rank-" + System.currentTimeMillis(); // GiraphJob job = new GiraphJob(getConf(), jobname); // GiraphConfiguration giraphConf = job.getConfiguration(); // giraphConf.setVertexClass(DeveloperRankVertex.class); // giraphConf.setVertexInputFormatClass(DeveloperRankVertexInputFormat.class); // giraphConf.setVertexOutputFormatClass(DeveloperRankVertexOutputFormat.class); // GiraphFileInputFormat.addVertexInputPath(job.getConfiguration(), new Path(inputPath)); // FileOutputFormat.setOutputPath(job.getInternalJob(), new Path(outputPath)); // giraphConf.setWorkerConfiguration(workers, workers, 100.0f); // return job.run(true) ? 0 : -1; // } // // @Override // public Configuration getConf() { // return configuration; // } // // @Override // public void setConf(Configuration configuration) { // this.configuration = configuration; // } // }
import java.util.HashMap; import java.util.Map; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import com.google.common.base.Joiner; import com.yasikstudio.devrank.merge.DataMergeJob; import com.yasikstudio.devrank.rank.DeveloperRankJob;
package com.yasikstudio.devrank; public class DevRank { private static Map<String, Class<?>> jobs = new HashMap<String, Class<?>>(); static { jobs.put("rank", DeveloperRankJob.class);
// Path: devrank-job/src/main/java/com/yasikstudio/devrank/merge/DataMergeJob.java // public class DataMergeJob implements Tool { // // private Configuration configuration; // // @Override // public int run(String[] args) throws Exception { // Options options = new Options(); // options.addOption("h", "help", false, "Help"); // options.addOption("i", "inputPath", true, "Input Path"); // options.addOption("o", "outputPath", true, "Output Path"); // // HelpFormatter formatter = new HelpFormatter(); // if (args.length == 0) { // formatter.printHelp(getClass().getName(), options, true); // return 0; // } // CommandLineParser parser = new PosixParser(); // CommandLine cmd = parser.parse(options, args); // if (cmd.hasOption('h')) { // formatter.printHelp(getClass().getName(), options, true); // return 0; // } // // String inputPath = cmd.getOptionValue("inputPath"); // String outputPath = cmd.getOptionValue("outputPath"); // // String jobname = "devrank-job-merge-" + System.currentTimeMillis(); // Job job = new Job(getConf(), jobname); // job.setJarByClass(DataMergeJob.class); // // job.setMapperClass(DataMergeMapper.class); // job.setCombinerClass(DataMergeCombiner.class); // job.setReducerClass(DataMergeReducer.class); // // job.setMapOutputKeyClass(Text.class); // job.setMapOutputValueClass(UserRecord.class); // job.setOutputKeyClass(Text.class); // job.setOutputValueClass(NullWritable.class); // // FileInputFormat.addInputPath(job, new Path(inputPath)); // FileOutputFormat.setOutputPath(job, new Path(outputPath)); // // return job.waitForCompletion(true) ? 0 : 1; // } // // @Override // public Configuration getConf() { // return configuration; // } // // @Override // public void setConf(Configuration configuration) { // this.configuration = configuration; // } // } // // Path: devrank-job/src/main/java/com/yasikstudio/devrank/rank/DeveloperRankJob.java // public class DeveloperRankJob implements Tool { // // private Configuration configuration; // // @Override // public int run(String[] args) throws Exception { // Options options = new Options(); // options.addOption("h", "help", false, "Help"); // options.addOption("i", "inputPath", true, "Input Path"); // options.addOption("o", "outputPath", true, "Output Path"); // options.addOption("w", "workers", true, "Number of workers"); // options.addOption("s", "supersteps", true, "Number of supersteps"); // options.addOption("r", "ratioOptions", true, "followings,forks,pulls,stars,watches"); // // HelpFormatter formatter = new HelpFormatter(); // if (args.length == 0) { // formatter.printHelp(getClass().getName(), options, true); // return 0; // } // CommandLineParser parser = new PosixParser(); // CommandLine cmd = parser.parse(options, args); // if (cmd.hasOption('h')) { // formatter.printHelp(getClass().getName(), options, true); // return 0; // } // // int workers = Integer.parseInt(cmd.getOptionValue('w', "1")); // long supersteps = Long.parseLong(cmd.getOptionValue('s', "10")); // String inputPath = cmd.getOptionValue("inputPath"); // String outputPath = cmd.getOptionValue("outputPath"); // String ratio = cmd.getOptionValue("ratioOptions", "1,1,1,1,1"); // // configuration.setLong("superstep", supersteps); // configuration.setStrings("ratioOptions", ratio); // // String jobname = "devrank-job-rank-" + System.currentTimeMillis(); // GiraphJob job = new GiraphJob(getConf(), jobname); // GiraphConfiguration giraphConf = job.getConfiguration(); // giraphConf.setVertexClass(DeveloperRankVertex.class); // giraphConf.setVertexInputFormatClass(DeveloperRankVertexInputFormat.class); // giraphConf.setVertexOutputFormatClass(DeveloperRankVertexOutputFormat.class); // GiraphFileInputFormat.addVertexInputPath(job.getConfiguration(), new Path(inputPath)); // FileOutputFormat.setOutputPath(job.getInternalJob(), new Path(outputPath)); // giraphConf.setWorkerConfiguration(workers, workers, 100.0f); // return job.run(true) ? 0 : -1; // } // // @Override // public Configuration getConf() { // return configuration; // } // // @Override // public void setConf(Configuration configuration) { // this.configuration = configuration; // } // } // Path: devrank-job/src/main/java/com/yasikstudio/devrank/DevRank.java import java.util.HashMap; import java.util.Map; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import com.google.common.base.Joiner; import com.yasikstudio.devrank.merge.DataMergeJob; import com.yasikstudio.devrank.rank.DeveloperRankJob; package com.yasikstudio.devrank; public class DevRank { private static Map<String, Class<?>> jobs = new HashMap<String, Class<?>>(); static { jobs.put("rank", DeveloperRankJob.class);
jobs.put("merge", DataMergeJob.class);
serendio-labs/diskoveror-ta
src/main/java/com/diskoverorta/utils/EntityUtils.java
// Path: src/main/java/com/diskoverorta/vo/DocumentObject.java // public class DocumentObject // { // String docText = null; // public EntityObject entities = null; // public EntityMap entitiesMeta = null; // // public DocumentObject() // { // entities = new EntityObject(); // entitiesMeta = new EntityMap(); // } // } // // Path: src/main/java/com/diskoverorta/vo/EntityAPISet.java // public class EntityAPISet // { // public Set<String> Currency = null; // public Set<String> Date = null; // public Set<String> Location = null; // public Set<String> Organization = null; // public Set<String> Percent = null; // public Set<String> Person = null; // public Set<String> Time = null; // // public EntityAPISet() // { // // } // }
import com.diskoverorta.vo.DocumentObject; import com.diskoverorta.vo.EntityAPISet; import com.diskoverorta.vo.EntityMap; import com.diskoverorta.vo.EntityObject; import java.util.*;
/******************************************************************************* * Copyright 2015 Serendio Inc. ( http://www.serendio.com/ ) * Author - Praveen Jesudhas * * 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.diskoverorta.utils; /** * Created by praveen on 25/11/14. */ public class EntityUtils { public static EntityMap extractEntityMap(EntityObject eObj) { EntityMap eMap = new EntityMap(); eMap.personCount = getListFrequency(eObj.person); eMap.organizationCount = getListFrequency(eObj.organization); eMap.locationCount = getListFrequency(eObj.location); eMap.personAlias = getAliasMap(eMap.personCount); eMap.organizationAlias = getAliasMap(eMap.organizationCount); eMap.locationAlias = getAliasMap(eMap.locationCount); return eMap; } public static Map<String,Integer> getListFrequency(List<String> elist) { Map<String,Integer> tempMap = new TreeMap<String,Integer>(); for(int i = 0 ; i < elist.size() ; i++) { String temp = elist.get(i).toLowerCase().trim(); if(tempMap.containsKey(temp)) { Integer val = tempMap.get(temp); tempMap.put(temp,val+1); } else tempMap.put(temp,1); } return tempMap; }
// Path: src/main/java/com/diskoverorta/vo/DocumentObject.java // public class DocumentObject // { // String docText = null; // public EntityObject entities = null; // public EntityMap entitiesMeta = null; // // public DocumentObject() // { // entities = new EntityObject(); // entitiesMeta = new EntityMap(); // } // } // // Path: src/main/java/com/diskoverorta/vo/EntityAPISet.java // public class EntityAPISet // { // public Set<String> Currency = null; // public Set<String> Date = null; // public Set<String> Location = null; // public Set<String> Organization = null; // public Set<String> Percent = null; // public Set<String> Person = null; // public Set<String> Time = null; // // public EntityAPISet() // { // // } // } // Path: src/main/java/com/diskoverorta/utils/EntityUtils.java import com.diskoverorta.vo.DocumentObject; import com.diskoverorta.vo.EntityAPISet; import com.diskoverorta.vo.EntityMap; import com.diskoverorta.vo.EntityObject; import java.util.*; /******************************************************************************* * Copyright 2015 Serendio Inc. ( http://www.serendio.com/ ) * Author - Praveen Jesudhas * * 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.diskoverorta.utils; /** * Created by praveen on 25/11/14. */ public class EntityUtils { public static EntityMap extractEntityMap(EntityObject eObj) { EntityMap eMap = new EntityMap(); eMap.personCount = getListFrequency(eObj.person); eMap.organizationCount = getListFrequency(eObj.organization); eMap.locationCount = getListFrequency(eObj.location); eMap.personAlias = getAliasMap(eMap.personCount); eMap.organizationAlias = getAliasMap(eMap.organizationCount); eMap.locationAlias = getAliasMap(eMap.locationCount); return eMap; } public static Map<String,Integer> getListFrequency(List<String> elist) { Map<String,Integer> tempMap = new TreeMap<String,Integer>(); for(int i = 0 ; i < elist.size() ; i++) { String temp = elist.get(i).toLowerCase().trim(); if(tempMap.containsKey(temp)) { Integer val = tempMap.get(temp); tempMap.put(temp,val+1); } else tempMap.put(temp,1); } return tempMap; }
public static EntityAPISet getEntitySet(DocumentObject documentObject)
serendio-labs/diskoveror-ta
src/main/java/com/diskoverorta/utils/EntityUtils.java
// Path: src/main/java/com/diskoverorta/vo/DocumentObject.java // public class DocumentObject // { // String docText = null; // public EntityObject entities = null; // public EntityMap entitiesMeta = null; // // public DocumentObject() // { // entities = new EntityObject(); // entitiesMeta = new EntityMap(); // } // } // // Path: src/main/java/com/diskoverorta/vo/EntityAPISet.java // public class EntityAPISet // { // public Set<String> Currency = null; // public Set<String> Date = null; // public Set<String> Location = null; // public Set<String> Organization = null; // public Set<String> Percent = null; // public Set<String> Person = null; // public Set<String> Time = null; // // public EntityAPISet() // { // // } // }
import com.diskoverorta.vo.DocumentObject; import com.diskoverorta.vo.EntityAPISet; import com.diskoverorta.vo.EntityMap; import com.diskoverorta.vo.EntityObject; import java.util.*;
/******************************************************************************* * Copyright 2015 Serendio Inc. ( http://www.serendio.com/ ) * Author - Praveen Jesudhas * * 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.diskoverorta.utils; /** * Created by praveen on 25/11/14. */ public class EntityUtils { public static EntityMap extractEntityMap(EntityObject eObj) { EntityMap eMap = new EntityMap(); eMap.personCount = getListFrequency(eObj.person); eMap.organizationCount = getListFrequency(eObj.organization); eMap.locationCount = getListFrequency(eObj.location); eMap.personAlias = getAliasMap(eMap.personCount); eMap.organizationAlias = getAliasMap(eMap.organizationCount); eMap.locationAlias = getAliasMap(eMap.locationCount); return eMap; } public static Map<String,Integer> getListFrequency(List<String> elist) { Map<String,Integer> tempMap = new TreeMap<String,Integer>(); for(int i = 0 ; i < elist.size() ; i++) { String temp = elist.get(i).toLowerCase().trim(); if(tempMap.containsKey(temp)) { Integer val = tempMap.get(temp); tempMap.put(temp,val+1); } else tempMap.put(temp,1); } return tempMap; }
// Path: src/main/java/com/diskoverorta/vo/DocumentObject.java // public class DocumentObject // { // String docText = null; // public EntityObject entities = null; // public EntityMap entitiesMeta = null; // // public DocumentObject() // { // entities = new EntityObject(); // entitiesMeta = new EntityMap(); // } // } // // Path: src/main/java/com/diskoverorta/vo/EntityAPISet.java // public class EntityAPISet // { // public Set<String> Currency = null; // public Set<String> Date = null; // public Set<String> Location = null; // public Set<String> Organization = null; // public Set<String> Percent = null; // public Set<String> Person = null; // public Set<String> Time = null; // // public EntityAPISet() // { // // } // } // Path: src/main/java/com/diskoverorta/utils/EntityUtils.java import com.diskoverorta.vo.DocumentObject; import com.diskoverorta.vo.EntityAPISet; import com.diskoverorta.vo.EntityMap; import com.diskoverorta.vo.EntityObject; import java.util.*; /******************************************************************************* * Copyright 2015 Serendio Inc. ( http://www.serendio.com/ ) * Author - Praveen Jesudhas * * 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.diskoverorta.utils; /** * Created by praveen on 25/11/14. */ public class EntityUtils { public static EntityMap extractEntityMap(EntityObject eObj) { EntityMap eMap = new EntityMap(); eMap.personCount = getListFrequency(eObj.person); eMap.organizationCount = getListFrequency(eObj.organization); eMap.locationCount = getListFrequency(eObj.location); eMap.personAlias = getAliasMap(eMap.personCount); eMap.organizationAlias = getAliasMap(eMap.organizationCount); eMap.locationAlias = getAliasMap(eMap.locationCount); return eMap; } public static Map<String,Integer> getListFrequency(List<String> elist) { Map<String,Integer> tempMap = new TreeMap<String,Integer>(); for(int i = 0 ; i < elist.size() ; i++) { String temp = elist.get(i).toLowerCase().trim(); if(tempMap.containsKey(temp)) { Integer val = tempMap.get(temp); tempMap.put(temp,val+1); } else tempMap.put(temp,1); } return tempMap; }
public static EntityAPISet getEntitySet(DocumentObject documentObject)
elefher/CpuHandler
src/com/elefher/customclasses/CpuGpuFreqVoltages.java
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // // Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // }
import java.io.DataOutputStream; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import android.content.Context; import android.util.Log; import com.elefher.utils.CpuUtils; import com.elefher.utils.ReadFile;
package com.elefher.customclasses; public class CpuGpuFreqVoltages { /*private final static String cpufreq_sys_volts = "/sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels"; private final static String gpufreq_sys_volts = "/sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels_GPU"; * gpufreq_sys_volts is an unsued feature!!! */ public CpuGpuFreqVoltages() { } public static ArrayList<String> getCpuVoltages(Context cntx) {
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // // Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // } // Path: src/com/elefher/customclasses/CpuGpuFreqVoltages.java import java.io.DataOutputStream; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import android.content.Context; import android.util.Log; import com.elefher.utils.CpuUtils; import com.elefher.utils.ReadFile; package com.elefher.customclasses; public class CpuGpuFreqVoltages { /*private final static String cpufreq_sys_volts = "/sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels"; private final static String gpufreq_sys_volts = "/sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels_GPU"; * gpufreq_sys_volts is an unsued feature!!! */ public CpuGpuFreqVoltages() { } public static ArrayList<String> getCpuVoltages(Context cntx) {
ArrayList<String> arrayStringList = CpuUtils
elefher/CpuHandler
src/com/elefher/customclasses/CpuGpuFreqVoltages.java
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // // Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // }
import java.io.DataOutputStream; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import android.content.Context; import android.util.Log; import com.elefher.utils.CpuUtils; import com.elefher.utils.ReadFile;
if (addSubVal.isEmpty()) return false; List<String> commands = new ArrayList<String>(); String cpufreq_sys_volts = findFilePath("vdd_levels", cntx); try { commands.add("chmod 0644 " + cpufreq_sys_volts + "\n"); for (String s : addSubVal) { commands.add("echo " + s + " > " + cpufreq_sys_volts + "\n"); } commands.add("exit\n"); Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath()); DataOutputStream dos = new DataOutputStream(p.getOutputStream()); for (String command : commands) { dos.writeBytes(command); dos.flush(); } dos.close(); p.waitFor(); return true; } catch (Exception ex) { Log.e("", ex.toString() + " Error: " + ex.getMessage()); return false; } } private static String findFilePath(String file, Context cntx){ try {
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // // Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // } // Path: src/com/elefher/customclasses/CpuGpuFreqVoltages.java import java.io.DataOutputStream; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import android.content.Context; import android.util.Log; import com.elefher.utils.CpuUtils; import com.elefher.utils.ReadFile; if (addSubVal.isEmpty()) return false; List<String> commands = new ArrayList<String>(); String cpufreq_sys_volts = findFilePath("vdd_levels", cntx); try { commands.add("chmod 0644 " + cpufreq_sys_volts + "\n"); for (String s : addSubVal) { commands.add("echo " + s + " > " + cpufreq_sys_volts + "\n"); } commands.add("exit\n"); Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath()); DataOutputStream dos = new DataOutputStream(p.getOutputStream()); for (String command : commands) { dos.writeBytes(command); dos.flush(); } dos.close(); p.waitFor(); return true; } catch (Exception ex) { Log.e("", ex.toString() + " Error: " + ex.getMessage()); return false; } } private static String findFilePath(String file, Context cntx){ try {
String path = ReadFile.existPath(ReadFile.getListOfFile("data/paths.json", "path", file, cntx));
elefher/CpuHandler
src/com/elefher/extendedclasses/GovernorLinearLayout.java
// Path: src/com/elefher/abstractclasses/CustomLinearLayoutOnTheFly.java // public abstract class CustomLinearLayoutOnTheFly { // protected LinearLayout layout, statusLayout; // protected TextView textView; // protected MiscProgressBar progressBar; // protected LinearLayout.LayoutParams progressBarParams, textViewParams, layoutParams, statusLayoutParams; // // public void textViewAddView(){ // layout.addView(textView); // } // // public void progressBarAddView(){ // layout.addView(progressBar); // } // // public void display(){ // statusLayout.setOrientation(LinearLayout.VERTICAL); // statusLayout.addView(layout); // } // // public LinearLayout getLayout(){ // return layout; // } // // public abstract void layoutSettings(); // public abstract void layoutParams(); // public abstract void textViewSettings(); // public abstract void textViewParams(); // public abstract void setText(); // public abstract void progressBarSettings(); // public abstract void progressBarParams(); // public abstract void setCurrentProgressBar(); // public abstract void update(); // } // // Path: src/com/elefher/customclasses/CpuGovernors.java // public class CpuGovernors { // // public CpuGovernors() { // // } // // public static String[] getAvailableGovernors(Context cntx) { // String[] governors = CpuUtils.readStringArray(findFilePath("scaling_available_governors", cntx)); // // // In case does not exist governors return null // if (governors == null) { // return null; // } // // return governors; // } // // public static String getCurrentGovernor(Context cntx){ // String currentGov = ""; // try { // currentGov = ReadFile.getStringOfFile(findFilePath("scaling_governor", cntx)); // }catch (NullPointerException e){ // currentGov = "Unknown"; // e.printStackTrace(); // } // return currentGov; // } // // public static boolean setGovernor(String governor, Context cntx){ // if(governor.isEmpty()) // return false; // // String scaling_governor = findFilePath("scaling_governor", cntx); // int cores = CpuStat.getNumCores(); // try { // List<String> commands = new ArrayList<String>(); // // for (int i = 0; i < cores; i++) { // /* // * Prepare permissions so that we can write // */ // commands.add("chmod 0664 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // commands.add("echo " + governor + " > " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // /* // * Set permissions in initial state // */ // commands.add("chmod 0444 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // } // // commands.add("exit\n"); // // Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath()); // DataOutputStream dos = new DataOutputStream(p.getOutputStream()); // for (String command : commands) { // dos.writeBytes(command); // dos.flush(); // } // dos.close(); // // p.waitFor(); // return true; // } catch (Exception ex) { // Log.e("", ex.toString() + " Error: " + ex.getMessage()); // return false; // } // } // // private static String findFilePath(String file, Context cntx){ // try { // String path = ReadFile.existPath(ReadFile.getListOfFile("data/paths.json", "path", file, cntx)); // return path; // } catch (JSONException e) { // e.printStackTrace(); // } // return null; // } // }
import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.widget.LinearLayout; import android.widget.TextView; import com.elefher.abstractclasses.CustomLinearLayoutOnTheFly; import com.elefher.customclasses.CpuGovernors;
layout.setLayoutParams(layoutParams); layout.setOrientation(LinearLayout.HORIZONTAL); } @Override public void layoutParams() { layoutParams = new LinearLayout.LayoutParams( android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.MATCH_PARENT, 1.0f); } @Override public void textViewSettings() { textView = new TextView(cntx); textViewParams(); textView.setLayoutParams(textViewParams); textView.setTypeface(Typeface.MONOSPACE); textView.setTextColor(Color.WHITE); textView.setTextSize(15); } @Override public void textViewParams() { textViewParams = new LinearLayout.LayoutParams( android.view.ViewGroup.LayoutParams.FILL_PARENT, 50); textViewParams.setMargins(20, 20, 0, 0); } @Override public void setText() {
// Path: src/com/elefher/abstractclasses/CustomLinearLayoutOnTheFly.java // public abstract class CustomLinearLayoutOnTheFly { // protected LinearLayout layout, statusLayout; // protected TextView textView; // protected MiscProgressBar progressBar; // protected LinearLayout.LayoutParams progressBarParams, textViewParams, layoutParams, statusLayoutParams; // // public void textViewAddView(){ // layout.addView(textView); // } // // public void progressBarAddView(){ // layout.addView(progressBar); // } // // public void display(){ // statusLayout.setOrientation(LinearLayout.VERTICAL); // statusLayout.addView(layout); // } // // public LinearLayout getLayout(){ // return layout; // } // // public abstract void layoutSettings(); // public abstract void layoutParams(); // public abstract void textViewSettings(); // public abstract void textViewParams(); // public abstract void setText(); // public abstract void progressBarSettings(); // public abstract void progressBarParams(); // public abstract void setCurrentProgressBar(); // public abstract void update(); // } // // Path: src/com/elefher/customclasses/CpuGovernors.java // public class CpuGovernors { // // public CpuGovernors() { // // } // // public static String[] getAvailableGovernors(Context cntx) { // String[] governors = CpuUtils.readStringArray(findFilePath("scaling_available_governors", cntx)); // // // In case does not exist governors return null // if (governors == null) { // return null; // } // // return governors; // } // // public static String getCurrentGovernor(Context cntx){ // String currentGov = ""; // try { // currentGov = ReadFile.getStringOfFile(findFilePath("scaling_governor", cntx)); // }catch (NullPointerException e){ // currentGov = "Unknown"; // e.printStackTrace(); // } // return currentGov; // } // // public static boolean setGovernor(String governor, Context cntx){ // if(governor.isEmpty()) // return false; // // String scaling_governor = findFilePath("scaling_governor", cntx); // int cores = CpuStat.getNumCores(); // try { // List<String> commands = new ArrayList<String>(); // // for (int i = 0; i < cores; i++) { // /* // * Prepare permissions so that we can write // */ // commands.add("chmod 0664 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // commands.add("echo " + governor + " > " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // /* // * Set permissions in initial state // */ // commands.add("chmod 0444 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // } // // commands.add("exit\n"); // // Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath()); // DataOutputStream dos = new DataOutputStream(p.getOutputStream()); // for (String command : commands) { // dos.writeBytes(command); // dos.flush(); // } // dos.close(); // // p.waitFor(); // return true; // } catch (Exception ex) { // Log.e("", ex.toString() + " Error: " + ex.getMessage()); // return false; // } // } // // private static String findFilePath(String file, Context cntx){ // try { // String path = ReadFile.existPath(ReadFile.getListOfFile("data/paths.json", "path", file, cntx)); // return path; // } catch (JSONException e) { // e.printStackTrace(); // } // return null; // } // } // Path: src/com/elefher/extendedclasses/GovernorLinearLayout.java import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.widget.LinearLayout; import android.widget.TextView; import com.elefher.abstractclasses.CustomLinearLayoutOnTheFly; import com.elefher.customclasses.CpuGovernors; layout.setLayoutParams(layoutParams); layout.setOrientation(LinearLayout.HORIZONTAL); } @Override public void layoutParams() { layoutParams = new LinearLayout.LayoutParams( android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.MATCH_PARENT, 1.0f); } @Override public void textViewSettings() { textView = new TextView(cntx); textViewParams(); textView.setLayoutParams(textViewParams); textView.setTypeface(Typeface.MONOSPACE); textView.setTextColor(Color.WHITE); textView.setTextSize(15); } @Override public void textViewParams() { textViewParams = new LinearLayout.LayoutParams( android.view.ViewGroup.LayoutParams.FILL_PARENT, 50); textViewParams.setMargins(20, 20, 0, 0); } @Override public void setText() {
textView.setText("Governor: " + CpuGovernors.getCurrentGovernor(cntx)
elefher/CpuHandler
src/com/elefher/implementation/CpuGovernorPicker.java
// Path: src/com/elefher/customclasses/CpuGovernors.java // public class CpuGovernors { // // public CpuGovernors() { // // } // // public static String[] getAvailableGovernors(Context cntx) { // String[] governors = CpuUtils.readStringArray(findFilePath("scaling_available_governors", cntx)); // // // In case does not exist governors return null // if (governors == null) { // return null; // } // // return governors; // } // // public static String getCurrentGovernor(Context cntx){ // String currentGov = ""; // try { // currentGov = ReadFile.getStringOfFile(findFilePath("scaling_governor", cntx)); // }catch (NullPointerException e){ // currentGov = "Unknown"; // e.printStackTrace(); // } // return currentGov; // } // // public static boolean setGovernor(String governor, Context cntx){ // if(governor.isEmpty()) // return false; // // String scaling_governor = findFilePath("scaling_governor", cntx); // int cores = CpuStat.getNumCores(); // try { // List<String> commands = new ArrayList<String>(); // // for (int i = 0; i < cores; i++) { // /* // * Prepare permissions so that we can write // */ // commands.add("chmod 0664 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // commands.add("echo " + governor + " > " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // /* // * Set permissions in initial state // */ // commands.add("chmod 0444 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // } // // commands.add("exit\n"); // // Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath()); // DataOutputStream dos = new DataOutputStream(p.getOutputStream()); // for (String command : commands) { // dos.writeBytes(command); // dos.flush(); // } // dos.close(); // // p.waitFor(); // return true; // } catch (Exception ex) { // Log.e("", ex.toString() + " Error: " + ex.getMessage()); // return false; // } // } // // private static String findFilePath(String file, Context cntx){ // try { // String path = ReadFile.existPath(ReadFile.getListOfFile("data/paths.json", "path", file, cntx)); // return path; // } catch (JSONException e) { // e.printStackTrace(); // } // return null; // } // } // // Path: src/com/elefher/customclasses/DisplayText.java // public class DisplayText { // // Activity activity; // // public DisplayText(Activity act){ // activity = act; // } // // public static void updateText(Activity act, int rIdGovText, String descriptionString){ // TextView currentCpuString = (TextView) act.findViewById(rIdGovText); // currentCpuString.setText(descriptionString); // } // } // // Path: src/com/elefher/extendedclasses/AlertGovernors.java // public class AlertGovernors extends AlertDialogUtils { // // Activity activity; // // public AlertGovernors(Activity act) { // super(act); // activity = act; // // // Set id button // createButton(R.id.governorButton); // // // Set available governors to dialog // setItems(CpuGovernors.getAvailableGovernors(activity.getApplicationContext())); // // // Set icon and tile for the dialog // setIcon(R.drawable.ic_launcher); // setTitle("Governor: Choose your Governor"); // // /* // * Set positive and negative button // */ // setPositiveButton("Select", new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, int which) { // // /* // * Display message if user haven't choose a governor // */ // if (getStringItem.isEmpty()){ // Toast.makeText(activity, "You have to choose a governor first!!", Toast.LENGTH_LONG).show(); // return; // } // // /* // * Set the cpu Governor and update info about the current governor // */ // boolean governorChanged = CpuGovernors.setGovernor(getStringItem, activity); // if(!governorChanged){ // Toast.makeText(activity, "Sorry, but the governor didn't change!!", Toast.LENGTH_LONG).show(); // } else if(governorChanged){ // Toast.makeText(activity, "The governor has changed to " + CpuGovernors.getCurrentGovernor(activity) + // "!!", Toast.LENGTH_LONG).show(); // } // // // Update the current governor // DisplayText.updateText(activity, R.id.updatedCurrentGov, CpuGovernors.getCurrentGovernor(activity)); // // /* // * Initialize var getStringItem in order to delete the preview choose // */ // getStringItem = ""; // // } // }); // // setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, int which) { // // TODO Auto-generated method stub // // } // }); // } // }
import com.cpu.handler.R; import com.elefher.customclasses.CpuGovernors; import com.elefher.customclasses.DisplayText; import com.elefher.extendedclasses.AlertGovernors; import android.app.Activity;
package com.elefher.implementation; public class CpuGovernorPicker { Activity activity; public CpuGovernorPicker(Activity act) { activity = act; /* * Display governors in an alert dialog and user can * change a governor */
// Path: src/com/elefher/customclasses/CpuGovernors.java // public class CpuGovernors { // // public CpuGovernors() { // // } // // public static String[] getAvailableGovernors(Context cntx) { // String[] governors = CpuUtils.readStringArray(findFilePath("scaling_available_governors", cntx)); // // // In case does not exist governors return null // if (governors == null) { // return null; // } // // return governors; // } // // public static String getCurrentGovernor(Context cntx){ // String currentGov = ""; // try { // currentGov = ReadFile.getStringOfFile(findFilePath("scaling_governor", cntx)); // }catch (NullPointerException e){ // currentGov = "Unknown"; // e.printStackTrace(); // } // return currentGov; // } // // public static boolean setGovernor(String governor, Context cntx){ // if(governor.isEmpty()) // return false; // // String scaling_governor = findFilePath("scaling_governor", cntx); // int cores = CpuStat.getNumCores(); // try { // List<String> commands = new ArrayList<String>(); // // for (int i = 0; i < cores; i++) { // /* // * Prepare permissions so that we can write // */ // commands.add("chmod 0664 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // commands.add("echo " + governor + " > " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // /* // * Set permissions in initial state // */ // commands.add("chmod 0444 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // } // // commands.add("exit\n"); // // Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath()); // DataOutputStream dos = new DataOutputStream(p.getOutputStream()); // for (String command : commands) { // dos.writeBytes(command); // dos.flush(); // } // dos.close(); // // p.waitFor(); // return true; // } catch (Exception ex) { // Log.e("", ex.toString() + " Error: " + ex.getMessage()); // return false; // } // } // // private static String findFilePath(String file, Context cntx){ // try { // String path = ReadFile.existPath(ReadFile.getListOfFile("data/paths.json", "path", file, cntx)); // return path; // } catch (JSONException e) { // e.printStackTrace(); // } // return null; // } // } // // Path: src/com/elefher/customclasses/DisplayText.java // public class DisplayText { // // Activity activity; // // public DisplayText(Activity act){ // activity = act; // } // // public static void updateText(Activity act, int rIdGovText, String descriptionString){ // TextView currentCpuString = (TextView) act.findViewById(rIdGovText); // currentCpuString.setText(descriptionString); // } // } // // Path: src/com/elefher/extendedclasses/AlertGovernors.java // public class AlertGovernors extends AlertDialogUtils { // // Activity activity; // // public AlertGovernors(Activity act) { // super(act); // activity = act; // // // Set id button // createButton(R.id.governorButton); // // // Set available governors to dialog // setItems(CpuGovernors.getAvailableGovernors(activity.getApplicationContext())); // // // Set icon and tile for the dialog // setIcon(R.drawable.ic_launcher); // setTitle("Governor: Choose your Governor"); // // /* // * Set positive and negative button // */ // setPositiveButton("Select", new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, int which) { // // /* // * Display message if user haven't choose a governor // */ // if (getStringItem.isEmpty()){ // Toast.makeText(activity, "You have to choose a governor first!!", Toast.LENGTH_LONG).show(); // return; // } // // /* // * Set the cpu Governor and update info about the current governor // */ // boolean governorChanged = CpuGovernors.setGovernor(getStringItem, activity); // if(!governorChanged){ // Toast.makeText(activity, "Sorry, but the governor didn't change!!", Toast.LENGTH_LONG).show(); // } else if(governorChanged){ // Toast.makeText(activity, "The governor has changed to " + CpuGovernors.getCurrentGovernor(activity) + // "!!", Toast.LENGTH_LONG).show(); // } // // // Update the current governor // DisplayText.updateText(activity, R.id.updatedCurrentGov, CpuGovernors.getCurrentGovernor(activity)); // // /* // * Initialize var getStringItem in order to delete the preview choose // */ // getStringItem = ""; // // } // }); // // setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, int which) { // // TODO Auto-generated method stub // // } // }); // } // } // Path: src/com/elefher/implementation/CpuGovernorPicker.java import com.cpu.handler.R; import com.elefher.customclasses.CpuGovernors; import com.elefher.customclasses.DisplayText; import com.elefher.extendedclasses.AlertGovernors; import android.app.Activity; package com.elefher.implementation; public class CpuGovernorPicker { Activity activity; public CpuGovernorPicker(Activity act) { activity = act; /* * Display governors in an alert dialog and user can * change a governor */
AlertGovernors alertGovernors = new AlertGovernors(activity);
elefher/CpuHandler
src/com/elefher/implementation/CpuGovernorPicker.java
// Path: src/com/elefher/customclasses/CpuGovernors.java // public class CpuGovernors { // // public CpuGovernors() { // // } // // public static String[] getAvailableGovernors(Context cntx) { // String[] governors = CpuUtils.readStringArray(findFilePath("scaling_available_governors", cntx)); // // // In case does not exist governors return null // if (governors == null) { // return null; // } // // return governors; // } // // public static String getCurrentGovernor(Context cntx){ // String currentGov = ""; // try { // currentGov = ReadFile.getStringOfFile(findFilePath("scaling_governor", cntx)); // }catch (NullPointerException e){ // currentGov = "Unknown"; // e.printStackTrace(); // } // return currentGov; // } // // public static boolean setGovernor(String governor, Context cntx){ // if(governor.isEmpty()) // return false; // // String scaling_governor = findFilePath("scaling_governor", cntx); // int cores = CpuStat.getNumCores(); // try { // List<String> commands = new ArrayList<String>(); // // for (int i = 0; i < cores; i++) { // /* // * Prepare permissions so that we can write // */ // commands.add("chmod 0664 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // commands.add("echo " + governor + " > " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // /* // * Set permissions in initial state // */ // commands.add("chmod 0444 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // } // // commands.add("exit\n"); // // Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath()); // DataOutputStream dos = new DataOutputStream(p.getOutputStream()); // for (String command : commands) { // dos.writeBytes(command); // dos.flush(); // } // dos.close(); // // p.waitFor(); // return true; // } catch (Exception ex) { // Log.e("", ex.toString() + " Error: " + ex.getMessage()); // return false; // } // } // // private static String findFilePath(String file, Context cntx){ // try { // String path = ReadFile.existPath(ReadFile.getListOfFile("data/paths.json", "path", file, cntx)); // return path; // } catch (JSONException e) { // e.printStackTrace(); // } // return null; // } // } // // Path: src/com/elefher/customclasses/DisplayText.java // public class DisplayText { // // Activity activity; // // public DisplayText(Activity act){ // activity = act; // } // // public static void updateText(Activity act, int rIdGovText, String descriptionString){ // TextView currentCpuString = (TextView) act.findViewById(rIdGovText); // currentCpuString.setText(descriptionString); // } // } // // Path: src/com/elefher/extendedclasses/AlertGovernors.java // public class AlertGovernors extends AlertDialogUtils { // // Activity activity; // // public AlertGovernors(Activity act) { // super(act); // activity = act; // // // Set id button // createButton(R.id.governorButton); // // // Set available governors to dialog // setItems(CpuGovernors.getAvailableGovernors(activity.getApplicationContext())); // // // Set icon and tile for the dialog // setIcon(R.drawable.ic_launcher); // setTitle("Governor: Choose your Governor"); // // /* // * Set positive and negative button // */ // setPositiveButton("Select", new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, int which) { // // /* // * Display message if user haven't choose a governor // */ // if (getStringItem.isEmpty()){ // Toast.makeText(activity, "You have to choose a governor first!!", Toast.LENGTH_LONG).show(); // return; // } // // /* // * Set the cpu Governor and update info about the current governor // */ // boolean governorChanged = CpuGovernors.setGovernor(getStringItem, activity); // if(!governorChanged){ // Toast.makeText(activity, "Sorry, but the governor didn't change!!", Toast.LENGTH_LONG).show(); // } else if(governorChanged){ // Toast.makeText(activity, "The governor has changed to " + CpuGovernors.getCurrentGovernor(activity) + // "!!", Toast.LENGTH_LONG).show(); // } // // // Update the current governor // DisplayText.updateText(activity, R.id.updatedCurrentGov, CpuGovernors.getCurrentGovernor(activity)); // // /* // * Initialize var getStringItem in order to delete the preview choose // */ // getStringItem = ""; // // } // }); // // setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, int which) { // // TODO Auto-generated method stub // // } // }); // } // }
import com.cpu.handler.R; import com.elefher.customclasses.CpuGovernors; import com.elefher.customclasses.DisplayText; import com.elefher.extendedclasses.AlertGovernors; import android.app.Activity;
package com.elefher.implementation; public class CpuGovernorPicker { Activity activity; public CpuGovernorPicker(Activity act) { activity = act; /* * Display governors in an alert dialog and user can * change a governor */ AlertGovernors alertGovernors = new AlertGovernors(activity); /* * Display the current governor */
// Path: src/com/elefher/customclasses/CpuGovernors.java // public class CpuGovernors { // // public CpuGovernors() { // // } // // public static String[] getAvailableGovernors(Context cntx) { // String[] governors = CpuUtils.readStringArray(findFilePath("scaling_available_governors", cntx)); // // // In case does not exist governors return null // if (governors == null) { // return null; // } // // return governors; // } // // public static String getCurrentGovernor(Context cntx){ // String currentGov = ""; // try { // currentGov = ReadFile.getStringOfFile(findFilePath("scaling_governor", cntx)); // }catch (NullPointerException e){ // currentGov = "Unknown"; // e.printStackTrace(); // } // return currentGov; // } // // public static boolean setGovernor(String governor, Context cntx){ // if(governor.isEmpty()) // return false; // // String scaling_governor = findFilePath("scaling_governor", cntx); // int cores = CpuStat.getNumCores(); // try { // List<String> commands = new ArrayList<String>(); // // for (int i = 0; i < cores; i++) { // /* // * Prepare permissions so that we can write // */ // commands.add("chmod 0664 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // commands.add("echo " + governor + " > " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // /* // * Set permissions in initial state // */ // commands.add("chmod 0444 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // } // // commands.add("exit\n"); // // Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath()); // DataOutputStream dos = new DataOutputStream(p.getOutputStream()); // for (String command : commands) { // dos.writeBytes(command); // dos.flush(); // } // dos.close(); // // p.waitFor(); // return true; // } catch (Exception ex) { // Log.e("", ex.toString() + " Error: " + ex.getMessage()); // return false; // } // } // // private static String findFilePath(String file, Context cntx){ // try { // String path = ReadFile.existPath(ReadFile.getListOfFile("data/paths.json", "path", file, cntx)); // return path; // } catch (JSONException e) { // e.printStackTrace(); // } // return null; // } // } // // Path: src/com/elefher/customclasses/DisplayText.java // public class DisplayText { // // Activity activity; // // public DisplayText(Activity act){ // activity = act; // } // // public static void updateText(Activity act, int rIdGovText, String descriptionString){ // TextView currentCpuString = (TextView) act.findViewById(rIdGovText); // currentCpuString.setText(descriptionString); // } // } // // Path: src/com/elefher/extendedclasses/AlertGovernors.java // public class AlertGovernors extends AlertDialogUtils { // // Activity activity; // // public AlertGovernors(Activity act) { // super(act); // activity = act; // // // Set id button // createButton(R.id.governorButton); // // // Set available governors to dialog // setItems(CpuGovernors.getAvailableGovernors(activity.getApplicationContext())); // // // Set icon and tile for the dialog // setIcon(R.drawable.ic_launcher); // setTitle("Governor: Choose your Governor"); // // /* // * Set positive and negative button // */ // setPositiveButton("Select", new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, int which) { // // /* // * Display message if user haven't choose a governor // */ // if (getStringItem.isEmpty()){ // Toast.makeText(activity, "You have to choose a governor first!!", Toast.LENGTH_LONG).show(); // return; // } // // /* // * Set the cpu Governor and update info about the current governor // */ // boolean governorChanged = CpuGovernors.setGovernor(getStringItem, activity); // if(!governorChanged){ // Toast.makeText(activity, "Sorry, but the governor didn't change!!", Toast.LENGTH_LONG).show(); // } else if(governorChanged){ // Toast.makeText(activity, "The governor has changed to " + CpuGovernors.getCurrentGovernor(activity) + // "!!", Toast.LENGTH_LONG).show(); // } // // // Update the current governor // DisplayText.updateText(activity, R.id.updatedCurrentGov, CpuGovernors.getCurrentGovernor(activity)); // // /* // * Initialize var getStringItem in order to delete the preview choose // */ // getStringItem = ""; // // } // }); // // setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, int which) { // // TODO Auto-generated method stub // // } // }); // } // } // Path: src/com/elefher/implementation/CpuGovernorPicker.java import com.cpu.handler.R; import com.elefher.customclasses.CpuGovernors; import com.elefher.customclasses.DisplayText; import com.elefher.extendedclasses.AlertGovernors; import android.app.Activity; package com.elefher.implementation; public class CpuGovernorPicker { Activity activity; public CpuGovernorPicker(Activity act) { activity = act; /* * Display governors in an alert dialog and user can * change a governor */ AlertGovernors alertGovernors = new AlertGovernors(activity); /* * Display the current governor */
DisplayText.updateText(activity, R.id.updatedCurrentGov, CpuGovernors.getCurrentGovernor(activity));
elefher/CpuHandler
src/com/elefher/implementation/CpuGovernorPicker.java
// Path: src/com/elefher/customclasses/CpuGovernors.java // public class CpuGovernors { // // public CpuGovernors() { // // } // // public static String[] getAvailableGovernors(Context cntx) { // String[] governors = CpuUtils.readStringArray(findFilePath("scaling_available_governors", cntx)); // // // In case does not exist governors return null // if (governors == null) { // return null; // } // // return governors; // } // // public static String getCurrentGovernor(Context cntx){ // String currentGov = ""; // try { // currentGov = ReadFile.getStringOfFile(findFilePath("scaling_governor", cntx)); // }catch (NullPointerException e){ // currentGov = "Unknown"; // e.printStackTrace(); // } // return currentGov; // } // // public static boolean setGovernor(String governor, Context cntx){ // if(governor.isEmpty()) // return false; // // String scaling_governor = findFilePath("scaling_governor", cntx); // int cores = CpuStat.getNumCores(); // try { // List<String> commands = new ArrayList<String>(); // // for (int i = 0; i < cores; i++) { // /* // * Prepare permissions so that we can write // */ // commands.add("chmod 0664 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // commands.add("echo " + governor + " > " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // /* // * Set permissions in initial state // */ // commands.add("chmod 0444 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // } // // commands.add("exit\n"); // // Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath()); // DataOutputStream dos = new DataOutputStream(p.getOutputStream()); // for (String command : commands) { // dos.writeBytes(command); // dos.flush(); // } // dos.close(); // // p.waitFor(); // return true; // } catch (Exception ex) { // Log.e("", ex.toString() + " Error: " + ex.getMessage()); // return false; // } // } // // private static String findFilePath(String file, Context cntx){ // try { // String path = ReadFile.existPath(ReadFile.getListOfFile("data/paths.json", "path", file, cntx)); // return path; // } catch (JSONException e) { // e.printStackTrace(); // } // return null; // } // } // // Path: src/com/elefher/customclasses/DisplayText.java // public class DisplayText { // // Activity activity; // // public DisplayText(Activity act){ // activity = act; // } // // public static void updateText(Activity act, int rIdGovText, String descriptionString){ // TextView currentCpuString = (TextView) act.findViewById(rIdGovText); // currentCpuString.setText(descriptionString); // } // } // // Path: src/com/elefher/extendedclasses/AlertGovernors.java // public class AlertGovernors extends AlertDialogUtils { // // Activity activity; // // public AlertGovernors(Activity act) { // super(act); // activity = act; // // // Set id button // createButton(R.id.governorButton); // // // Set available governors to dialog // setItems(CpuGovernors.getAvailableGovernors(activity.getApplicationContext())); // // // Set icon and tile for the dialog // setIcon(R.drawable.ic_launcher); // setTitle("Governor: Choose your Governor"); // // /* // * Set positive and negative button // */ // setPositiveButton("Select", new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, int which) { // // /* // * Display message if user haven't choose a governor // */ // if (getStringItem.isEmpty()){ // Toast.makeText(activity, "You have to choose a governor first!!", Toast.LENGTH_LONG).show(); // return; // } // // /* // * Set the cpu Governor and update info about the current governor // */ // boolean governorChanged = CpuGovernors.setGovernor(getStringItem, activity); // if(!governorChanged){ // Toast.makeText(activity, "Sorry, but the governor didn't change!!", Toast.LENGTH_LONG).show(); // } else if(governorChanged){ // Toast.makeText(activity, "The governor has changed to " + CpuGovernors.getCurrentGovernor(activity) + // "!!", Toast.LENGTH_LONG).show(); // } // // // Update the current governor // DisplayText.updateText(activity, R.id.updatedCurrentGov, CpuGovernors.getCurrentGovernor(activity)); // // /* // * Initialize var getStringItem in order to delete the preview choose // */ // getStringItem = ""; // // } // }); // // setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, int which) { // // TODO Auto-generated method stub // // } // }); // } // }
import com.cpu.handler.R; import com.elefher.customclasses.CpuGovernors; import com.elefher.customclasses.DisplayText; import com.elefher.extendedclasses.AlertGovernors; import android.app.Activity;
package com.elefher.implementation; public class CpuGovernorPicker { Activity activity; public CpuGovernorPicker(Activity act) { activity = act; /* * Display governors in an alert dialog and user can * change a governor */ AlertGovernors alertGovernors = new AlertGovernors(activity); /* * Display the current governor */
// Path: src/com/elefher/customclasses/CpuGovernors.java // public class CpuGovernors { // // public CpuGovernors() { // // } // // public static String[] getAvailableGovernors(Context cntx) { // String[] governors = CpuUtils.readStringArray(findFilePath("scaling_available_governors", cntx)); // // // In case does not exist governors return null // if (governors == null) { // return null; // } // // return governors; // } // // public static String getCurrentGovernor(Context cntx){ // String currentGov = ""; // try { // currentGov = ReadFile.getStringOfFile(findFilePath("scaling_governor", cntx)); // }catch (NullPointerException e){ // currentGov = "Unknown"; // e.printStackTrace(); // } // return currentGov; // } // // public static boolean setGovernor(String governor, Context cntx){ // if(governor.isEmpty()) // return false; // // String scaling_governor = findFilePath("scaling_governor", cntx); // int cores = CpuStat.getNumCores(); // try { // List<String> commands = new ArrayList<String>(); // // for (int i = 0; i < cores; i++) { // /* // * Prepare permissions so that we can write // */ // commands.add("chmod 0664 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // commands.add("echo " + governor + " > " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // /* // * Set permissions in initial state // */ // commands.add("chmod 0444 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // } // // commands.add("exit\n"); // // Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath()); // DataOutputStream dos = new DataOutputStream(p.getOutputStream()); // for (String command : commands) { // dos.writeBytes(command); // dos.flush(); // } // dos.close(); // // p.waitFor(); // return true; // } catch (Exception ex) { // Log.e("", ex.toString() + " Error: " + ex.getMessage()); // return false; // } // } // // private static String findFilePath(String file, Context cntx){ // try { // String path = ReadFile.existPath(ReadFile.getListOfFile("data/paths.json", "path", file, cntx)); // return path; // } catch (JSONException e) { // e.printStackTrace(); // } // return null; // } // } // // Path: src/com/elefher/customclasses/DisplayText.java // public class DisplayText { // // Activity activity; // // public DisplayText(Activity act){ // activity = act; // } // // public static void updateText(Activity act, int rIdGovText, String descriptionString){ // TextView currentCpuString = (TextView) act.findViewById(rIdGovText); // currentCpuString.setText(descriptionString); // } // } // // Path: src/com/elefher/extendedclasses/AlertGovernors.java // public class AlertGovernors extends AlertDialogUtils { // // Activity activity; // // public AlertGovernors(Activity act) { // super(act); // activity = act; // // // Set id button // createButton(R.id.governorButton); // // // Set available governors to dialog // setItems(CpuGovernors.getAvailableGovernors(activity.getApplicationContext())); // // // Set icon and tile for the dialog // setIcon(R.drawable.ic_launcher); // setTitle("Governor: Choose your Governor"); // // /* // * Set positive and negative button // */ // setPositiveButton("Select", new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, int which) { // // /* // * Display message if user haven't choose a governor // */ // if (getStringItem.isEmpty()){ // Toast.makeText(activity, "You have to choose a governor first!!", Toast.LENGTH_LONG).show(); // return; // } // // /* // * Set the cpu Governor and update info about the current governor // */ // boolean governorChanged = CpuGovernors.setGovernor(getStringItem, activity); // if(!governorChanged){ // Toast.makeText(activity, "Sorry, but the governor didn't change!!", Toast.LENGTH_LONG).show(); // } else if(governorChanged){ // Toast.makeText(activity, "The governor has changed to " + CpuGovernors.getCurrentGovernor(activity) + // "!!", Toast.LENGTH_LONG).show(); // } // // // Update the current governor // DisplayText.updateText(activity, R.id.updatedCurrentGov, CpuGovernors.getCurrentGovernor(activity)); // // /* // * Initialize var getStringItem in order to delete the preview choose // */ // getStringItem = ""; // // } // }); // // setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, int which) { // // TODO Auto-generated method stub // // } // }); // } // } // Path: src/com/elefher/implementation/CpuGovernorPicker.java import com.cpu.handler.R; import com.elefher.customclasses.CpuGovernors; import com.elefher.customclasses.DisplayText; import com.elefher.extendedclasses.AlertGovernors; import android.app.Activity; package com.elefher.implementation; public class CpuGovernorPicker { Activity activity; public CpuGovernorPicker(Activity act) { activity = act; /* * Display governors in an alert dialog and user can * change a governor */ AlertGovernors alertGovernors = new AlertGovernors(activity); /* * Display the current governor */
DisplayText.updateText(activity, R.id.updatedCurrentGov, CpuGovernors.getCurrentGovernor(activity));
elefher/CpuHandler
src/com/elefher/customclasses/SetVoltagesButton.java
// Path: src/com/elefher/tab/Voltages.java // public class Voltages extends Activity { // // /** Called when the activity is first created. */ // // String[] freqs, volts; // public static ArrayList<SetCpuVoltage> setCpuVoltsList; // public static int lengthObj; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.voltages); // // getActionBar().setDisplayHomeAsUpEnabled(true); // // setCpuVoltagesSeparate(); // // setCpuVoltsList = new ArrayList<SetCpuVoltage>(); // // // Length of cpuVolts objects // lengthObj = volts.length; // // for(int i = 0; i < lengthObj; i++){ // setCpuVoltsList.add(new SetCpuVoltage(this)); // setCpuVoltsList.get(i).setValue(volts[i]); // setCpuVoltsList.get(i).setTitle(freqs[i]); // setCpuVoltsList.get(i).createReachEditText(R.id.voltagesEdit); // } // // SetVoltagesButton setVoltBtn = new SetVoltagesButton(this, "Set Volts"); // setVoltBtn.positionButton(R.id.voltagesEdit); // setVoltBtn.enableButton(); // // UpDownVoltageButtons upDownOffsetBtns = new UpDownVoltageButtons(this); // } // // private void setCpuVoltagesSeparate() { // ArrayList<String> cpuFreqsVolts = CpuGpuFreqVoltages.getCpuVoltages(this); // int size = cpuFreqsVolts.size(); // freqs = new String[size]; // volts = new String[size]; // // /* // * Trim spaces at the end and start of string and after that // * split string. Separate to freqs and volts // */ // for(int i = 0; i < size; i++){ // String[] str = cpuFreqsVolts.get(i).trim().split("\\s+"); // freqs[i] = str[0]; // volts[i] = str[1]; // } // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // // Respond to the action bar's Up/Home button // case android.R.id.home: // NavUtils.navigateUpFromSameTask(this); // return true; // } // return super.onOptionsItemSelected(item); // } // }
import java.util.ArrayList; import com.cpu.handler.R; import com.elefher.tab.Voltages; import android.app.Activity; import android.graphics.Color; import android.graphics.Typeface; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import android.widget.LinearLayout.LayoutParams;
} return offset; } private void offsetDoChanges(){ /* * Check if voltages changed. Also prepare getEditOffset to arraylist * in order to fit in setCpuVoltages function. */ ArrayList<String> offset = new ArrayList<String>(); offset.add(getEditOffset()); if(CpuGpuFreqVoltages.setCpuVoltages(offset, activity)){ Toast.makeText(activity, "Greate the voltages has changed!!", Toast.LENGTH_LONG).show(); UpDownVoltageButtons.offestCount = 0; }else{ if("0".equals(getEditOffset())){ Toast.makeText(activity, "You didn't change voltages!!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(activity, "Somithing went wrong!!", Toast.LENGTH_LONG).show(); } } } /* * Get all freqs and volts from edit texts */ private ArrayList<String> getChanges(){ ArrayList<String> storeNewFreqsVolts = new ArrayList<String>();
// Path: src/com/elefher/tab/Voltages.java // public class Voltages extends Activity { // // /** Called when the activity is first created. */ // // String[] freqs, volts; // public static ArrayList<SetCpuVoltage> setCpuVoltsList; // public static int lengthObj; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.voltages); // // getActionBar().setDisplayHomeAsUpEnabled(true); // // setCpuVoltagesSeparate(); // // setCpuVoltsList = new ArrayList<SetCpuVoltage>(); // // // Length of cpuVolts objects // lengthObj = volts.length; // // for(int i = 0; i < lengthObj; i++){ // setCpuVoltsList.add(new SetCpuVoltage(this)); // setCpuVoltsList.get(i).setValue(volts[i]); // setCpuVoltsList.get(i).setTitle(freqs[i]); // setCpuVoltsList.get(i).createReachEditText(R.id.voltagesEdit); // } // // SetVoltagesButton setVoltBtn = new SetVoltagesButton(this, "Set Volts"); // setVoltBtn.positionButton(R.id.voltagesEdit); // setVoltBtn.enableButton(); // // UpDownVoltageButtons upDownOffsetBtns = new UpDownVoltageButtons(this); // } // // private void setCpuVoltagesSeparate() { // ArrayList<String> cpuFreqsVolts = CpuGpuFreqVoltages.getCpuVoltages(this); // int size = cpuFreqsVolts.size(); // freqs = new String[size]; // volts = new String[size]; // // /* // * Trim spaces at the end and start of string and after that // * split string. Separate to freqs and volts // */ // for(int i = 0; i < size; i++){ // String[] str = cpuFreqsVolts.get(i).trim().split("\\s+"); // freqs[i] = str[0]; // volts[i] = str[1]; // } // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // // Respond to the action bar's Up/Home button // case android.R.id.home: // NavUtils.navigateUpFromSameTask(this); // return true; // } // return super.onOptionsItemSelected(item); // } // } // Path: src/com/elefher/customclasses/SetVoltagesButton.java import java.util.ArrayList; import com.cpu.handler.R; import com.elefher.tab.Voltages; import android.app.Activity; import android.graphics.Color; import android.graphics.Typeface; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import android.widget.LinearLayout.LayoutParams; } return offset; } private void offsetDoChanges(){ /* * Check if voltages changed. Also prepare getEditOffset to arraylist * in order to fit in setCpuVoltages function. */ ArrayList<String> offset = new ArrayList<String>(); offset.add(getEditOffset()); if(CpuGpuFreqVoltages.setCpuVoltages(offset, activity)){ Toast.makeText(activity, "Greate the voltages has changed!!", Toast.LENGTH_LONG).show(); UpDownVoltageButtons.offestCount = 0; }else{ if("0".equals(getEditOffset())){ Toast.makeText(activity, "You didn't change voltages!!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(activity, "Somithing went wrong!!", Toast.LENGTH_LONG).show(); } } } /* * Get all freqs and volts from edit texts */ private ArrayList<String> getChanges(){ ArrayList<String> storeNewFreqsVolts = new ArrayList<String>();
for(int i = 0; i < Voltages.lengthObj; i++){
elefher/CpuHandler
src/com/elefher/extendedclasses/AlertGovernors.java
// Path: src/com/elefher/customclasses/CpuGovernors.java // public class CpuGovernors { // // public CpuGovernors() { // // } // // public static String[] getAvailableGovernors(Context cntx) { // String[] governors = CpuUtils.readStringArray(findFilePath("scaling_available_governors", cntx)); // // // In case does not exist governors return null // if (governors == null) { // return null; // } // // return governors; // } // // public static String getCurrentGovernor(Context cntx){ // String currentGov = ""; // try { // currentGov = ReadFile.getStringOfFile(findFilePath("scaling_governor", cntx)); // }catch (NullPointerException e){ // currentGov = "Unknown"; // e.printStackTrace(); // } // return currentGov; // } // // public static boolean setGovernor(String governor, Context cntx){ // if(governor.isEmpty()) // return false; // // String scaling_governor = findFilePath("scaling_governor", cntx); // int cores = CpuStat.getNumCores(); // try { // List<String> commands = new ArrayList<String>(); // // for (int i = 0; i < cores; i++) { // /* // * Prepare permissions so that we can write // */ // commands.add("chmod 0664 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // commands.add("echo " + governor + " > " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // /* // * Set permissions in initial state // */ // commands.add("chmod 0444 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // } // // commands.add("exit\n"); // // Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath()); // DataOutputStream dos = new DataOutputStream(p.getOutputStream()); // for (String command : commands) { // dos.writeBytes(command); // dos.flush(); // } // dos.close(); // // p.waitFor(); // return true; // } catch (Exception ex) { // Log.e("", ex.toString() + " Error: " + ex.getMessage()); // return false; // } // } // // private static String findFilePath(String file, Context cntx){ // try { // String path = ReadFile.existPath(ReadFile.getListOfFile("data/paths.json", "path", file, cntx)); // return path; // } catch (JSONException e) { // e.printStackTrace(); // } // return null; // } // } // // Path: src/com/elefher/customclasses/DisplayText.java // public class DisplayText { // // Activity activity; // // public DisplayText(Activity act){ // activity = act; // } // // public static void updateText(Activity act, int rIdGovText, String descriptionString){ // TextView currentCpuString = (TextView) act.findViewById(rIdGovText); // currentCpuString.setText(descriptionString); // } // }
import android.app.Activity; import android.content.DialogInterface; import android.widget.Toast; import com.elefher.abstractclasses.*; import com.cpu.handler.R; import com.elefher.customclasses.CpuGovernors; import com.elefher.customclasses.DisplayText;
package com.elefher.extendedclasses; public class AlertGovernors extends AlertDialogUtils { Activity activity; public AlertGovernors(Activity act) { super(act); activity = act; // Set id button createButton(R.id.governorButton); // Set available governors to dialog
// Path: src/com/elefher/customclasses/CpuGovernors.java // public class CpuGovernors { // // public CpuGovernors() { // // } // // public static String[] getAvailableGovernors(Context cntx) { // String[] governors = CpuUtils.readStringArray(findFilePath("scaling_available_governors", cntx)); // // // In case does not exist governors return null // if (governors == null) { // return null; // } // // return governors; // } // // public static String getCurrentGovernor(Context cntx){ // String currentGov = ""; // try { // currentGov = ReadFile.getStringOfFile(findFilePath("scaling_governor", cntx)); // }catch (NullPointerException e){ // currentGov = "Unknown"; // e.printStackTrace(); // } // return currentGov; // } // // public static boolean setGovernor(String governor, Context cntx){ // if(governor.isEmpty()) // return false; // // String scaling_governor = findFilePath("scaling_governor", cntx); // int cores = CpuStat.getNumCores(); // try { // List<String> commands = new ArrayList<String>(); // // for (int i = 0; i < cores; i++) { // /* // * Prepare permissions so that we can write // */ // commands.add("chmod 0664 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // commands.add("echo " + governor + " > " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // /* // * Set permissions in initial state // */ // commands.add("chmod 0444 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // } // // commands.add("exit\n"); // // Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath()); // DataOutputStream dos = new DataOutputStream(p.getOutputStream()); // for (String command : commands) { // dos.writeBytes(command); // dos.flush(); // } // dos.close(); // // p.waitFor(); // return true; // } catch (Exception ex) { // Log.e("", ex.toString() + " Error: " + ex.getMessage()); // return false; // } // } // // private static String findFilePath(String file, Context cntx){ // try { // String path = ReadFile.existPath(ReadFile.getListOfFile("data/paths.json", "path", file, cntx)); // return path; // } catch (JSONException e) { // e.printStackTrace(); // } // return null; // } // } // // Path: src/com/elefher/customclasses/DisplayText.java // public class DisplayText { // // Activity activity; // // public DisplayText(Activity act){ // activity = act; // } // // public static void updateText(Activity act, int rIdGovText, String descriptionString){ // TextView currentCpuString = (TextView) act.findViewById(rIdGovText); // currentCpuString.setText(descriptionString); // } // } // Path: src/com/elefher/extendedclasses/AlertGovernors.java import android.app.Activity; import android.content.DialogInterface; import android.widget.Toast; import com.elefher.abstractclasses.*; import com.cpu.handler.R; import com.elefher.customclasses.CpuGovernors; import com.elefher.customclasses.DisplayText; package com.elefher.extendedclasses; public class AlertGovernors extends AlertDialogUtils { Activity activity; public AlertGovernors(Activity act) { super(act); activity = act; // Set id button createButton(R.id.governorButton); // Set available governors to dialog
setItems(CpuGovernors.getAvailableGovernors(activity.getApplicationContext()));
elefher/CpuHandler
src/com/elefher/extendedclasses/AlertGovernors.java
// Path: src/com/elefher/customclasses/CpuGovernors.java // public class CpuGovernors { // // public CpuGovernors() { // // } // // public static String[] getAvailableGovernors(Context cntx) { // String[] governors = CpuUtils.readStringArray(findFilePath("scaling_available_governors", cntx)); // // // In case does not exist governors return null // if (governors == null) { // return null; // } // // return governors; // } // // public static String getCurrentGovernor(Context cntx){ // String currentGov = ""; // try { // currentGov = ReadFile.getStringOfFile(findFilePath("scaling_governor", cntx)); // }catch (NullPointerException e){ // currentGov = "Unknown"; // e.printStackTrace(); // } // return currentGov; // } // // public static boolean setGovernor(String governor, Context cntx){ // if(governor.isEmpty()) // return false; // // String scaling_governor = findFilePath("scaling_governor", cntx); // int cores = CpuStat.getNumCores(); // try { // List<String> commands = new ArrayList<String>(); // // for (int i = 0; i < cores; i++) { // /* // * Prepare permissions so that we can write // */ // commands.add("chmod 0664 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // commands.add("echo " + governor + " > " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // /* // * Set permissions in initial state // */ // commands.add("chmod 0444 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // } // // commands.add("exit\n"); // // Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath()); // DataOutputStream dos = new DataOutputStream(p.getOutputStream()); // for (String command : commands) { // dos.writeBytes(command); // dos.flush(); // } // dos.close(); // // p.waitFor(); // return true; // } catch (Exception ex) { // Log.e("", ex.toString() + " Error: " + ex.getMessage()); // return false; // } // } // // private static String findFilePath(String file, Context cntx){ // try { // String path = ReadFile.existPath(ReadFile.getListOfFile("data/paths.json", "path", file, cntx)); // return path; // } catch (JSONException e) { // e.printStackTrace(); // } // return null; // } // } // // Path: src/com/elefher/customclasses/DisplayText.java // public class DisplayText { // // Activity activity; // // public DisplayText(Activity act){ // activity = act; // } // // public static void updateText(Activity act, int rIdGovText, String descriptionString){ // TextView currentCpuString = (TextView) act.findViewById(rIdGovText); // currentCpuString.setText(descriptionString); // } // }
import android.app.Activity; import android.content.DialogInterface; import android.widget.Toast; import com.elefher.abstractclasses.*; import com.cpu.handler.R; import com.elefher.customclasses.CpuGovernors; import com.elefher.customclasses.DisplayText;
package com.elefher.extendedclasses; public class AlertGovernors extends AlertDialogUtils { Activity activity; public AlertGovernors(Activity act) { super(act); activity = act; // Set id button createButton(R.id.governorButton); // Set available governors to dialog setItems(CpuGovernors.getAvailableGovernors(activity.getApplicationContext())); // Set icon and tile for the dialog setIcon(R.drawable.ic_launcher); setTitle("Governor: Choose your Governor"); /* * Set positive and negative button */ setPositiveButton("Select", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { /* * Display message if user haven't choose a governor */ if (getStringItem.isEmpty()){ Toast.makeText(activity, "You have to choose a governor first!!", Toast.LENGTH_LONG).show(); return; } /* * Set the cpu Governor and update info about the current governor */ boolean governorChanged = CpuGovernors.setGovernor(getStringItem, activity); if(!governorChanged){ Toast.makeText(activity, "Sorry, but the governor didn't change!!", Toast.LENGTH_LONG).show(); } else if(governorChanged){ Toast.makeText(activity, "The governor has changed to " + CpuGovernors.getCurrentGovernor(activity) + "!!", Toast.LENGTH_LONG).show(); } // Update the current governor
// Path: src/com/elefher/customclasses/CpuGovernors.java // public class CpuGovernors { // // public CpuGovernors() { // // } // // public static String[] getAvailableGovernors(Context cntx) { // String[] governors = CpuUtils.readStringArray(findFilePath("scaling_available_governors", cntx)); // // // In case does not exist governors return null // if (governors == null) { // return null; // } // // return governors; // } // // public static String getCurrentGovernor(Context cntx){ // String currentGov = ""; // try { // currentGov = ReadFile.getStringOfFile(findFilePath("scaling_governor", cntx)); // }catch (NullPointerException e){ // currentGov = "Unknown"; // e.printStackTrace(); // } // return currentGov; // } // // public static boolean setGovernor(String governor, Context cntx){ // if(governor.isEmpty()) // return false; // // String scaling_governor = findFilePath("scaling_governor", cntx); // int cores = CpuStat.getNumCores(); // try { // List<String> commands = new ArrayList<String>(); // // for (int i = 0; i < cores; i++) { // /* // * Prepare permissions so that we can write // */ // commands.add("chmod 0664 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // commands.add("echo " + governor + " > " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // // /* // * Set permissions in initial state // */ // commands.add("chmod 0444 " // + scaling_governor.replace("cpu0", "cpu" + i) + "\n"); // } // // commands.add("exit\n"); // // Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath()); // DataOutputStream dos = new DataOutputStream(p.getOutputStream()); // for (String command : commands) { // dos.writeBytes(command); // dos.flush(); // } // dos.close(); // // p.waitFor(); // return true; // } catch (Exception ex) { // Log.e("", ex.toString() + " Error: " + ex.getMessage()); // return false; // } // } // // private static String findFilePath(String file, Context cntx){ // try { // String path = ReadFile.existPath(ReadFile.getListOfFile("data/paths.json", "path", file, cntx)); // return path; // } catch (JSONException e) { // e.printStackTrace(); // } // return null; // } // } // // Path: src/com/elefher/customclasses/DisplayText.java // public class DisplayText { // // Activity activity; // // public DisplayText(Activity act){ // activity = act; // } // // public static void updateText(Activity act, int rIdGovText, String descriptionString){ // TextView currentCpuString = (TextView) act.findViewById(rIdGovText); // currentCpuString.setText(descriptionString); // } // } // Path: src/com/elefher/extendedclasses/AlertGovernors.java import android.app.Activity; import android.content.DialogInterface; import android.widget.Toast; import com.elefher.abstractclasses.*; import com.cpu.handler.R; import com.elefher.customclasses.CpuGovernors; import com.elefher.customclasses.DisplayText; package com.elefher.extendedclasses; public class AlertGovernors extends AlertDialogUtils { Activity activity; public AlertGovernors(Activity act) { super(act); activity = act; // Set id button createButton(R.id.governorButton); // Set available governors to dialog setItems(CpuGovernors.getAvailableGovernors(activity.getApplicationContext())); // Set icon and tile for the dialog setIcon(R.drawable.ic_launcher); setTitle("Governor: Choose your Governor"); /* * Set positive and negative button */ setPositiveButton("Select", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { /* * Display message if user haven't choose a governor */ if (getStringItem.isEmpty()){ Toast.makeText(activity, "You have to choose a governor first!!", Toast.LENGTH_LONG).show(); return; } /* * Set the cpu Governor and update info about the current governor */ boolean governorChanged = CpuGovernors.setGovernor(getStringItem, activity); if(!governorChanged){ Toast.makeText(activity, "Sorry, but the governor didn't change!!", Toast.LENGTH_LONG).show(); } else if(governorChanged){ Toast.makeText(activity, "The governor has changed to " + CpuGovernors.getCurrentGovernor(activity) + "!!", Toast.LENGTH_LONG).show(); } // Update the current governor
DisplayText.updateText(activity, R.id.updatedCurrentGov, CpuGovernors.getCurrentGovernor(activity));
elefher/CpuHandler
src/com/elefher/abstractclasses/CustomLinearLayoutOnTheFly.java
// Path: src/com/elefher/utils/MiscProgressBar.java // public class MiscProgressBar extends ProgressBar{ // // public int maxCpuProgress, currentCpuProgress; // // public MiscProgressBar(Context context, int Rdrawable, LinearLayout.LayoutParams paramsCircle) { // super(context, null, android.R.attr.progressBarStyleHorizontal); // // setProgressDrawable(getResources().getDrawable(Rdrawable)); // setLayoutParams(paramsCircle); // setIndeterminate(false); // setVisibility(View.VISIBLE); // } // // public void max(int max){ // setMax(max); // maxCpuProgress = max; // } // // public void setCurrentProgress(int percentage){ // setProgress(percentage); // currentCpuProgress = percentage; // } // // public void rotation(int rotate){ // setRotation(rotate); // } // }
import android.widget.LinearLayout; import android.widget.TextView; import com.elefher.utils.MiscProgressBar;
package com.elefher.abstractclasses; /** * Created by elefher on 28/12/2014. */ public abstract class CustomLinearLayoutOnTheFly { protected LinearLayout layout, statusLayout; protected TextView textView;
// Path: src/com/elefher/utils/MiscProgressBar.java // public class MiscProgressBar extends ProgressBar{ // // public int maxCpuProgress, currentCpuProgress; // // public MiscProgressBar(Context context, int Rdrawable, LinearLayout.LayoutParams paramsCircle) { // super(context, null, android.R.attr.progressBarStyleHorizontal); // // setProgressDrawable(getResources().getDrawable(Rdrawable)); // setLayoutParams(paramsCircle); // setIndeterminate(false); // setVisibility(View.VISIBLE); // } // // public void max(int max){ // setMax(max); // maxCpuProgress = max; // } // // public void setCurrentProgress(int percentage){ // setProgress(percentage); // currentCpuProgress = percentage; // } // // public void rotation(int rotate){ // setRotation(rotate); // } // } // Path: src/com/elefher/abstractclasses/CustomLinearLayoutOnTheFly.java import android.widget.LinearLayout; import android.widget.TextView; import com.elefher.utils.MiscProgressBar; package com.elefher.abstractclasses; /** * Created by elefher on 28/12/2014. */ public abstract class CustomLinearLayoutOnTheFly { protected LinearLayout layout, statusLayout; protected TextView textView;
protected MiscProgressBar progressBar;
elefher/CpuHandler
src/com/elefher/customclasses/OnBoot.java
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // }
import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import android.app.Activity; import com.elefher.utils.CpuUtils;
/* * Write commands into file and set it executable */ public boolean setOnBoot(String rootFolder) { String command = ""; if (commands.isEmpty() || shell.isEmpty()) return false; command += shell; for (String c : commands) { command += c; } File f = new File(SYSTEM_INITD + fileName); if (!f.exists()) { createFile(rootFolder, SYSTEM_INITD + fileName); createScript(command, rootFolder, SYSTEM_INITD + fileName); } else { createScript(command, rootFolder, SYSTEM_INITD + fileName); } return true; } private void createFile(String folder, String pathFileToCreate) { try { // Get Root
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // Path: src/com/elefher/customclasses/OnBoot.java import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import android.app.Activity; import com.elefher.utils.CpuUtils; /* * Write commands into file and set it executable */ public boolean setOnBoot(String rootFolder) { String command = ""; if (commands.isEmpty() || shell.isEmpty()) return false; command += shell; for (String c : commands) { command += c; } File f = new File(SYSTEM_INITD + fileName); if (!f.exists()) { createFile(rootFolder, SYSTEM_INITD + fileName); createScript(command, rootFolder, SYSTEM_INITD + fileName); } else { createScript(command, rootFolder, SYSTEM_INITD + fileName); } return true; } private void createFile(String folder, String pathFileToCreate) { try { // Get Root
Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath());
elefher/CpuHandler
src/com/elefher/customclasses/MemoryStat.java
// Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // }
import com.elefher.utils.ReadFile; import android.app.ActivityManager; import android.app.ActivityManager.MemoryInfo; import android.content.Context;
package com.elefher.customclasses; public class MemoryStat { MemoryInfo mi; ActivityManager activityManager; public MemoryStat(Context context) { mi = new MemoryInfo(); activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); } public static long getTotalMemory(){
// Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // } // Path: src/com/elefher/customclasses/MemoryStat.java import com.elefher.utils.ReadFile; import android.app.ActivityManager; import android.app.ActivityManager.MemoryInfo; import android.content.Context; package com.elefher.customclasses; public class MemoryStat { MemoryInfo mi; ActivityManager activityManager; public MemoryStat(Context context) { mi = new MemoryInfo(); activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); } public static long getTotalMemory(){
String strMem = ReadFile.getStringOfFile("/proc/meminfo");
elefher/CpuHandler
src/com/elefher/customclasses/MiscServices.java
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // // Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // }
import java.io.DataOutputStream; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import android.app.Activity; import android.content.Context; import android.util.Log; import com.elefher.utils.CpuUtils; import com.elefher.utils.ReadFile;
package com.elefher.customclasses; /* * TODO this class needs optimization */ public class MiscServices { public MiscServices() { } public static String getFastChargeState(Activity act) {
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // // Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // } // Path: src/com/elefher/customclasses/MiscServices.java import java.io.DataOutputStream; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import android.app.Activity; import android.content.Context; import android.util.Log; import com.elefher.utils.CpuUtils; import com.elefher.utils.ReadFile; package com.elefher.customclasses; /* * TODO this class needs optimization */ public class MiscServices { public MiscServices() { } public static String getFastChargeState(Activity act) {
return ReadFile.getStringOfFile(findFilePath("force_fast_charge", act));
elefher/CpuHandler
src/com/elefher/customclasses/MiscServices.java
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // // Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // }
import java.io.DataOutputStream; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import android.app.Activity; import android.content.Context; import android.util.Log; import com.elefher.utils.CpuUtils; import com.elefher.utils.ReadFile;
package com.elefher.customclasses; /* * TODO this class needs optimization */ public class MiscServices { public MiscServices() { } public static String getFastChargeState(Activity act) { return ReadFile.getStringOfFile(findFilePath("force_fast_charge", act)); } public static boolean setFastChargeState(String state, Context cntx) { String FORCE_FAST_CHARGE = findFilePath("force_fast_charge", cntx); try { List<String> commands = new ArrayList<String>(); commands.add("chmod 0664 " + FORCE_FAST_CHARGE + "\n"); commands.add("echo " + state + " > " + FORCE_FAST_CHARGE + "\n"); commands.add("chmod 0444 " + FORCE_FAST_CHARGE + "\n"); commands.add("exit\n");
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // // Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // } // Path: src/com/elefher/customclasses/MiscServices.java import java.io.DataOutputStream; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import android.app.Activity; import android.content.Context; import android.util.Log; import com.elefher.utils.CpuUtils; import com.elefher.utils.ReadFile; package com.elefher.customclasses; /* * TODO this class needs optimization */ public class MiscServices { public MiscServices() { } public static String getFastChargeState(Activity act) { return ReadFile.getStringOfFile(findFilePath("force_fast_charge", act)); } public static boolean setFastChargeState(String state, Context cntx) { String FORCE_FAST_CHARGE = findFilePath("force_fast_charge", cntx); try { List<String> commands = new ArrayList<String>(); commands.add("chmod 0664 " + FORCE_FAST_CHARGE + "\n"); commands.add("echo " + state + " > " + FORCE_FAST_CHARGE + "\n"); commands.add("chmod 0444 " + FORCE_FAST_CHARGE + "\n"); commands.add("exit\n");
Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath());
elefher/CpuHandler
src/com/elefher/extendedclasses/RamLinearLayout.java
// Path: src/com/elefher/abstractclasses/CustomLinearLayoutOnTheFly.java // public abstract class CustomLinearLayoutOnTheFly { // protected LinearLayout layout, statusLayout; // protected TextView textView; // protected MiscProgressBar progressBar; // protected LinearLayout.LayoutParams progressBarParams, textViewParams, layoutParams, statusLayoutParams; // // public void textViewAddView(){ // layout.addView(textView); // } // // public void progressBarAddView(){ // layout.addView(progressBar); // } // // public void display(){ // statusLayout.setOrientation(LinearLayout.VERTICAL); // statusLayout.addView(layout); // } // // public LinearLayout getLayout(){ // return layout; // } // // public abstract void layoutSettings(); // public abstract void layoutParams(); // public abstract void textViewSettings(); // public abstract void textViewParams(); // public abstract void setText(); // public abstract void progressBarSettings(); // public abstract void progressBarParams(); // public abstract void setCurrentProgressBar(); // public abstract void update(); // } // // Path: src/com/elefher/customclasses/MemoryStat.java // public class MemoryStat { // MemoryInfo mi; // ActivityManager activityManager; // // public MemoryStat(Context context) { // mi = new MemoryInfo(); // activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // } // // public static long getTotalMemory(){ // String strMem = ReadFile.getStringOfFile("/proc/meminfo"); // String [] strM = strMem.split("\\s+"); // // long totalMem = Long.valueOf(strM[1]).longValue() / 1024; // return totalMem; // } // // public long getUsageMemory(){ // activityManager.getMemoryInfo(mi); // long usageMemory = mi.availMem / 1048576L; // return usageMemory; // } // // } // // Path: src/com/elefher/utils/MiscProgressBar.java // public class MiscProgressBar extends ProgressBar{ // // public int maxCpuProgress, currentCpuProgress; // // public MiscProgressBar(Context context, int Rdrawable, LinearLayout.LayoutParams paramsCircle) { // super(context, null, android.R.attr.progressBarStyleHorizontal); // // setProgressDrawable(getResources().getDrawable(Rdrawable)); // setLayoutParams(paramsCircle); // setIndeterminate(false); // setVisibility(View.VISIBLE); // } // // public void max(int max){ // setMax(max); // maxCpuProgress = max; // } // // public void setCurrentProgress(int percentage){ // setProgress(percentage); // currentCpuProgress = percentage; // } // // public void rotation(int rotate){ // setRotation(rotate); // } // }
import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.widget.LinearLayout; import android.widget.TextView; import com.cpu.handler.R; import com.elefher.abstractclasses.CustomLinearLayoutOnTheFly; import com.elefher.customclasses.MemoryStat; import com.elefher.utils.MiscProgressBar;
package com.elefher.extendedclasses; /** * Created by elefher on 31/12/2014. */ public class RamLinearLayout extends CustomLinearLayoutOnTheFly { Context cntx;
// Path: src/com/elefher/abstractclasses/CustomLinearLayoutOnTheFly.java // public abstract class CustomLinearLayoutOnTheFly { // protected LinearLayout layout, statusLayout; // protected TextView textView; // protected MiscProgressBar progressBar; // protected LinearLayout.LayoutParams progressBarParams, textViewParams, layoutParams, statusLayoutParams; // // public void textViewAddView(){ // layout.addView(textView); // } // // public void progressBarAddView(){ // layout.addView(progressBar); // } // // public void display(){ // statusLayout.setOrientation(LinearLayout.VERTICAL); // statusLayout.addView(layout); // } // // public LinearLayout getLayout(){ // return layout; // } // // public abstract void layoutSettings(); // public abstract void layoutParams(); // public abstract void textViewSettings(); // public abstract void textViewParams(); // public abstract void setText(); // public abstract void progressBarSettings(); // public abstract void progressBarParams(); // public abstract void setCurrentProgressBar(); // public abstract void update(); // } // // Path: src/com/elefher/customclasses/MemoryStat.java // public class MemoryStat { // MemoryInfo mi; // ActivityManager activityManager; // // public MemoryStat(Context context) { // mi = new MemoryInfo(); // activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // } // // public static long getTotalMemory(){ // String strMem = ReadFile.getStringOfFile("/proc/meminfo"); // String [] strM = strMem.split("\\s+"); // // long totalMem = Long.valueOf(strM[1]).longValue() / 1024; // return totalMem; // } // // public long getUsageMemory(){ // activityManager.getMemoryInfo(mi); // long usageMemory = mi.availMem / 1048576L; // return usageMemory; // } // // } // // Path: src/com/elefher/utils/MiscProgressBar.java // public class MiscProgressBar extends ProgressBar{ // // public int maxCpuProgress, currentCpuProgress; // // public MiscProgressBar(Context context, int Rdrawable, LinearLayout.LayoutParams paramsCircle) { // super(context, null, android.R.attr.progressBarStyleHorizontal); // // setProgressDrawable(getResources().getDrawable(Rdrawable)); // setLayoutParams(paramsCircle); // setIndeterminate(false); // setVisibility(View.VISIBLE); // } // // public void max(int max){ // setMax(max); // maxCpuProgress = max; // } // // public void setCurrentProgress(int percentage){ // setProgress(percentage); // currentCpuProgress = percentage; // } // // public void rotation(int rotate){ // setRotation(rotate); // } // } // Path: src/com/elefher/extendedclasses/RamLinearLayout.java import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.widget.LinearLayout; import android.widget.TextView; import com.cpu.handler.R; import com.elefher.abstractclasses.CustomLinearLayoutOnTheFly; import com.elefher.customclasses.MemoryStat; import com.elefher.utils.MiscProgressBar; package com.elefher.extendedclasses; /** * Created by elefher on 31/12/2014. */ public class RamLinearLayout extends CustomLinearLayoutOnTheFly { Context cntx;
MemoryStat memoryStat;
elefher/CpuHandler
src/com/elefher/extendedclasses/RamLinearLayout.java
// Path: src/com/elefher/abstractclasses/CustomLinearLayoutOnTheFly.java // public abstract class CustomLinearLayoutOnTheFly { // protected LinearLayout layout, statusLayout; // protected TextView textView; // protected MiscProgressBar progressBar; // protected LinearLayout.LayoutParams progressBarParams, textViewParams, layoutParams, statusLayoutParams; // // public void textViewAddView(){ // layout.addView(textView); // } // // public void progressBarAddView(){ // layout.addView(progressBar); // } // // public void display(){ // statusLayout.setOrientation(LinearLayout.VERTICAL); // statusLayout.addView(layout); // } // // public LinearLayout getLayout(){ // return layout; // } // // public abstract void layoutSettings(); // public abstract void layoutParams(); // public abstract void textViewSettings(); // public abstract void textViewParams(); // public abstract void setText(); // public abstract void progressBarSettings(); // public abstract void progressBarParams(); // public abstract void setCurrentProgressBar(); // public abstract void update(); // } // // Path: src/com/elefher/customclasses/MemoryStat.java // public class MemoryStat { // MemoryInfo mi; // ActivityManager activityManager; // // public MemoryStat(Context context) { // mi = new MemoryInfo(); // activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // } // // public static long getTotalMemory(){ // String strMem = ReadFile.getStringOfFile("/proc/meminfo"); // String [] strM = strMem.split("\\s+"); // // long totalMem = Long.valueOf(strM[1]).longValue() / 1024; // return totalMem; // } // // public long getUsageMemory(){ // activityManager.getMemoryInfo(mi); // long usageMemory = mi.availMem / 1048576L; // return usageMemory; // } // // } // // Path: src/com/elefher/utils/MiscProgressBar.java // public class MiscProgressBar extends ProgressBar{ // // public int maxCpuProgress, currentCpuProgress; // // public MiscProgressBar(Context context, int Rdrawable, LinearLayout.LayoutParams paramsCircle) { // super(context, null, android.R.attr.progressBarStyleHorizontal); // // setProgressDrawable(getResources().getDrawable(Rdrawable)); // setLayoutParams(paramsCircle); // setIndeterminate(false); // setVisibility(View.VISIBLE); // } // // public void max(int max){ // setMax(max); // maxCpuProgress = max; // } // // public void setCurrentProgress(int percentage){ // setProgress(percentage); // currentCpuProgress = percentage; // } // // public void rotation(int rotate){ // setRotation(rotate); // } // }
import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.widget.LinearLayout; import android.widget.TextView; import com.cpu.handler.R; import com.elefher.abstractclasses.CustomLinearLayoutOnTheFly; import com.elefher.customclasses.MemoryStat; import com.elefher.utils.MiscProgressBar;
public void layoutParams() { layoutParams = new LinearLayout.LayoutParams( android.view.ViewGroup.LayoutParams.FILL_PARENT, 60); layoutParams.setMargins(20, 40, 20, 0); } @Override public void textViewSettings() { textView = new TextView(cntx); textViewParams(); textView.setLayoutParams(textViewParams); textView.setTypeface(Typeface.MONOSPACE); textView.setTextColor(Color.WHITE); textView.setTextSize(15); } @Override public void textViewParams() { textViewParams = new LinearLayout.LayoutParams( android.view.ViewGroup.LayoutParams.FILL_PARENT, 50); } @Override public void setText() { textView.setText("Ram Usage: Unknown MB"); } @Override public void progressBarSettings() { progressBarParams();
// Path: src/com/elefher/abstractclasses/CustomLinearLayoutOnTheFly.java // public abstract class CustomLinearLayoutOnTheFly { // protected LinearLayout layout, statusLayout; // protected TextView textView; // protected MiscProgressBar progressBar; // protected LinearLayout.LayoutParams progressBarParams, textViewParams, layoutParams, statusLayoutParams; // // public void textViewAddView(){ // layout.addView(textView); // } // // public void progressBarAddView(){ // layout.addView(progressBar); // } // // public void display(){ // statusLayout.setOrientation(LinearLayout.VERTICAL); // statusLayout.addView(layout); // } // // public LinearLayout getLayout(){ // return layout; // } // // public abstract void layoutSettings(); // public abstract void layoutParams(); // public abstract void textViewSettings(); // public abstract void textViewParams(); // public abstract void setText(); // public abstract void progressBarSettings(); // public abstract void progressBarParams(); // public abstract void setCurrentProgressBar(); // public abstract void update(); // } // // Path: src/com/elefher/customclasses/MemoryStat.java // public class MemoryStat { // MemoryInfo mi; // ActivityManager activityManager; // // public MemoryStat(Context context) { // mi = new MemoryInfo(); // activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // } // // public static long getTotalMemory(){ // String strMem = ReadFile.getStringOfFile("/proc/meminfo"); // String [] strM = strMem.split("\\s+"); // // long totalMem = Long.valueOf(strM[1]).longValue() / 1024; // return totalMem; // } // // public long getUsageMemory(){ // activityManager.getMemoryInfo(mi); // long usageMemory = mi.availMem / 1048576L; // return usageMemory; // } // // } // // Path: src/com/elefher/utils/MiscProgressBar.java // public class MiscProgressBar extends ProgressBar{ // // public int maxCpuProgress, currentCpuProgress; // // public MiscProgressBar(Context context, int Rdrawable, LinearLayout.LayoutParams paramsCircle) { // super(context, null, android.R.attr.progressBarStyleHorizontal); // // setProgressDrawable(getResources().getDrawable(Rdrawable)); // setLayoutParams(paramsCircle); // setIndeterminate(false); // setVisibility(View.VISIBLE); // } // // public void max(int max){ // setMax(max); // maxCpuProgress = max; // } // // public void setCurrentProgress(int percentage){ // setProgress(percentage); // currentCpuProgress = percentage; // } // // public void rotation(int rotate){ // setRotation(rotate); // } // } // Path: src/com/elefher/extendedclasses/RamLinearLayout.java import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.widget.LinearLayout; import android.widget.TextView; import com.cpu.handler.R; import com.elefher.abstractclasses.CustomLinearLayoutOnTheFly; import com.elefher.customclasses.MemoryStat; import com.elefher.utils.MiscProgressBar; public void layoutParams() { layoutParams = new LinearLayout.LayoutParams( android.view.ViewGroup.LayoutParams.FILL_PARENT, 60); layoutParams.setMargins(20, 40, 20, 0); } @Override public void textViewSettings() { textView = new TextView(cntx); textViewParams(); textView.setLayoutParams(textViewParams); textView.setTypeface(Typeface.MONOSPACE); textView.setTextColor(Color.WHITE); textView.setTextSize(15); } @Override public void textViewParams() { textViewParams = new LinearLayout.LayoutParams( android.view.ViewGroup.LayoutParams.FILL_PARENT, 50); } @Override public void setText() { textView.setText("Ram Usage: Unknown MB"); } @Override public void progressBarSettings() { progressBarParams();
progressBar = new MiscProgressBar(cntx, R.drawable.lineprogressbar, progressBarParams);
elefher/CpuHandler
src/com/elefher/customclasses/IOSchedulers.java
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // // Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // }
import java.io.DataOutputStream; import java.io.File; import java.util.ArrayList; import java.util.List; import android.util.Log; import com.elefher.utils.CpuUtils; import com.elefher.utils.ReadFile;
package com.elefher.customclasses; public class IOSchedulers { private final static String ioscheduler = "/sys/block/mmcblk0/queue/scheduler"; private final static String SEARCH_IN_FOLDERS = "(loop|zram|dm-)[0-9]+"; private final static String SEARCH_FOR_READAHEADFOLDER = "179:[0-9]"; public IOSchedulers() { } public static String[] getAvailableIOSchedules() {
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // // Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // } // Path: src/com/elefher/customclasses/IOSchedulers.java import java.io.DataOutputStream; import java.io.File; import java.util.ArrayList; import java.util.List; import android.util.Log; import com.elefher.utils.CpuUtils; import com.elefher.utils.ReadFile; package com.elefher.customclasses; public class IOSchedulers { private final static String ioscheduler = "/sys/block/mmcblk0/queue/scheduler"; private final static String SEARCH_IN_FOLDERS = "(loop|zram|dm-)[0-9]+"; private final static String SEARCH_FOR_READAHEADFOLDER = "179:[0-9]"; public IOSchedulers() { } public static String[] getAvailableIOSchedules() {
String[] ioSchedulers = CpuUtils.readStringArray(ioscheduler);
elefher/CpuHandler
src/com/elefher/customclasses/IOSchedulers.java
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // // Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // }
import java.io.DataOutputStream; import java.io.File; import java.util.ArrayList; import java.util.List; import android.util.Log; import com.elefher.utils.CpuUtils; import com.elefher.utils.ReadFile;
commands.add("exit\n"); Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath()); DataOutputStream dos = new DataOutputStream(p.getOutputStream()); for (String command : commands) { dos.writeBytes(command); dos.flush(); } dos.close(); p.waitFor(); return true; } catch (Exception ex) { Log.e("", ex.toString() + " Error: " + ex.getMessage()); return false; } } /* * This function gets the cache of the sdcard in kb/s */ public static String getReadAheadBufferSize() { try { File folders = new File("/sys/devices/virtual/bdi/"); File[] dirs = folders.listFiles(); for (File dir : dirs) { if (dir.isDirectory() && dir.getName().matches(SEARCH_FOR_READAHEADFOLDER)) { File readAheadFile = new File(dir, "read_ahead_kb"); if (readAheadFile.exists()) {
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // // Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // } // Path: src/com/elefher/customclasses/IOSchedulers.java import java.io.DataOutputStream; import java.io.File; import java.util.ArrayList; import java.util.List; import android.util.Log; import com.elefher.utils.CpuUtils; import com.elefher.utils.ReadFile; commands.add("exit\n"); Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath()); DataOutputStream dos = new DataOutputStream(p.getOutputStream()); for (String command : commands) { dos.writeBytes(command); dos.flush(); } dos.close(); p.waitFor(); return true; } catch (Exception ex) { Log.e("", ex.toString() + " Error: " + ex.getMessage()); return false; } } /* * This function gets the cache of the sdcard in kb/s */ public static String getReadAheadBufferSize() { try { File folders = new File("/sys/devices/virtual/bdi/"); File[] dirs = folders.listFiles(); for (File dir : dirs) { if (dir.isDirectory() && dir.getName().matches(SEARCH_FOR_READAHEADFOLDER)) { File readAheadFile = new File(dir, "read_ahead_kb"); if (readAheadFile.exists()) {
return ReadFile.getStringOfFile(readAheadFile
elefher/CpuHandler
src/com/elefher/customclasses/CpuGovernors.java
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // // Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // }
import java.io.DataOutputStream; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import android.content.Context; import android.util.Log; import com.elefher.utils.CpuUtils; import com.elefher.utils.ReadFile;
package com.elefher.customclasses; public class CpuGovernors { public CpuGovernors() { } public static String[] getAvailableGovernors(Context cntx) {
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // // Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // } // Path: src/com/elefher/customclasses/CpuGovernors.java import java.io.DataOutputStream; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import android.content.Context; import android.util.Log; import com.elefher.utils.CpuUtils; import com.elefher.utils.ReadFile; package com.elefher.customclasses; public class CpuGovernors { public CpuGovernors() { } public static String[] getAvailableGovernors(Context cntx) {
String[] governors = CpuUtils.readStringArray(findFilePath("scaling_available_governors", cntx));
elefher/CpuHandler
src/com/elefher/customclasses/CpuGovernors.java
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // // Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // }
import java.io.DataOutputStream; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import android.content.Context; import android.util.Log; import com.elefher.utils.CpuUtils; import com.elefher.utils.ReadFile;
package com.elefher.customclasses; public class CpuGovernors { public CpuGovernors() { } public static String[] getAvailableGovernors(Context cntx) { String[] governors = CpuUtils.readStringArray(findFilePath("scaling_available_governors", cntx)); // In case does not exist governors return null if (governors == null) { return null; } return governors; } public static String getCurrentGovernor(Context cntx){ String currentGov = ""; try {
// Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // // Path: src/com/elefher/utils/ReadFile.java // public class ReadFile { // // public ReadFile() { // // TODO Auto-generated constructor stub // } // // public static String getStringOfFile(String file) { // String cpuFreq = ""; // RandomAccessFile reader; // try { // reader = new RandomAccessFile(file, "r"); // cpuFreq = reader.readLine(); // reader.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return cpuFreq; // } // // public static ArrayList<String> getListOfFile(String fileToRead, String oBj, String searchPath, Context cntx) throws JSONException { // JSONObject jsonObj = new JSONObject(loadJSONFromAssets(fileToRead, cntx)); // JSONArray jsonPaths = jsonObj.getJSONArray(oBj); // // int jsonPathsLength = jsonPaths.length(); // ArrayList<String> pathList = new ArrayList<String>(); // // for (int i = 0; i < jsonPathsLength; i++) { // // check if searchPath is equal with object // if(jsonPaths.getJSONObject(i).names().toString().toLowerCase().indexOf(searchPath) != -1){ // // Store every value from array to an ArrayList // JSONArray jArr = jsonPaths.getJSONObject(i).getJSONArray(searchPath); // int jsonArrLength = jArr.length(); // for (int l = 0; l < jsonArrLength; l++){ // pathList.add(jArr.getString(l)); // } // break; // } // } // //Log.d("out-->", pathList.toString()); // return pathList; // } // // public static String loadJSONFromAssets(String file, Context cntx) { // String json = null; // try { // InputStream is = cntx.getAssets().open(file); // int size = is.available(); // byte[] buffer = new byte[size]; // is.read(buffer); // is.close(); // json = new String(buffer, "UTF-8"); // } catch (IOException ex) { // ex.printStackTrace(); // return null; // } // return json; // } // // public static String existPath(ArrayList<String> paths){ // int pathsSize = paths.size(); // for(int i = 0; i < pathsSize; i++){ // File file = new File(paths.get(i)); // if (file.exists()){ // return paths.get(i); // } // } // return null; // } // // public static String findFilePath(String file, Context cntx){ // String path = null; // try { // path = existPath(getListOfFile("data/paths.json", "path", file, cntx)); // } catch (JSONException e) { // e.printStackTrace(); // } // return path; // } // } // Path: src/com/elefher/customclasses/CpuGovernors.java import java.io.DataOutputStream; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import android.content.Context; import android.util.Log; import com.elefher.utils.CpuUtils; import com.elefher.utils.ReadFile; package com.elefher.customclasses; public class CpuGovernors { public CpuGovernors() { } public static String[] getAvailableGovernors(Context cntx) { String[] governors = CpuUtils.readStringArray(findFilePath("scaling_available_governors", cntx)); // In case does not exist governors return null if (governors == null) { return null; } return governors; } public static String getCurrentGovernor(Context cntx){ String currentGov = ""; try {
currentGov = ReadFile.getStringOfFile(findFilePath("scaling_governor", cntx));
elefher/CpuHandler
src/com/elefher/customclasses/Gpu.java
// Path: src/com/elefher/abstractclasses/Sysfs.java // public abstract class Sysfs { // // public static String[] getAvailableFreequencies(Context cntx, String findPath) { // String[] frequencies = CpuUtils.readStringArray(findFilePath(findPath, cntx)); // // // In case does not exist frequencies return null // if (frequencies == null) { // return null; // } // // // Convert String array to int array in order to sort it // int[] minAvToInt = ArrayUtils.stringToIntArray(frequencies); // // Sort the array as ascending // Arrays.sort(minAvToInt); // // Convert int array to string sorted // frequencies = ArrayUtils.intToStringArray(minAvToInt); // // return frequencies; // } // // public static String getCurrentFrequency(Context cntx, String searchFile) { // return ReadFile.getStringOfFile(findFilePath(searchFile, cntx)); // } // // public static String findFilePath(String file, Context cntx){ // try { // String path = ReadFile.existPath(ReadFile.getListOfFile("data/paths.json", "path", file, cntx)); // return path; // } catch (JSONException e) { // e.printStackTrace(); // } // return null; // } // // public abstract boolean setFrequency(String freq); // public abstract boolean set(String Val, String To); // public abstract boolean setFrequencies(String minFreq, String maxFreq); // public abstract String[] getCurrent(String searchFile); // public abstract String returnTo(String val); // } // // Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // }
import java.io.DataOutputStream; import java.util.ArrayList; import java.util.List; import com.elefher.abstractclasses.Sysfs; import com.elefher.utils.CpuUtils; import android.content.Context; import android.util.Log; import android.widget.Toast;
package com.elefher.customclasses; public class Gpu extends Sysfs { Context context; public Gpu(Context cntx) { context = cntx; } @Override public boolean setFrequency(String freq) { if (freq.isEmpty() || freq == null) return false; String gpu_file = findFilePath("max_gpuclk", context); try { List<String> commands = new ArrayList<String>(); /* * Prepare permissions so that we can write */ commands.add("chmod 0664 " + gpu_file + "\n"); commands.add("echo " + freq + " > " + gpu_file + "\n"); /* * Set permissions in initial state */ commands.add("chmod 0444 " + gpu_file + "\n"); commands.add("exit\n");
// Path: src/com/elefher/abstractclasses/Sysfs.java // public abstract class Sysfs { // // public static String[] getAvailableFreequencies(Context cntx, String findPath) { // String[] frequencies = CpuUtils.readStringArray(findFilePath(findPath, cntx)); // // // In case does not exist frequencies return null // if (frequencies == null) { // return null; // } // // // Convert String array to int array in order to sort it // int[] minAvToInt = ArrayUtils.stringToIntArray(frequencies); // // Sort the array as ascending // Arrays.sort(minAvToInt); // // Convert int array to string sorted // frequencies = ArrayUtils.intToStringArray(minAvToInt); // // return frequencies; // } // // public static String getCurrentFrequency(Context cntx, String searchFile) { // return ReadFile.getStringOfFile(findFilePath(searchFile, cntx)); // } // // public static String findFilePath(String file, Context cntx){ // try { // String path = ReadFile.existPath(ReadFile.getListOfFile("data/paths.json", "path", file, cntx)); // return path; // } catch (JSONException e) { // e.printStackTrace(); // } // return null; // } // // public abstract boolean setFrequency(String freq); // public abstract boolean set(String Val, String To); // public abstract boolean setFrequencies(String minFreq, String maxFreq); // public abstract String[] getCurrent(String searchFile); // public abstract String returnTo(String val); // } // // Path: src/com/elefher/utils/CpuUtils.java // public class CpuUtils { // public CpuUtils() { // // } // // public static String getSUbinaryPath() { // String s = "/system/bin/su"; // File f = new File(s); // if (f.exists()) { // return s; // } // s = "/system/xbin/su"; // f = new File(s); // if (f.exists()) { // return s; // } // return null; // } // // public static String[] readStringArray(String filename) { // String line = ReadFile.getStringOfFile(filename); // if (line != null) { // return line.split(" "); // } // return null; // } // // public static ArrayList<String> readStringArray2Cells(String filename) { // BufferedReader buffered_reader = null; // ArrayList<String> strLines = new ArrayList<String>(); // try { // buffered_reader = new BufferedReader(new FileReader(filename)); // String line; // // while ((line = buffered_reader.readLine()) != null) { // strLines.add(line); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (buffered_reader != null){ // buffered_reader.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // // return strLines; // } // } // Path: src/com/elefher/customclasses/Gpu.java import java.io.DataOutputStream; import java.util.ArrayList; import java.util.List; import com.elefher.abstractclasses.Sysfs; import com.elefher.utils.CpuUtils; import android.content.Context; import android.util.Log; import android.widget.Toast; package com.elefher.customclasses; public class Gpu extends Sysfs { Context context; public Gpu(Context cntx) { context = cntx; } @Override public boolean setFrequency(String freq) { if (freq.isEmpty() || freq == null) return false; String gpu_file = findFilePath("max_gpuclk", context); try { List<String> commands = new ArrayList<String>(); /* * Prepare permissions so that we can write */ commands.add("chmod 0664 " + gpu_file + "\n"); commands.add("echo " + freq + " > " + gpu_file + "\n"); /* * Set permissions in initial state */ commands.add("chmod 0444 " + gpu_file + "\n"); commands.add("exit\n");
Process p = Runtime.getRuntime().exec(CpuUtils.getSUbinaryPath());
peterarsentev/code_quality_principles
src/main/java/ru/job4j/principle_002/MultiIf.java
// Path: src/main/java/ru/job4j/principle_002/Message.java // enum Type { // /** // * Email. // */ // EMAIL, // /** // * Jabber. // */ // JABBER, // /** // * Twitter. // */ // TWITTER, // /** // * Etc. // */ // ETC, // /** // * Unknown. // */ // UNKNOWN // }
import ru.job4j.principle_002.Message.Type;
package ru.job4j.principle_002; /** * Anti-pattern - multi if statements. * * @author Petr Arsentev (parsentev@yandex.ru) * @version $Id$ * @since 0.1 */ public class MultiIf { /** * Sent message to type. * @param msg message * @return true if it finds a type. */ public boolean sent(final Message msg) { boolean rsl = false;
// Path: src/main/java/ru/job4j/principle_002/Message.java // enum Type { // /** // * Email. // */ // EMAIL, // /** // * Jabber. // */ // JABBER, // /** // * Twitter. // */ // TWITTER, // /** // * Etc. // */ // ETC, // /** // * Unknown. // */ // UNKNOWN // } // Path: src/main/java/ru/job4j/principle_002/MultiIf.java import ru.job4j.principle_002.Message.Type; package ru.job4j.principle_002; /** * Anti-pattern - multi if statements. * * @author Petr Arsentev (parsentev@yandex.ru) * @version $Id$ * @since 0.1 */ public class MultiIf { /** * Sent message to type. * @param msg message * @return true if it finds a type. */ public boolean sent(final Message msg) { boolean rsl = false;
if (msg.type() == Type.EMAIL) {
peterarsentev/code_quality_principles
src/test/java/ru/job4j/principle_004/HibernateStoreTest.java
// Path: src/test/java/ru/job4j/principle_004/ConnectionRollback.java // public static Connection create(Connection connection) throws SQLException { // connection.setAutoCommit(false); // return (Connection) Proxy.newProxyInstance( // ConnectionRollback.class.getClassLoader(), // new Class[] { // Connection.class // }, // (proxy, method, args) -> { // Object rsl = null; // if ("close".equals(method.getName())) { // connection.rollback(); // connection.close(); // } else { // rsl = method.invoke(connection, args); // } // return rsl; // } // ); // }
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.junit.AfterClass; import org.junit.Ignore; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; import static ru.job4j.principle_004.ConnectionRollback.create;
package ru.job4j.principle_004; /** * Tests for hibernate. */ @Ignore public class HibernateStoreTest { /** * Create a new user and check id. */ @Test public void whenCreateUser() {
// Path: src/test/java/ru/job4j/principle_004/ConnectionRollback.java // public static Connection create(Connection connection) throws SQLException { // connection.setAutoCommit(false); // return (Connection) Proxy.newProxyInstance( // ConnectionRollback.class.getClassLoader(), // new Class[] { // Connection.class // }, // (proxy, method, args) -> { // Object rsl = null; // if ("close".equals(method.getName())) { // connection.rollback(); // connection.close(); // } else { // rsl = method.invoke(connection, args); // } // return rsl; // } // ); // } // Path: src/test/java/ru/job4j/principle_004/HibernateStoreTest.java import org.hibernate.Session; import org.hibernate.SessionFactory; import org.junit.AfterClass; import org.junit.Ignore; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; import static ru.job4j.principle_004.ConnectionRollback.create; package ru.job4j.principle_004; /** * Tests for hibernate. */ @Ignore public class HibernateStoreTest { /** * Create a new user and check id. */ @Test public void whenCreateUser() {
SessionFactory factory = create(HibernateFactory.FACTORY);
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongUtils.java
// Path: cango-common/src/main/java/com/bella/cango/enums/DbType.java // public enum DbType { // MYSQL(1, "com.mysql.jdbc.Driver"), // ORACLE(2, "oracle.jdbc.driver.OracleDriver"), // DRDS(3, "com.mysql.jdbc.Driver"); // // private Integer code; // private String driver; // // DbType(Integer type, String driver) { // this.code = type; // } // // public Integer getCode() { // return code; // } // // public String getDriver() { // return driver; // } // // public boolean isOracle() { // return this.equals(ORACLE); // } // // // public boolean isMysql() { // return this.equals(MYSQL); // } // // public boolean isDRDS() { // return this.equals(DRDS); // } // // public DbType parse(Integer code) { // switch (code) { // case 1: // return MYSQL; // case 2: // return ORACLE; // case 3: // return DRDS; // default: // return null; // } // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnMeta.java // public class ColumnMeta { // // private String name; // private int type; // // public ColumnMeta(String columnName, int columnType) { // this.name = StringUtils.upperCase(columnName);// 统一为大写 // this.type = columnType; // } // // public String getName() { // return name; // } // // public int getType() { // return type; // } // // public void setName(String name) { // this.name = StringUtils.upperCase(name); // } // // public void setType(int type) { // this.type = type; // } // // public ColumnMeta clone() { // return new ColumnMeta(this.name, this.type); // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, YuGongToStringStyle.DEFAULT_STYLE); // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // result = prime * result + type; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnMeta other = (ColumnMeta) obj; // if (name == null) { // if (other.name != null) return false; // } else if (!name.equals(other.name)) return false; // if (type != other.type) return false; // return true; // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // }
import com.bella.cango.enums.DbType; import com.bella.cango.instance.oracle.common.db.meta.ColumnMeta; import com.bella.cango.instance.oracle.exception.YuGongException; import org.apache.commons.lang.StringUtils; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.sql.Types; import java.util.Collection; import java.util.List;
package com.bella.cango.instance.oracle.common.utils; public class YuGongUtils { public static boolean isEmpty(Collection collection) { return collection == null || collection.size() == 0; } public static boolean isNotEmpty(Collection collection) { return collection != null && collection.size() != 0; } /** * 返回字段名字的数组 * * @param columns * @return */
// Path: cango-common/src/main/java/com/bella/cango/enums/DbType.java // public enum DbType { // MYSQL(1, "com.mysql.jdbc.Driver"), // ORACLE(2, "oracle.jdbc.driver.OracleDriver"), // DRDS(3, "com.mysql.jdbc.Driver"); // // private Integer code; // private String driver; // // DbType(Integer type, String driver) { // this.code = type; // } // // public Integer getCode() { // return code; // } // // public String getDriver() { // return driver; // } // // public boolean isOracle() { // return this.equals(ORACLE); // } // // // public boolean isMysql() { // return this.equals(MYSQL); // } // // public boolean isDRDS() { // return this.equals(DRDS); // } // // public DbType parse(Integer code) { // switch (code) { // case 1: // return MYSQL; // case 2: // return ORACLE; // case 3: // return DRDS; // default: // return null; // } // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnMeta.java // public class ColumnMeta { // // private String name; // private int type; // // public ColumnMeta(String columnName, int columnType) { // this.name = StringUtils.upperCase(columnName);// 统一为大写 // this.type = columnType; // } // // public String getName() { // return name; // } // // public int getType() { // return type; // } // // public void setName(String name) { // this.name = StringUtils.upperCase(name); // } // // public void setType(int type) { // this.type = type; // } // // public ColumnMeta clone() { // return new ColumnMeta(this.name, this.type); // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, YuGongToStringStyle.DEFAULT_STYLE); // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // result = prime * result + type; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnMeta other = (ColumnMeta) obj; // if (name == null) { // if (other.name != null) return false; // } else if (!name.equals(other.name)) return false; // if (type != other.type) return false; // return true; // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongUtils.java import com.bella.cango.enums.DbType; import com.bella.cango.instance.oracle.common.db.meta.ColumnMeta; import com.bella.cango.instance.oracle.exception.YuGongException; import org.apache.commons.lang.StringUtils; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.sql.Types; import java.util.Collection; import java.util.List; package com.bella.cango.instance.oracle.common.utils; public class YuGongUtils { public static boolean isEmpty(Collection collection) { return collection == null || collection.size() == 0; } public static boolean isNotEmpty(Collection collection) { return collection != null && collection.size() != 0; } /** * 返回字段名字的数组 * * @param columns * @return */
public static String[] getColumnNameArray(List<ColumnMeta> columns) {
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongUtils.java
// Path: cango-common/src/main/java/com/bella/cango/enums/DbType.java // public enum DbType { // MYSQL(1, "com.mysql.jdbc.Driver"), // ORACLE(2, "oracle.jdbc.driver.OracleDriver"), // DRDS(3, "com.mysql.jdbc.Driver"); // // private Integer code; // private String driver; // // DbType(Integer type, String driver) { // this.code = type; // } // // public Integer getCode() { // return code; // } // // public String getDriver() { // return driver; // } // // public boolean isOracle() { // return this.equals(ORACLE); // } // // // public boolean isMysql() { // return this.equals(MYSQL); // } // // public boolean isDRDS() { // return this.equals(DRDS); // } // // public DbType parse(Integer code) { // switch (code) { // case 1: // return MYSQL; // case 2: // return ORACLE; // case 3: // return DRDS; // default: // return null; // } // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnMeta.java // public class ColumnMeta { // // private String name; // private int type; // // public ColumnMeta(String columnName, int columnType) { // this.name = StringUtils.upperCase(columnName);// 统一为大写 // this.type = columnType; // } // // public String getName() { // return name; // } // // public int getType() { // return type; // } // // public void setName(String name) { // this.name = StringUtils.upperCase(name); // } // // public void setType(int type) { // this.type = type; // } // // public ColumnMeta clone() { // return new ColumnMeta(this.name, this.type); // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, YuGongToStringStyle.DEFAULT_STYLE); // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // result = prime * result + type; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnMeta other = (ColumnMeta) obj; // if (name == null) { // if (other.name != null) return false; // } else if (!name.equals(other.name)) return false; // if (type != other.type) return false; // return true; // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // }
import com.bella.cango.enums.DbType; import com.bella.cango.instance.oracle.common.db.meta.ColumnMeta; import com.bella.cango.instance.oracle.exception.YuGongException; import org.apache.commons.lang.StringUtils; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.sql.Types; import java.util.Collection; import java.util.List;
package com.bella.cango.instance.oracle.common.utils; public class YuGongUtils { public static boolean isEmpty(Collection collection) { return collection == null || collection.size() == 0; } public static boolean isNotEmpty(Collection collection) { return collection != null && collection.size() != 0; } /** * 返回字段名字的数组 * * @param columns * @return */ public static String[] getColumnNameArray(List<ColumnMeta> columns) { if (columns == null || columns.size() == 0) { return new String[]{}; } String[] result = new String[columns.size()]; int i = 0; for (ColumnMeta column : columns) { result[i++] = column.getName(); } return result; } /** * 根据DataSource判断一下数据库类型 * * @param dataSource * @return */
// Path: cango-common/src/main/java/com/bella/cango/enums/DbType.java // public enum DbType { // MYSQL(1, "com.mysql.jdbc.Driver"), // ORACLE(2, "oracle.jdbc.driver.OracleDriver"), // DRDS(3, "com.mysql.jdbc.Driver"); // // private Integer code; // private String driver; // // DbType(Integer type, String driver) { // this.code = type; // } // // public Integer getCode() { // return code; // } // // public String getDriver() { // return driver; // } // // public boolean isOracle() { // return this.equals(ORACLE); // } // // // public boolean isMysql() { // return this.equals(MYSQL); // } // // public boolean isDRDS() { // return this.equals(DRDS); // } // // public DbType parse(Integer code) { // switch (code) { // case 1: // return MYSQL; // case 2: // return ORACLE; // case 3: // return DRDS; // default: // return null; // } // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnMeta.java // public class ColumnMeta { // // private String name; // private int type; // // public ColumnMeta(String columnName, int columnType) { // this.name = StringUtils.upperCase(columnName);// 统一为大写 // this.type = columnType; // } // // public String getName() { // return name; // } // // public int getType() { // return type; // } // // public void setName(String name) { // this.name = StringUtils.upperCase(name); // } // // public void setType(int type) { // this.type = type; // } // // public ColumnMeta clone() { // return new ColumnMeta(this.name, this.type); // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, YuGongToStringStyle.DEFAULT_STYLE); // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // result = prime * result + type; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnMeta other = (ColumnMeta) obj; // if (name == null) { // if (other.name != null) return false; // } else if (!name.equals(other.name)) return false; // if (type != other.type) return false; // return true; // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongUtils.java import com.bella.cango.enums.DbType; import com.bella.cango.instance.oracle.common.db.meta.ColumnMeta; import com.bella.cango.instance.oracle.exception.YuGongException; import org.apache.commons.lang.StringUtils; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.sql.Types; import java.util.Collection; import java.util.List; package com.bella.cango.instance.oracle.common.utils; public class YuGongUtils { public static boolean isEmpty(Collection collection) { return collection == null || collection.size() == 0; } public static boolean isNotEmpty(Collection collection) { return collection != null && collection.size() != 0; } /** * 返回字段名字的数组 * * @param columns * @return */ public static String[] getColumnNameArray(List<ColumnMeta> columns) { if (columns == null || columns.size() == 0) { return new String[]{}; } String[] result = new String[columns.size()]; int i = 0; for (ColumnMeta column : columns) { result[i++] = column.getName(); } return result; } /** * 根据DataSource判断一下数据库类型 * * @param dataSource * @return */
public static DbType judgeDbType(DataSource dataSource) {
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongUtils.java
// Path: cango-common/src/main/java/com/bella/cango/enums/DbType.java // public enum DbType { // MYSQL(1, "com.mysql.jdbc.Driver"), // ORACLE(2, "oracle.jdbc.driver.OracleDriver"), // DRDS(3, "com.mysql.jdbc.Driver"); // // private Integer code; // private String driver; // // DbType(Integer type, String driver) { // this.code = type; // } // // public Integer getCode() { // return code; // } // // public String getDriver() { // return driver; // } // // public boolean isOracle() { // return this.equals(ORACLE); // } // // // public boolean isMysql() { // return this.equals(MYSQL); // } // // public boolean isDRDS() { // return this.equals(DRDS); // } // // public DbType parse(Integer code) { // switch (code) { // case 1: // return MYSQL; // case 2: // return ORACLE; // case 3: // return DRDS; // default: // return null; // } // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnMeta.java // public class ColumnMeta { // // private String name; // private int type; // // public ColumnMeta(String columnName, int columnType) { // this.name = StringUtils.upperCase(columnName);// 统一为大写 // this.type = columnType; // } // // public String getName() { // return name; // } // // public int getType() { // return type; // } // // public void setName(String name) { // this.name = StringUtils.upperCase(name); // } // // public void setType(int type) { // this.type = type; // } // // public ColumnMeta clone() { // return new ColumnMeta(this.name, this.type); // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, YuGongToStringStyle.DEFAULT_STYLE); // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // result = prime * result + type; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnMeta other = (ColumnMeta) obj; // if (name == null) { // if (other.name != null) return false; // } else if (!name.equals(other.name)) return false; // if (type != other.type) return false; // return true; // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // }
import com.bella.cango.enums.DbType; import com.bella.cango.instance.oracle.common.db.meta.ColumnMeta; import com.bella.cango.instance.oracle.exception.YuGongException; import org.apache.commons.lang.StringUtils; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.sql.Types; import java.util.Collection; import java.util.List;
result[i++] = column.getName(); } return result; } /** * 根据DataSource判断一下数据库类型 * * @param dataSource * @return */ public static DbType judgeDbType(DataSource dataSource) { final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return (DbType) jdbcTemplate.execute(new ConnectionCallback() { public Object doInConnection(Connection c) throws SQLException, DataAccessException { DatabaseMetaData meta = c.getMetaData(); String databaseName = meta.getDatabaseProductName(); String version = meta.getDatabaseProductVersion(); if (StringUtils.startsWithIgnoreCase(databaseName, "oracle")) { return DbType.ORACLE; } else if (StringUtils.startsWithIgnoreCase(databaseName, "mysql")) { if (StringUtils.contains(version, "-TDDL-")) { return DbType.DRDS; } else { return DbType.MYSQL; } } else {
// Path: cango-common/src/main/java/com/bella/cango/enums/DbType.java // public enum DbType { // MYSQL(1, "com.mysql.jdbc.Driver"), // ORACLE(2, "oracle.jdbc.driver.OracleDriver"), // DRDS(3, "com.mysql.jdbc.Driver"); // // private Integer code; // private String driver; // // DbType(Integer type, String driver) { // this.code = type; // } // // public Integer getCode() { // return code; // } // // public String getDriver() { // return driver; // } // // public boolean isOracle() { // return this.equals(ORACLE); // } // // // public boolean isMysql() { // return this.equals(MYSQL); // } // // public boolean isDRDS() { // return this.equals(DRDS); // } // // public DbType parse(Integer code) { // switch (code) { // case 1: // return MYSQL; // case 2: // return ORACLE; // case 3: // return DRDS; // default: // return null; // } // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnMeta.java // public class ColumnMeta { // // private String name; // private int type; // // public ColumnMeta(String columnName, int columnType) { // this.name = StringUtils.upperCase(columnName);// 统一为大写 // this.type = columnType; // } // // public String getName() { // return name; // } // // public int getType() { // return type; // } // // public void setName(String name) { // this.name = StringUtils.upperCase(name); // } // // public void setType(int type) { // this.type = type; // } // // public ColumnMeta clone() { // return new ColumnMeta(this.name, this.type); // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, YuGongToStringStyle.DEFAULT_STYLE); // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // result = prime * result + type; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnMeta other = (ColumnMeta) obj; // if (name == null) { // if (other.name != null) return false; // } else if (!name.equals(other.name)) return false; // if (type != other.type) return false; // return true; // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongUtils.java import com.bella.cango.enums.DbType; import com.bella.cango.instance.oracle.common.db.meta.ColumnMeta; import com.bella.cango.instance.oracle.exception.YuGongException; import org.apache.commons.lang.StringUtils; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.sql.Types; import java.util.Collection; import java.util.List; result[i++] = column.getName(); } return result; } /** * 根据DataSource判断一下数据库类型 * * @param dataSource * @return */ public static DbType judgeDbType(DataSource dataSource) { final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return (DbType) jdbcTemplate.execute(new ConnectionCallback() { public Object doInConnection(Connection c) throws SQLException, DataAccessException { DatabaseMetaData meta = c.getMetaData(); String databaseName = meta.getDatabaseProductName(); String version = meta.getDatabaseProductVersion(); if (StringUtils.startsWithIgnoreCase(databaseName, "oracle")) { return DbType.ORACLE; } else if (StringUtils.startsWithIgnoreCase(databaseName, "mysql")) { if (StringUtils.contains(version, "-TDDL-")) { return DbType.DRDS; } else { return DbType.MYSQL; } } else {
throw new YuGongException("unknow database type " + databaseName);
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnMeta.java
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // }
import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder;
package com.bella.cango.instance.oracle.common.db.meta; /** * 代表一个字段的信息 * * @author agapple 2013-9-3 下午2:46:32 * @since 3.0.0 */ public class ColumnMeta { private String name; private int type; public ColumnMeta(String columnName, int columnType) { this.name = StringUtils.upperCase(columnName);// 统一为大写 this.type = columnType; } public String getName() { return name; } public int getType() { return type; } public void setName(String name) { this.name = StringUtils.upperCase(name); } public void setType(int type) { this.type = type; } public ColumnMeta clone() { return new ColumnMeta(this.name, this.type); } public String toString() {
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnMeta.java import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; package com.bella.cango.instance.oracle.common.db.meta; /** * 代表一个字段的信息 * * @author agapple 2013-9-3 下午2:46:32 * @since 3.0.0 */ public class ColumnMeta { private String name; private int type; public ColumnMeta(String columnName, int columnType) { this.name = StringUtils.upperCase(columnName);// 统一为大写 this.type = columnType; } public String getName() { return name; } public int getType() { return type; } public void setName(String name) { this.name = StringUtils.upperCase(name); } public void setType(int type) { this.type = type; } public ColumnMeta clone() { return new ColumnMeta(this.name, this.type); } public String toString() {
return ToStringBuilder.reflectionToString(this, YuGongToStringStyle.DEFAULT_STYLE);
kevinKaiF/cango
cango-service/src/main/java/com/bella/cango/service/impl/CangoTableServiceImpl.java
// Path: cango-model/src/main/java/com/bella/cango/entity/CangoTable.java // public class CangoTable { // // private Long id; // // private String instancesName; // // private String tableName; // // private Date createTime; // // private Date updateTime; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getInstancesName() { // return instancesName; // } // // public CangoTable setInstancesName(String instancesName) { // this.instancesName = instancesName; // return this; // } // // public String getTableName() { // return tableName; // } // // public CangoTable setTableName(String tableName) { // this.tableName = tableName; // return this; // } // // public Date getCreateTime() { // return createTime; // } // // public CangoTable setCreateTime(Date createTime) { // this.createTime = createTime; // return this; // } // // public Date getUpdateTime() { // return updateTime; // } // // public CangoTable setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // return this; // } // } // // Path: cango-service/src/main/java/com/bella/cango/service/CangoTableService.java // public interface CangoTableService { // void save(CangoTable cangoTable); // // CangoTable query(CangoTable cangoTable); // // void deleteByInstancesName(CangoTable cangoTable); // // List<CangoTable> findByInstancesName(CangoTable cangoTable); // // void deleteAll(); // // void batchSave(List<CangoTable> cangoTables); // } // // Path: cango-common/src/main/java/com/bella/cango/utils/ValidateUtil.java // public class ValidateUtil { // private static Validator validator; // static { // final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); // validator = validatorFactory.getValidator(); // } // public static <T> void validate(T t) { // final Set<ConstraintViolation<T>> constraintViolations = validator.validate(t); // if (constraintViolations != null && constraintViolations.size() > 0) { // StringBuilder stringBuilder = new StringBuilder(); // for (ConstraintViolation<T> constraintViolation : constraintViolations) { // stringBuilder.append(constraintViolation.getPropertyPath()) // .append(" : ") // .append(constraintViolation.getMessage()) // .append(", "); // } // String constraintMessage = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString(); // throw new CangoException(constraintMessage); // } // } // }
import com.bella.cango.entity.CangoTable; import com.bella.cango.service.CangoTableService; import com.bella.cango.utils.ValidateUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.stereotype.Service; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List;
package com.bella.cango.service.impl; /** * TODO * * @author kevin * @date 2016/8/30 */ @Service("cangoTableService") public class CangoTableServiceImpl implements CangoTableService { @Autowired private JdbcTemplate jdbcTemplate; private Date getCurrentTime() { return new Date(System.currentTimeMillis()); } @Override
// Path: cango-model/src/main/java/com/bella/cango/entity/CangoTable.java // public class CangoTable { // // private Long id; // // private String instancesName; // // private String tableName; // // private Date createTime; // // private Date updateTime; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getInstancesName() { // return instancesName; // } // // public CangoTable setInstancesName(String instancesName) { // this.instancesName = instancesName; // return this; // } // // public String getTableName() { // return tableName; // } // // public CangoTable setTableName(String tableName) { // this.tableName = tableName; // return this; // } // // public Date getCreateTime() { // return createTime; // } // // public CangoTable setCreateTime(Date createTime) { // this.createTime = createTime; // return this; // } // // public Date getUpdateTime() { // return updateTime; // } // // public CangoTable setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // return this; // } // } // // Path: cango-service/src/main/java/com/bella/cango/service/CangoTableService.java // public interface CangoTableService { // void save(CangoTable cangoTable); // // CangoTable query(CangoTable cangoTable); // // void deleteByInstancesName(CangoTable cangoTable); // // List<CangoTable> findByInstancesName(CangoTable cangoTable); // // void deleteAll(); // // void batchSave(List<CangoTable> cangoTables); // } // // Path: cango-common/src/main/java/com/bella/cango/utils/ValidateUtil.java // public class ValidateUtil { // private static Validator validator; // static { // final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); // validator = validatorFactory.getValidator(); // } // public static <T> void validate(T t) { // final Set<ConstraintViolation<T>> constraintViolations = validator.validate(t); // if (constraintViolations != null && constraintViolations.size() > 0) { // StringBuilder stringBuilder = new StringBuilder(); // for (ConstraintViolation<T> constraintViolation : constraintViolations) { // stringBuilder.append(constraintViolation.getPropertyPath()) // .append(" : ") // .append(constraintViolation.getMessage()) // .append(", "); // } // String constraintMessage = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString(); // throw new CangoException(constraintMessage); // } // } // } // Path: cango-service/src/main/java/com/bella/cango/service/impl/CangoTableServiceImpl.java import com.bella.cango.entity.CangoTable; import com.bella.cango.service.CangoTableService; import com.bella.cango.utils.ValidateUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.stereotype.Service; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; package com.bella.cango.service.impl; /** * TODO * * @author kevin * @date 2016/8/30 */ @Service("cangoTableService") public class CangoTableServiceImpl implements CangoTableService { @Autowired private JdbcTemplate jdbcTemplate; private Date getCurrentTime() { return new Date(System.currentTimeMillis()); } @Override
public CangoTable query(CangoTable cangoTable) {
kevinKaiF/cango
cango-service/src/main/java/com/bella/cango/service/impl/CangoTableServiceImpl.java
// Path: cango-model/src/main/java/com/bella/cango/entity/CangoTable.java // public class CangoTable { // // private Long id; // // private String instancesName; // // private String tableName; // // private Date createTime; // // private Date updateTime; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getInstancesName() { // return instancesName; // } // // public CangoTable setInstancesName(String instancesName) { // this.instancesName = instancesName; // return this; // } // // public String getTableName() { // return tableName; // } // // public CangoTable setTableName(String tableName) { // this.tableName = tableName; // return this; // } // // public Date getCreateTime() { // return createTime; // } // // public CangoTable setCreateTime(Date createTime) { // this.createTime = createTime; // return this; // } // // public Date getUpdateTime() { // return updateTime; // } // // public CangoTable setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // return this; // } // } // // Path: cango-service/src/main/java/com/bella/cango/service/CangoTableService.java // public interface CangoTableService { // void save(CangoTable cangoTable); // // CangoTable query(CangoTable cangoTable); // // void deleteByInstancesName(CangoTable cangoTable); // // List<CangoTable> findByInstancesName(CangoTable cangoTable); // // void deleteAll(); // // void batchSave(List<CangoTable> cangoTables); // } // // Path: cango-common/src/main/java/com/bella/cango/utils/ValidateUtil.java // public class ValidateUtil { // private static Validator validator; // static { // final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); // validator = validatorFactory.getValidator(); // } // public static <T> void validate(T t) { // final Set<ConstraintViolation<T>> constraintViolations = validator.validate(t); // if (constraintViolations != null && constraintViolations.size() > 0) { // StringBuilder stringBuilder = new StringBuilder(); // for (ConstraintViolation<T> constraintViolation : constraintViolations) { // stringBuilder.append(constraintViolation.getPropertyPath()) // .append(" : ") // .append(constraintViolation.getMessage()) // .append(", "); // } // String constraintMessage = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString(); // throw new CangoException(constraintMessage); // } // } // }
import com.bella.cango.entity.CangoTable; import com.bella.cango.service.CangoTableService; import com.bella.cango.utils.ValidateUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.stereotype.Service; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List;
package com.bella.cango.service.impl; /** * TODO * * @author kevin * @date 2016/8/30 */ @Service("cangoTableService") public class CangoTableServiceImpl implements CangoTableService { @Autowired private JdbcTemplate jdbcTemplate; private Date getCurrentTime() { return new Date(System.currentTimeMillis()); } @Override public CangoTable query(CangoTable cangoTable) {
// Path: cango-model/src/main/java/com/bella/cango/entity/CangoTable.java // public class CangoTable { // // private Long id; // // private String instancesName; // // private String tableName; // // private Date createTime; // // private Date updateTime; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getInstancesName() { // return instancesName; // } // // public CangoTable setInstancesName(String instancesName) { // this.instancesName = instancesName; // return this; // } // // public String getTableName() { // return tableName; // } // // public CangoTable setTableName(String tableName) { // this.tableName = tableName; // return this; // } // // public Date getCreateTime() { // return createTime; // } // // public CangoTable setCreateTime(Date createTime) { // this.createTime = createTime; // return this; // } // // public Date getUpdateTime() { // return updateTime; // } // // public CangoTable setUpdateTime(Date updateTime) { // this.updateTime = updateTime; // return this; // } // } // // Path: cango-service/src/main/java/com/bella/cango/service/CangoTableService.java // public interface CangoTableService { // void save(CangoTable cangoTable); // // CangoTable query(CangoTable cangoTable); // // void deleteByInstancesName(CangoTable cangoTable); // // List<CangoTable> findByInstancesName(CangoTable cangoTable); // // void deleteAll(); // // void batchSave(List<CangoTable> cangoTables); // } // // Path: cango-common/src/main/java/com/bella/cango/utils/ValidateUtil.java // public class ValidateUtil { // private static Validator validator; // static { // final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); // validator = validatorFactory.getValidator(); // } // public static <T> void validate(T t) { // final Set<ConstraintViolation<T>> constraintViolations = validator.validate(t); // if (constraintViolations != null && constraintViolations.size() > 0) { // StringBuilder stringBuilder = new StringBuilder(); // for (ConstraintViolation<T> constraintViolation : constraintViolations) { // stringBuilder.append(constraintViolation.getPropertyPath()) // .append(" : ") // .append(constraintViolation.getMessage()) // .append(", "); // } // String constraintMessage = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString(); // throw new CangoException(constraintMessage); // } // } // } // Path: cango-service/src/main/java/com/bella/cango/service/impl/CangoTableServiceImpl.java import com.bella.cango.entity.CangoTable; import com.bella.cango.service.CangoTableService; import com.bella.cango.utils.ValidateUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.stereotype.Service; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; package com.bella.cango.service.impl; /** * TODO * * @author kevin * @date 2016/8/30 */ @Service("cangoTableService") public class CangoTableServiceImpl implements CangoTableService { @Autowired private JdbcTemplate jdbcTemplate; private Date getCurrentTime() { return new Date(System.currentTimeMillis()); } @Override public CangoTable query(CangoTable cangoTable) {
ValidateUtil.validate(cangoTable);
kevinKaiF/cango
cango-common/src/main/java/com/bella/cango/utils/ValidateUtil.java
// Path: cango-common/src/main/java/com/bella/cango/exception/CangoException.java // public class CangoException extends RuntimeException { // public CangoException() { // super(); // } // // public CangoException(String message) { // super(message); // } // // public CangoException(String message, Throwable cause) { // super(message, cause); // } // // public CangoException(Throwable cause) { // super(cause); // } // // protected CangoException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // }
import com.bella.cango.exception.CangoException; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import java.util.Set;
package com.bella.cango.utils; /** * TODO * * @author kevin * @date 2016/9/24 */ public class ValidateUtil { private static Validator validator; static { final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); validator = validatorFactory.getValidator(); } public static <T> void validate(T t) { final Set<ConstraintViolation<T>> constraintViolations = validator.validate(t); if (constraintViolations != null && constraintViolations.size() > 0) { StringBuilder stringBuilder = new StringBuilder(); for (ConstraintViolation<T> constraintViolation : constraintViolations) { stringBuilder.append(constraintViolation.getPropertyPath()) .append(" : ") .append(constraintViolation.getMessage()) .append(", "); } String constraintMessage = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
// Path: cango-common/src/main/java/com/bella/cango/exception/CangoException.java // public class CangoException extends RuntimeException { // public CangoException() { // super(); // } // // public CangoException(String message) { // super(message); // } // // public CangoException(String message, Throwable cause) { // super(message, cause); // } // // public CangoException(Throwable cause) { // super(cause); // } // // protected CangoException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: cango-common/src/main/java/com/bella/cango/utils/ValidateUtil.java import com.bella.cango.exception.CangoException; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import java.util.Set; package com.bella.cango.utils; /** * TODO * * @author kevin * @date 2016/9/24 */ public class ValidateUtil { private static Validator validator; static { final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); validator = validatorFactory.getValidator(); } public static <T> void validate(T t) { final Set<ConstraintViolation<T>> constraintViolations = validator.validate(t); if (constraintViolations != null && constraintViolations.size() > 0) { StringBuilder stringBuilder = new StringBuilder(); for (ConstraintViolation<T> constraintViolation : constraintViolations) { stringBuilder.append(constraintViolation.getPropertyPath()) .append(" : ") .append(constraintViolation.getMessage()) .append(", "); } String constraintMessage = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
throw new CangoException(constraintMessage);
kevinKaiF/cango
cango-dto/src/main/java/com/bella/cango/dto/CangoRequestDto.java
// Path: cango-common/src/main/java/com/bella/cango/enums/DbType.java // public enum DbType { // MYSQL(1, "com.mysql.jdbc.Driver"), // ORACLE(2, "oracle.jdbc.driver.OracleDriver"), // DRDS(3, "com.mysql.jdbc.Driver"); // // private Integer code; // private String driver; // // DbType(Integer type, String driver) { // this.code = type; // } // // public Integer getCode() { // return code; // } // // public String getDriver() { // return driver; // } // // public boolean isOracle() { // return this.equals(ORACLE); // } // // // public boolean isMysql() { // return this.equals(MYSQL); // } // // public boolean isDRDS() { // return this.equals(DRDS); // } // // public DbType parse(Integer code) { // switch (code) { // case 1: // return MYSQL; // case 2: // return ORACLE; // case 3: // return DRDS; // default: // return null; // } // } // }
import com.bella.cango.enums.DbType; import com.bella.cango.validate.SlaveId; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.util.Set;
package com.bella.cango.dto; /** * TODO * * @author kevin * @date 2016/8/7 */ @SlaveId public class CangoRequestDto { /** * The constant serialVersionUID. */ private static final long serialVersionUID = -3153523853123787010L; /** * The Name. * * @描述:canal实例名称 * @字段:name VARCHAR(50) */ @NotEmpty private String name; /** * The Host. * * @描述:源库主机地址 * @字段:host VARCHAR(50) */ @NotEmpty private String host; /** * The Port. * * @描述:源库主机端口 * @字段:port INT(10) */ @NotNull private Integer port; /** * The User name. * * @描述:源库用户名 * @字段:user_name VARCHAR(100) */ @NotEmpty private String userName; /** * The Password. * * @描述:源库密码 * @字段:password VARCHAR(32) */ @NotEmpty private String password; /** * @描述:源库名称 * @字段:db_name VARCHAR(50) */ @NotEmpty private String dbName; /** * 该Canal实例上所有感兴趣的表. */ private Set<String> tableNames; /** * The Db type. * */ @NotNull
// Path: cango-common/src/main/java/com/bella/cango/enums/DbType.java // public enum DbType { // MYSQL(1, "com.mysql.jdbc.Driver"), // ORACLE(2, "oracle.jdbc.driver.OracleDriver"), // DRDS(3, "com.mysql.jdbc.Driver"); // // private Integer code; // private String driver; // // DbType(Integer type, String driver) { // this.code = type; // } // // public Integer getCode() { // return code; // } // // public String getDriver() { // return driver; // } // // public boolean isOracle() { // return this.equals(ORACLE); // } // // // public boolean isMysql() { // return this.equals(MYSQL); // } // // public boolean isDRDS() { // return this.equals(DRDS); // } // // public DbType parse(Integer code) { // switch (code) { // case 1: // return MYSQL; // case 2: // return ORACLE; // case 3: // return DRDS; // default: // return null; // } // } // } // Path: cango-dto/src/main/java/com/bella/cango/dto/CangoRequestDto.java import com.bella.cango.enums.DbType; import com.bella.cango.validate.SlaveId; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.util.Set; package com.bella.cango.dto; /** * TODO * * @author kevin * @date 2016/8/7 */ @SlaveId public class CangoRequestDto { /** * The constant serialVersionUID. */ private static final long serialVersionUID = -3153523853123787010L; /** * The Name. * * @描述:canal实例名称 * @字段:name VARCHAR(50) */ @NotEmpty private String name; /** * The Host. * * @描述:源库主机地址 * @字段:host VARCHAR(50) */ @NotEmpty private String host; /** * The Port. * * @描述:源库主机端口 * @字段:port INT(10) */ @NotNull private Integer port; /** * The User name. * * @描述:源库用户名 * @字段:user_name VARCHAR(100) */ @NotEmpty private String userName; /** * The Password. * * @描述:源库密码 * @字段:password VARCHAR(32) */ @NotEmpty private String password; /** * @描述:源库名称 * @字段:db_name VARCHAR(50) */ @NotEmpty private String dbName; /** * 该Canal实例上所有感兴趣的表. */ private Set<String> tableNames; /** * The Db type. * */ @NotNull
private DbType dbType;
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/sql/SqlTemplate.java
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnMeta.java // public class ColumnMeta { // // private String name; // private int type; // // public ColumnMeta(String columnName, int columnType) { // this.name = StringUtils.upperCase(columnName);// 统一为大写 // this.type = columnType; // } // // public String getName() { // return name; // } // // public int getType() { // return type; // } // // public void setName(String name) { // this.name = StringUtils.upperCase(name); // } // // public void setType(int type) { // this.type = type; // } // // public ColumnMeta clone() { // return new ColumnMeta(this.name, this.type); // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, YuGongToStringStyle.DEFAULT_STYLE); // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // result = prime * result + type; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnMeta other = (ColumnMeta) obj; // if (name == null) { // if (other.name != null) return false; // } else if (!name.equals(other.name)) return false; // if (type != other.type) return false; // return true; // } // // }
import com.bella.cango.instance.oracle.common.db.meta.ColumnMeta; import java.sql.Types; import java.util.List;
package com.bella.cango.instance.oracle.common.db.sql; /** * sql构造 * * @author agapple 2013-9-10 下午6:10:10 * @since 1.0.0 */ public class SqlTemplate { private static final String DOT = "."; /** * 根据字段的列表顺序,拼写以 col1,col2,col3,.... */
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnMeta.java // public class ColumnMeta { // // private String name; // private int type; // // public ColumnMeta(String columnName, int columnType) { // this.name = StringUtils.upperCase(columnName);// 统一为大写 // this.type = columnType; // } // // public String getName() { // return name; // } // // public int getType() { // return type; // } // // public void setName(String name) { // this.name = StringUtils.upperCase(name); // } // // public void setType(int type) { // this.type = type; // } // // public ColumnMeta clone() { // return new ColumnMeta(this.name, this.type); // } // // public String toString() { // return ToStringBuilder.reflectionToString(this, YuGongToStringStyle.DEFAULT_STYLE); // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // result = prime * result + type; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnMeta other = (ColumnMeta) obj; // if (name == null) { // if (other.name != null) return false; // } else if (!name.equals(other.name)) return false; // if (type != other.type) return false; // return true; // } // // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/sql/SqlTemplate.java import com.bella.cango.instance.oracle.common.db.meta.ColumnMeta; import java.sql.Types; import java.util.List; package com.bella.cango.instance.oracle.common.db.sql; /** * sql构造 * * @author agapple 2013-9-10 下午6:10:10 * @since 1.0.0 */ public class SqlTemplate { private static final String DOT = "."; /** * 根据字段的列表顺序,拼写以 col1,col2,col3,.... */
public String makeColumn(List<ColumnMeta> columns) {
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/Table.java
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // }
import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import com.google.common.collect.Lists; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import java.util.List;
result.addAll(columns); return result; } public boolean isPrimaryKey(String columnName) { for (ColumnMeta col : primaryKeys) { if (StringUtils.equalsIgnoreCase(col.getName(), columnName)) { return true; } } return false; } /** * 返回schema.name */ public String getFullName() { return schema + "." + name; } public String getExtKey() { return extKey; } public void setExtKey(String extKey) { this.extKey = extKey; } public String toString() {
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/Table.java import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import com.google.common.collect.Lists; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import java.util.List; result.addAll(columns); return result; } public boolean isPrimaryKey(String columnName) { for (ColumnMeta col : primaryKeys) { if (StringUtils.equalsIgnoreCase(col.getName(), columnName)) { return true; } } return false; } /** * 返回schema.name */ public String getFullName() { return schema + "." + name; } public String getExtKey() { return extKey; } public void setExtKey(String extKey) { this.extKey = extKey; } public String toString() {
return ToStringBuilder.reflectionToString(this, YuGongToStringStyle.DEFAULT_STYLE);
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/record/Record.java
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnValue.java // public class ColumnValue { // // private ColumnMeta column; // private Object value; // private boolean check = true; // 是否需要做数据对比 // // public ColumnValue() { // } // // public ColumnValue(ColumnMeta column, Object value) { // this(column, value, true); // } // // public ColumnValue(ColumnMeta column, Object value, boolean check) { // this.value = value; // this.column = column; // this.check = check; // } // // public ColumnMeta getColumn() { // return column; // } // // public void setColumn(ColumnMeta column) { // this.column = column; // } // // public Object getValue() { // return value; // } // // public void setValue(Object value) { // this.value = value; // } // // public boolean isCheck() { // return check; // } // // public void setCheck(boolean check) { // this.check = check; // } // // public ColumnValue clone() { // ColumnValue column = new ColumnValue(); // column.setValue(this.value); // column.setColumn(this.column.clone()); // return column; // } // // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((column == null) ? 0 : column.hashCode()); // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnValue other = (ColumnValue) obj; // if (column == null) { // if (other.column != null) return false; // } else if (!column.equals(other.column)) return false; // if (value == null) { // if (other.value != null) return false; // } else if (!value.equals(other.value)) return false; // return true; // } // // @Override // public String toString() { // return "ColumnValue [column=" + column + ", value=" + value + "]"; // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // }
import com.bella.cango.instance.oracle.common.db.meta.ColumnValue; import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import com.bella.cango.instance.oracle.exception.YuGongException; import com.google.common.collect.Lists; import org.apache.commons.lang.builder.ToStringBuilder; import java.util.List;
package com.bella.cango.instance.oracle.common.model.record; /** * 代表一条记录 * * @author agapple 2013-9-3 下午2:50:21 * @since 3.0.0 */ public class Record { private String schemaName; private String tableName;
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnValue.java // public class ColumnValue { // // private ColumnMeta column; // private Object value; // private boolean check = true; // 是否需要做数据对比 // // public ColumnValue() { // } // // public ColumnValue(ColumnMeta column, Object value) { // this(column, value, true); // } // // public ColumnValue(ColumnMeta column, Object value, boolean check) { // this.value = value; // this.column = column; // this.check = check; // } // // public ColumnMeta getColumn() { // return column; // } // // public void setColumn(ColumnMeta column) { // this.column = column; // } // // public Object getValue() { // return value; // } // // public void setValue(Object value) { // this.value = value; // } // // public boolean isCheck() { // return check; // } // // public void setCheck(boolean check) { // this.check = check; // } // // public ColumnValue clone() { // ColumnValue column = new ColumnValue(); // column.setValue(this.value); // column.setColumn(this.column.clone()); // return column; // } // // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((column == null) ? 0 : column.hashCode()); // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnValue other = (ColumnValue) obj; // if (column == null) { // if (other.column != null) return false; // } else if (!column.equals(other.column)) return false; // if (value == null) { // if (other.value != null) return false; // } else if (!value.equals(other.value)) return false; // return true; // } // // @Override // public String toString() { // return "ColumnValue [column=" + column + ", value=" + value + "]"; // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/record/Record.java import com.bella.cango.instance.oracle.common.db.meta.ColumnValue; import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import com.bella.cango.instance.oracle.exception.YuGongException; import com.google.common.collect.Lists; import org.apache.commons.lang.builder.ToStringBuilder; import java.util.List; package com.bella.cango.instance.oracle.common.model.record; /** * 代表一条记录 * * @author agapple 2013-9-3 下午2:50:21 * @since 3.0.0 */ public class Record { private String schemaName; private String tableName;
private List<ColumnValue> primaryKeys = Lists.newArrayList();
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/record/Record.java
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnValue.java // public class ColumnValue { // // private ColumnMeta column; // private Object value; // private boolean check = true; // 是否需要做数据对比 // // public ColumnValue() { // } // // public ColumnValue(ColumnMeta column, Object value) { // this(column, value, true); // } // // public ColumnValue(ColumnMeta column, Object value, boolean check) { // this.value = value; // this.column = column; // this.check = check; // } // // public ColumnMeta getColumn() { // return column; // } // // public void setColumn(ColumnMeta column) { // this.column = column; // } // // public Object getValue() { // return value; // } // // public void setValue(Object value) { // this.value = value; // } // // public boolean isCheck() { // return check; // } // // public void setCheck(boolean check) { // this.check = check; // } // // public ColumnValue clone() { // ColumnValue column = new ColumnValue(); // column.setValue(this.value); // column.setColumn(this.column.clone()); // return column; // } // // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((column == null) ? 0 : column.hashCode()); // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnValue other = (ColumnValue) obj; // if (column == null) { // if (other.column != null) return false; // } else if (!column.equals(other.column)) return false; // if (value == null) { // if (other.value != null) return false; // } else if (!value.equals(other.value)) return false; // return true; // } // // @Override // public String toString() { // return "ColumnValue [column=" + column + ", value=" + value + "]"; // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // }
import com.bella.cango.instance.oracle.common.db.meta.ColumnValue; import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import com.bella.cango.instance.oracle.exception.YuGongException; import com.google.common.collect.Lists; import org.apache.commons.lang.builder.ToStringBuilder; import java.util.List;
package com.bella.cango.instance.oracle.common.model.record; /** * 代表一条记录 * * @author agapple 2013-9-3 下午2:50:21 * @since 3.0.0 */ public class Record { private String schemaName; private String tableName; private List<ColumnValue> primaryKeys = Lists.newArrayList(); private List<ColumnValue> columns = Lists.newArrayList(); public Record() { } public Record(String schemaName, String tableName, List<ColumnValue> primaryKeys, List<ColumnValue> columns) { this.schemaName = schemaName; this.tableName = tableName; this.primaryKeys = primaryKeys; this.columns = columns; } public List<ColumnValue> getPrimaryKeys() { return primaryKeys; } public void setPrimaryKeys(List<ColumnValue> primaryKeys) { this.primaryKeys = primaryKeys; } public void addPrimaryKey(ColumnValue primaryKey) { if (getColumnByName(primaryKey.getColumn().getName(), true) != null) {
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnValue.java // public class ColumnValue { // // private ColumnMeta column; // private Object value; // private boolean check = true; // 是否需要做数据对比 // // public ColumnValue() { // } // // public ColumnValue(ColumnMeta column, Object value) { // this(column, value, true); // } // // public ColumnValue(ColumnMeta column, Object value, boolean check) { // this.value = value; // this.column = column; // this.check = check; // } // // public ColumnMeta getColumn() { // return column; // } // // public void setColumn(ColumnMeta column) { // this.column = column; // } // // public Object getValue() { // return value; // } // // public void setValue(Object value) { // this.value = value; // } // // public boolean isCheck() { // return check; // } // // public void setCheck(boolean check) { // this.check = check; // } // // public ColumnValue clone() { // ColumnValue column = new ColumnValue(); // column.setValue(this.value); // column.setColumn(this.column.clone()); // return column; // } // // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((column == null) ? 0 : column.hashCode()); // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnValue other = (ColumnValue) obj; // if (column == null) { // if (other.column != null) return false; // } else if (!column.equals(other.column)) return false; // if (value == null) { // if (other.value != null) return false; // } else if (!value.equals(other.value)) return false; // return true; // } // // @Override // public String toString() { // return "ColumnValue [column=" + column + ", value=" + value + "]"; // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/record/Record.java import com.bella.cango.instance.oracle.common.db.meta.ColumnValue; import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import com.bella.cango.instance.oracle.exception.YuGongException; import com.google.common.collect.Lists; import org.apache.commons.lang.builder.ToStringBuilder; import java.util.List; package com.bella.cango.instance.oracle.common.model.record; /** * 代表一条记录 * * @author agapple 2013-9-3 下午2:50:21 * @since 3.0.0 */ public class Record { private String schemaName; private String tableName; private List<ColumnValue> primaryKeys = Lists.newArrayList(); private List<ColumnValue> columns = Lists.newArrayList(); public Record() { } public Record(String schemaName, String tableName, List<ColumnValue> primaryKeys, List<ColumnValue> columns) { this.schemaName = schemaName; this.tableName = tableName; this.primaryKeys = primaryKeys; this.columns = columns; } public List<ColumnValue> getPrimaryKeys() { return primaryKeys; } public void setPrimaryKeys(List<ColumnValue> primaryKeys) { this.primaryKeys = primaryKeys; } public void addPrimaryKey(ColumnValue primaryKey) { if (getColumnByName(primaryKey.getColumn().getName(), true) != null) {
throw new YuGongException("dup column[" + primaryKey.getColumn().getName() + "]");
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/record/Record.java
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnValue.java // public class ColumnValue { // // private ColumnMeta column; // private Object value; // private boolean check = true; // 是否需要做数据对比 // // public ColumnValue() { // } // // public ColumnValue(ColumnMeta column, Object value) { // this(column, value, true); // } // // public ColumnValue(ColumnMeta column, Object value, boolean check) { // this.value = value; // this.column = column; // this.check = check; // } // // public ColumnMeta getColumn() { // return column; // } // // public void setColumn(ColumnMeta column) { // this.column = column; // } // // public Object getValue() { // return value; // } // // public void setValue(Object value) { // this.value = value; // } // // public boolean isCheck() { // return check; // } // // public void setCheck(boolean check) { // this.check = check; // } // // public ColumnValue clone() { // ColumnValue column = new ColumnValue(); // column.setValue(this.value); // column.setColumn(this.column.clone()); // return column; // } // // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((column == null) ? 0 : column.hashCode()); // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnValue other = (ColumnValue) obj; // if (column == null) { // if (other.column != null) return false; // } else if (!column.equals(other.column)) return false; // if (value == null) { // if (other.value != null) return false; // } else if (!value.equals(other.value)) return false; // return true; // } // // @Override // public String toString() { // return "ColumnValue [column=" + column + ", value=" + value + "]"; // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // }
import com.bella.cango.instance.oracle.common.db.meta.ColumnValue; import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import com.bella.cango.instance.oracle.exception.YuGongException; import com.google.common.collect.Lists; import org.apache.commons.lang.builder.ToStringBuilder; import java.util.List;
final int prime = 31; int result = 1; result = prime * result + ((columns == null) ? 0 : columns.hashCode()); result = prime * result + ((primaryKeys == null) ? 0 : primaryKeys.hashCode()); result = prime * result + ((schemaName == null) ? 0 : schemaName.hashCode()); result = prime * result + ((tableName == null) ? 0 : tableName.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Record other = (Record) obj; if (columns == null) { if (other.columns != null) return false; } else if (!columns.equals(other.columns)) return false; if (primaryKeys == null) { if (other.primaryKeys != null) return false; } else if (!primaryKeys.equals(other.primaryKeys)) return false; if (schemaName == null) { if (other.schemaName != null) return false; } else if (!schemaName.equals(other.schemaName)) return false; if (tableName == null) { if (other.tableName != null) return false; } else if (!tableName.equals(other.tableName)) return false; return true; } public String toString() {
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnValue.java // public class ColumnValue { // // private ColumnMeta column; // private Object value; // private boolean check = true; // 是否需要做数据对比 // // public ColumnValue() { // } // // public ColumnValue(ColumnMeta column, Object value) { // this(column, value, true); // } // // public ColumnValue(ColumnMeta column, Object value, boolean check) { // this.value = value; // this.column = column; // this.check = check; // } // // public ColumnMeta getColumn() { // return column; // } // // public void setColumn(ColumnMeta column) { // this.column = column; // } // // public Object getValue() { // return value; // } // // public void setValue(Object value) { // this.value = value; // } // // public boolean isCheck() { // return check; // } // // public void setCheck(boolean check) { // this.check = check; // } // // public ColumnValue clone() { // ColumnValue column = new ColumnValue(); // column.setValue(this.value); // column.setColumn(this.column.clone()); // return column; // } // // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((column == null) ? 0 : column.hashCode()); // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnValue other = (ColumnValue) obj; // if (column == null) { // if (other.column != null) return false; // } else if (!column.equals(other.column)) return false; // if (value == null) { // if (other.value != null) return false; // } else if (!value.equals(other.value)) return false; // return true; // } // // @Override // public String toString() { // return "ColumnValue [column=" + column + ", value=" + value + "]"; // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/record/Record.java import com.bella.cango.instance.oracle.common.db.meta.ColumnValue; import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import com.bella.cango.instance.oracle.exception.YuGongException; import com.google.common.collect.Lists; import org.apache.commons.lang.builder.ToStringBuilder; import java.util.List; final int prime = 31; int result = 1; result = prime * result + ((columns == null) ? 0 : columns.hashCode()); result = prime * result + ((primaryKeys == null) ? 0 : primaryKeys.hashCode()); result = prime * result + ((schemaName == null) ? 0 : schemaName.hashCode()); result = prime * result + ((tableName == null) ? 0 : tableName.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Record other = (Record) obj; if (columns == null) { if (other.columns != null) return false; } else if (!columns.equals(other.columns)) return false; if (primaryKeys == null) { if (other.primaryKeys != null) return false; } else if (!primaryKeys.equals(other.primaryKeys)) return false; if (schemaName == null) { if (other.schemaName != null) return false; } else if (!schemaName.equals(other.schemaName)) return false; if (tableName == null) { if (other.tableName != null) return false; } else if (!tableName.equals(other.tableName)) return false; return true; } public String toString() {
return ToStringBuilder.reflectionToString(this, YuGongToStringStyle.DEFAULT_STYLE);
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/extractor/AbstractRecordExtractor.java
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/lifecycle/AbstractYuGongLifeCycle.java // public abstract class AbstractYuGongLifeCycle implements YuGongLifeCycle { // // protected final Logger logger = LoggerFactory.getLogger(this.getClass()); // protected volatile boolean running = false; // 是否处于运行中 // // public boolean isStart() { // return running; // } // // public void start() { // if (running) { // return; // } // // running = true; // } // // public void stop() { // if (!running) { // return; // } // // running = false; // } // // public void abort(String why, Throwable e) { // logger.error("abort caused by " + why, e); // stop(); // } // // public boolean isStop() { // return !isStart(); // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/ExtractStatus.java // public enum ExtractStatus { // /** // * 正常提取 // */ // NORMAL, // /** // * 追上 // */ // CATCH_UP, // /** // * 无变更 // */ // NO_UPDATE, // /** // * 处理结束 // */ // TABLE_END; // }
import com.bella.cango.instance.oracle.common.lifecycle.AbstractYuGongLifeCycle; import com.bella.cango.instance.oracle.common.model.ExtractStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.bella.cango.instance.oracle.extractor; /** * @author agapple 2014年2月25日 下午11:38:06 * @since 1.0.0 */ public abstract class AbstractRecordExtractor extends AbstractYuGongLifeCycle implements RecordExtractor { protected final Logger logger = LoggerFactory.getLogger(this.getClass());
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/lifecycle/AbstractYuGongLifeCycle.java // public abstract class AbstractYuGongLifeCycle implements YuGongLifeCycle { // // protected final Logger logger = LoggerFactory.getLogger(this.getClass()); // protected volatile boolean running = false; // 是否处于运行中 // // public boolean isStart() { // return running; // } // // public void start() { // if (running) { // return; // } // // running = true; // } // // public void stop() { // if (!running) { // return; // } // // running = false; // } // // public void abort(String why, Throwable e) { // logger.error("abort caused by " + why, e); // stop(); // } // // public boolean isStop() { // return !isStart(); // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/ExtractStatus.java // public enum ExtractStatus { // /** // * 正常提取 // */ // NORMAL, // /** // * 追上 // */ // CATCH_UP, // /** // * 无变更 // */ // NO_UPDATE, // /** // * 处理结束 // */ // TABLE_END; // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/extractor/AbstractRecordExtractor.java import com.bella.cango.instance.oracle.common.lifecycle.AbstractYuGongLifeCycle; import com.bella.cango.instance.oracle.common.model.ExtractStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.bella.cango.instance.oracle.extractor; /** * @author agapple 2014年2月25日 下午11:38:06 * @since 1.0.0 */ public abstract class AbstractRecordExtractor extends AbstractYuGongLifeCycle implements RecordExtractor { protected final Logger logger = LoggerFactory.getLogger(this.getClass());
protected volatile ExtractStatus status = ExtractStatus.NORMAL;
kevinKaiF/cango
cango-message/src/main/java/com/bella/cango/message/producer/KafkaProducer.java
// Path: cango-common/src/main/java/com/bella/cango/exception/CangoException.java // public class CangoException extends RuntimeException { // public CangoException() { // super(); // } // // public CangoException(String message) { // super(message); // } // // public CangoException(String message, Throwable cause) { // super(message, cause); // } // // public CangoException(Throwable cause) { // super(cause); // } // // protected CangoException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: cango-common/src/main/java/com/bella/cango/utils/PropertiesFileLoader.java // public class PropertiesFileLoader { // public static final String PROJECT_DIR; // // public static final String CLASSPATH_DIR; // // public static final String DEFAULT_CONF_DIR; // // public static final String DEFAULT_KAFKA_PATH; // // public static final String DEFAULT_LOG_HOME; // // static { // File classFile = new File(Thread.currentThread().getContextClassLoader().getResource(".").getFile()); // CLASSPATH_DIR = classFile.getAbsolutePath(); // PROJECT_DIR = classFile.getParentFile().getParentFile().getAbsolutePath(); // File confFile = new File(PROJECT_DIR, "src/conf"); // DEFAULT_CONF_DIR = confFile.getAbsolutePath(); // DEFAULT_KAFKA_PATH = DEFAULT_CONF_DIR + File.separator + "kafkaProduce.properties"; // DEFAULT_LOG_HOME = DEFAULT_CONF_DIR + File.separator + "log"; // } // // public static Properties loadKafkaProperties() throws IOException { // String kafkaPath = System.getProperty("kafkaProduce"); // if (StringUtils.isEmpty(kafkaPath)) { // kafkaPath = DEFAULT_KAFKA_PATH; // } // // return PropertiesLoaderUtils.loadProperties(new FileSystemResource(kafkaPath)); // } // // public static Properties load(String path) throws IOException { // if (StringUtils.isEmpty(path)) { // return new Properties(); // } // // return PropertiesLoaderUtils.loadProperties(new FileSystemResource(path)); // } // }
import com.alibaba.fastjson.JSON; import com.bella.cango.exception.CangoException; import com.bella.cango.utils.PropertiesFileLoader; import kafka.javaapi.producer.Producer; import kafka.producer.KeyedMessage; import kafka.producer.ProducerConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
public void run() { while (true) { try { String message = messageQueue.poll(); producer.send(new KeyedMessage<String, String>(topic, message)); Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } } }); } public void send(String message) { messageQueue.offer(message); } public void send(Object object) { messageQueue.offer(JSON.toJSONString(object)); } public void start() { if (!start) { worker.start(); } } private void init() { try {
// Path: cango-common/src/main/java/com/bella/cango/exception/CangoException.java // public class CangoException extends RuntimeException { // public CangoException() { // super(); // } // // public CangoException(String message) { // super(message); // } // // public CangoException(String message, Throwable cause) { // super(message, cause); // } // // public CangoException(Throwable cause) { // super(cause); // } // // protected CangoException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: cango-common/src/main/java/com/bella/cango/utils/PropertiesFileLoader.java // public class PropertiesFileLoader { // public static final String PROJECT_DIR; // // public static final String CLASSPATH_DIR; // // public static final String DEFAULT_CONF_DIR; // // public static final String DEFAULT_KAFKA_PATH; // // public static final String DEFAULT_LOG_HOME; // // static { // File classFile = new File(Thread.currentThread().getContextClassLoader().getResource(".").getFile()); // CLASSPATH_DIR = classFile.getAbsolutePath(); // PROJECT_DIR = classFile.getParentFile().getParentFile().getAbsolutePath(); // File confFile = new File(PROJECT_DIR, "src/conf"); // DEFAULT_CONF_DIR = confFile.getAbsolutePath(); // DEFAULT_KAFKA_PATH = DEFAULT_CONF_DIR + File.separator + "kafkaProduce.properties"; // DEFAULT_LOG_HOME = DEFAULT_CONF_DIR + File.separator + "log"; // } // // public static Properties loadKafkaProperties() throws IOException { // String kafkaPath = System.getProperty("kafkaProduce"); // if (StringUtils.isEmpty(kafkaPath)) { // kafkaPath = DEFAULT_KAFKA_PATH; // } // // return PropertiesLoaderUtils.loadProperties(new FileSystemResource(kafkaPath)); // } // // public static Properties load(String path) throws IOException { // if (StringUtils.isEmpty(path)) { // return new Properties(); // } // // return PropertiesLoaderUtils.loadProperties(new FileSystemResource(path)); // } // } // Path: cango-message/src/main/java/com/bella/cango/message/producer/KafkaProducer.java import com.alibaba.fastjson.JSON; import com.bella.cango.exception.CangoException; import com.bella.cango.utils.PropertiesFileLoader; import kafka.javaapi.producer.Producer; import kafka.producer.KeyedMessage; import kafka.producer.ProducerConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public void run() { while (true) { try { String message = messageQueue.poll(); producer.send(new KeyedMessage<String, String>(topic, message)); Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } } }); } public void send(String message) { messageQueue.offer(message); } public void send(Object object) { messageQueue.offer(JSON.toJSONString(object)); } public void start() { if (!start) { worker.start(); } } private void init() { try {
Properties props = PropertiesFileLoader.loadKafkaProperties();
kevinKaiF/cango
cango-message/src/main/java/com/bella/cango/message/producer/KafkaProducer.java
// Path: cango-common/src/main/java/com/bella/cango/exception/CangoException.java // public class CangoException extends RuntimeException { // public CangoException() { // super(); // } // // public CangoException(String message) { // super(message); // } // // public CangoException(String message, Throwable cause) { // super(message, cause); // } // // public CangoException(Throwable cause) { // super(cause); // } // // protected CangoException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: cango-common/src/main/java/com/bella/cango/utils/PropertiesFileLoader.java // public class PropertiesFileLoader { // public static final String PROJECT_DIR; // // public static final String CLASSPATH_DIR; // // public static final String DEFAULT_CONF_DIR; // // public static final String DEFAULT_KAFKA_PATH; // // public static final String DEFAULT_LOG_HOME; // // static { // File classFile = new File(Thread.currentThread().getContextClassLoader().getResource(".").getFile()); // CLASSPATH_DIR = classFile.getAbsolutePath(); // PROJECT_DIR = classFile.getParentFile().getParentFile().getAbsolutePath(); // File confFile = new File(PROJECT_DIR, "src/conf"); // DEFAULT_CONF_DIR = confFile.getAbsolutePath(); // DEFAULT_KAFKA_PATH = DEFAULT_CONF_DIR + File.separator + "kafkaProduce.properties"; // DEFAULT_LOG_HOME = DEFAULT_CONF_DIR + File.separator + "log"; // } // // public static Properties loadKafkaProperties() throws IOException { // String kafkaPath = System.getProperty("kafkaProduce"); // if (StringUtils.isEmpty(kafkaPath)) { // kafkaPath = DEFAULT_KAFKA_PATH; // } // // return PropertiesLoaderUtils.loadProperties(new FileSystemResource(kafkaPath)); // } // // public static Properties load(String path) throws IOException { // if (StringUtils.isEmpty(path)) { // return new Properties(); // } // // return PropertiesLoaderUtils.loadProperties(new FileSystemResource(path)); // } // }
import com.alibaba.fastjson.JSON; import com.bella.cango.exception.CangoException; import com.bella.cango.utils.PropertiesFileLoader; import kafka.javaapi.producer.Producer; import kafka.producer.KeyedMessage; import kafka.producer.ProducerConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
} }); } public void send(String message) { messageQueue.offer(message); } public void send(Object object) { messageQueue.offer(JSON.toJSONString(object)); } public void start() { if (!start) { worker.start(); } } private void init() { try { Properties props = PropertiesFileLoader.loadKafkaProperties(); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("serializer.class", "kafka.serializer.StringEncoder"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("request.required.acks", "0"); producer = new Producer<>(new ProducerConfig(props)); topic = props.getProperty("topic", "cango"); } catch (FileNotFoundException e) { e.printStackTrace(); LOGGER.error("not found kafkaProduce.properties, please check it");
// Path: cango-common/src/main/java/com/bella/cango/exception/CangoException.java // public class CangoException extends RuntimeException { // public CangoException() { // super(); // } // // public CangoException(String message) { // super(message); // } // // public CangoException(String message, Throwable cause) { // super(message, cause); // } // // public CangoException(Throwable cause) { // super(cause); // } // // protected CangoException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: cango-common/src/main/java/com/bella/cango/utils/PropertiesFileLoader.java // public class PropertiesFileLoader { // public static final String PROJECT_DIR; // // public static final String CLASSPATH_DIR; // // public static final String DEFAULT_CONF_DIR; // // public static final String DEFAULT_KAFKA_PATH; // // public static final String DEFAULT_LOG_HOME; // // static { // File classFile = new File(Thread.currentThread().getContextClassLoader().getResource(".").getFile()); // CLASSPATH_DIR = classFile.getAbsolutePath(); // PROJECT_DIR = classFile.getParentFile().getParentFile().getAbsolutePath(); // File confFile = new File(PROJECT_DIR, "src/conf"); // DEFAULT_CONF_DIR = confFile.getAbsolutePath(); // DEFAULT_KAFKA_PATH = DEFAULT_CONF_DIR + File.separator + "kafkaProduce.properties"; // DEFAULT_LOG_HOME = DEFAULT_CONF_DIR + File.separator + "log"; // } // // public static Properties loadKafkaProperties() throws IOException { // String kafkaPath = System.getProperty("kafkaProduce"); // if (StringUtils.isEmpty(kafkaPath)) { // kafkaPath = DEFAULT_KAFKA_PATH; // } // // return PropertiesLoaderUtils.loadProperties(new FileSystemResource(kafkaPath)); // } // // public static Properties load(String path) throws IOException { // if (StringUtils.isEmpty(path)) { // return new Properties(); // } // // return PropertiesLoaderUtils.loadProperties(new FileSystemResource(path)); // } // } // Path: cango-message/src/main/java/com/bella/cango/message/producer/KafkaProducer.java import com.alibaba.fastjson.JSON; import com.bella.cango.exception.CangoException; import com.bella.cango.utils.PropertiesFileLoader; import kafka.javaapi.producer.Producer; import kafka.producer.KeyedMessage; import kafka.producer.ProducerConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; } }); } public void send(String message) { messageQueue.offer(message); } public void send(Object object) { messageQueue.offer(JSON.toJSONString(object)); } public void start() { if (!start) { worker.start(); } } private void init() { try { Properties props = PropertiesFileLoader.loadKafkaProperties(); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("serializer.class", "kafka.serializer.StringEncoder"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("request.required.acks", "0"); producer = new Producer<>(new ProducerConfig(props)); topic = props.getProperty("topic", "cango"); } catch (FileNotFoundException e) { e.printStackTrace(); LOGGER.error("not found kafkaProduce.properties, please check it");
throw new CangoException(e);
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/DataSourceConfig.java
// Path: cango-common/src/main/java/com/bella/cango/enums/DbType.java // public enum DbType { // MYSQL(1, "com.mysql.jdbc.Driver"), // ORACLE(2, "oracle.jdbc.driver.OracleDriver"), // DRDS(3, "com.mysql.jdbc.Driver"); // // private Integer code; // private String driver; // // DbType(Integer type, String driver) { // this.code = type; // } // // public Integer getCode() { // return code; // } // // public String getDriver() { // return driver; // } // // public boolean isOracle() { // return this.equals(ORACLE); // } // // // public boolean isMysql() { // return this.equals(MYSQL); // } // // public boolean isDRDS() { // return this.equals(DRDS); // } // // public DbType parse(Integer code) { // switch (code) { // case 1: // return MYSQL; // case 2: // return ORACLE; // case 3: // return DRDS; // default: // return null; // } // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // }
import com.bella.cango.enums.DbType; import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import org.apache.commons.lang.builder.ToStringBuilder; import java.io.Serializable; import java.util.Properties;
package com.bella.cango.instance.oracle.common.model; /** * 数据介质源信息描述 * * @author agapple 2011-9-2 上午11:28:21 */ public class DataSourceConfig implements Serializable { private static final long serialVersionUID = -7653632703273608373L; private String username; private String password; private String url;
// Path: cango-common/src/main/java/com/bella/cango/enums/DbType.java // public enum DbType { // MYSQL(1, "com.mysql.jdbc.Driver"), // ORACLE(2, "oracle.jdbc.driver.OracleDriver"), // DRDS(3, "com.mysql.jdbc.Driver"); // // private Integer code; // private String driver; // // DbType(Integer type, String driver) { // this.code = type; // } // // public Integer getCode() { // return code; // } // // public String getDriver() { // return driver; // } // // public boolean isOracle() { // return this.equals(ORACLE); // } // // // public boolean isMysql() { // return this.equals(MYSQL); // } // // public boolean isDRDS() { // return this.equals(DRDS); // } // // public DbType parse(Integer code) { // switch (code) { // case 1: // return MYSQL; // case 2: // return ORACLE; // case 3: // return DRDS; // default: // return null; // } // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/DataSourceConfig.java import com.bella.cango.enums.DbType; import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import org.apache.commons.lang.builder.ToStringBuilder; import java.io.Serializable; import java.util.Properties; package com.bella.cango.instance.oracle.common.model; /** * 数据介质源信息描述 * * @author agapple 2011-9-2 上午11:28:21 */ public class DataSourceConfig implements Serializable { private static final long serialVersionUID = -7653632703273608373L; private String username; private String password; private String url;
private DbType type;
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/DataSourceConfig.java
// Path: cango-common/src/main/java/com/bella/cango/enums/DbType.java // public enum DbType { // MYSQL(1, "com.mysql.jdbc.Driver"), // ORACLE(2, "oracle.jdbc.driver.OracleDriver"), // DRDS(3, "com.mysql.jdbc.Driver"); // // private Integer code; // private String driver; // // DbType(Integer type, String driver) { // this.code = type; // } // // public Integer getCode() { // return code; // } // // public String getDriver() { // return driver; // } // // public boolean isOracle() { // return this.equals(ORACLE); // } // // // public boolean isMysql() { // return this.equals(MYSQL); // } // // public boolean isDRDS() { // return this.equals(DRDS); // } // // public DbType parse(Integer code) { // switch (code) { // case 1: // return MYSQL; // case 2: // return ORACLE; // case 3: // return DRDS; // default: // return null; // } // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // }
import com.bella.cango.enums.DbType; import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import org.apache.commons.lang.builder.ToStringBuilder; import java.io.Serializable; import java.util.Properties;
result = prime * result + ((username == null) ? 0 : username.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DataSourceConfig other = (DataSourceConfig) obj; if (encode == null) { if (other.encode != null) return false; } else if (!encode.equals(other.encode)) return false; if (password == null) { if (other.password != null) return false; } else if (!password.equals(other.password)) return false; if (properties == null) { if (other.properties != null) return false; } else if (!properties.equals(other.properties)) return false; if (type != other.type) return false; if (url == null) { if (other.url != null) return false; } else if (!url.equals(other.url)) return false; if (username == null) { if (other.username != null) return false; } else if (!username.equals(other.username)) return false; return true; } public String toString() {
// Path: cango-common/src/main/java/com/bella/cango/enums/DbType.java // public enum DbType { // MYSQL(1, "com.mysql.jdbc.Driver"), // ORACLE(2, "oracle.jdbc.driver.OracleDriver"), // DRDS(3, "com.mysql.jdbc.Driver"); // // private Integer code; // private String driver; // // DbType(Integer type, String driver) { // this.code = type; // } // // public Integer getCode() { // return code; // } // // public String getDriver() { // return driver; // } // // public boolean isOracle() { // return this.equals(ORACLE); // } // // // public boolean isMysql() { // return this.equals(MYSQL); // } // // public boolean isDRDS() { // return this.equals(DRDS); // } // // public DbType parse(Integer code) { // switch (code) { // case 1: // return MYSQL; // case 2: // return ORACLE; // case 3: // return DRDS; // default: // return null; // } // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/DataSourceConfig.java import com.bella.cango.enums.DbType; import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import org.apache.commons.lang.builder.ToStringBuilder; import java.io.Serializable; import java.util.Properties; result = prime * result + ((username == null) ? 0 : username.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DataSourceConfig other = (DataSourceConfig) obj; if (encode == null) { if (other.encode != null) return false; } else if (!encode.equals(other.encode)) return false; if (password == null) { if (other.password != null) return false; } else if (!password.equals(other.password)) return false; if (properties == null) { if (other.properties != null) return false; } else if (!properties.equals(other.properties)) return false; if (type != other.type) return false; if (url == null) { if (other.url != null) return false; } else if (!url.equals(other.url)) return false; if (username == null) { if (other.username != null) return false; } else if (!username.equals(other.username)) return false; return true; } public String toString() {
return ToStringBuilder.reflectionToString(this, YuGongToStringStyle.DEFAULT_STYLE);
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/YuGongContext.java
// Path: cango-common/src/main/java/com/bella/cango/enums/DbType.java // public enum DbType { // MYSQL(1, "com.mysql.jdbc.Driver"), // ORACLE(2, "oracle.jdbc.driver.OracleDriver"), // DRDS(3, "com.mysql.jdbc.Driver"); // // private Integer code; // private String driver; // // DbType(Integer type, String driver) { // this.code = type; // } // // public Integer getCode() { // return code; // } // // public String getDriver() { // return driver; // } // // public boolean isOracle() { // return this.equals(ORACLE); // } // // // public boolean isMysql() { // return this.equals(MYSQL); // } // // public boolean isDRDS() { // return this.equals(DRDS); // } // // public DbType parse(Integer code) { // switch (code) { // case 1: // return MYSQL; // case 2: // return ORACLE; // case 3: // return DRDS; // default: // return null; // } // } // }
import com.bella.cango.enums.DbType; import javax.sql.DataSource;
package com.bella.cango.instance.oracle.common.model; /** * yugong数据处理上下文 * * @author kevin */ public class YuGongContext { // 具体每张表的同步 private boolean ignoreSchema = false; // 同步时是否忽略schema,oracle迁移到mysql可能schema不同,可设置为忽略 // 全局共享 private RunMode runMode; private int onceCrawNum; // 每次提取的记录数 private int tpsLimit = 0; // <=0代表不限制 private DataSource sourceDs; // 源数据库链接 private boolean batchApply = false; private boolean skipApplierException = false; // 是否允许跳过applier异常 private String sourceEncoding = "UTF-8";
// Path: cango-common/src/main/java/com/bella/cango/enums/DbType.java // public enum DbType { // MYSQL(1, "com.mysql.jdbc.Driver"), // ORACLE(2, "oracle.jdbc.driver.OracleDriver"), // DRDS(3, "com.mysql.jdbc.Driver"); // // private Integer code; // private String driver; // // DbType(Integer type, String driver) { // this.code = type; // } // // public Integer getCode() { // return code; // } // // public String getDriver() { // return driver; // } // // public boolean isOracle() { // return this.equals(ORACLE); // } // // // public boolean isMysql() { // return this.equals(MYSQL); // } // // public boolean isDRDS() { // return this.equals(DRDS); // } // // public DbType parse(Integer code) { // switch (code) { // case 1: // return MYSQL; // case 2: // return ORACLE; // case 3: // return DRDS; // default: // return null; // } // } // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/YuGongContext.java import com.bella.cango.enums.DbType; import javax.sql.DataSource; package com.bella.cango.instance.oracle.common.model; /** * yugong数据处理上下文 * * @author kevin */ public class YuGongContext { // 具体每张表的同步 private boolean ignoreSchema = false; // 同步时是否忽略schema,oracle迁移到mysql可能schema不同,可设置为忽略 // 全局共享 private RunMode runMode; private int onceCrawNum; // 每次提取的记录数 private int tpsLimit = 0; // <=0代表不限制 private DataSource sourceDs; // 源数据库链接 private boolean batchApply = false; private boolean skipApplierException = false; // 是否允许跳过applier异常 private String sourceEncoding = "UTF-8";
private DbType sourceDbType = DbType.ORACLE;
kevinKaiF/cango
cango-server/src/main/java/com/bella/cango/server/startUp/TomcatBootstrap.java
// Path: cango-service/src/main/java/com/bella/cango/service/CangoManagerService.java // public interface CangoManagerService { // // CangoResponseDto start(CangoRequestDto cangoRequestDto); // // CangoResponseDto add(CangoRequestDto cangoRequestDto); // // CangoResponseDto stop(CangoRequestDto cangoRequestDto); // // CangoResponseDto enable(CangoRequestDto cangoRequestDto); // // CangoResponseDto disable(CangoRequestDto cangoRequestDto); // // CangoResponseDto check(CangoRequestDto canalReqDto); // // CangoResponseDto startAll(); // // CangoResponseDto stopAll(); // // CangoResponseDto shutdown(); // // CangoResponseDto clearAll(); // } // // Path: cango-common/src/main/java/com/bella/cango/utils/PropertiesFileLoader.java // public class PropertiesFileLoader { // public static final String PROJECT_DIR; // // public static final String CLASSPATH_DIR; // // public static final String DEFAULT_CONF_DIR; // // public static final String DEFAULT_KAFKA_PATH; // // public static final String DEFAULT_LOG_HOME; // // static { // File classFile = new File(Thread.currentThread().getContextClassLoader().getResource(".").getFile()); // CLASSPATH_DIR = classFile.getAbsolutePath(); // PROJECT_DIR = classFile.getParentFile().getParentFile().getAbsolutePath(); // File confFile = new File(PROJECT_DIR, "src/conf"); // DEFAULT_CONF_DIR = confFile.getAbsolutePath(); // DEFAULT_KAFKA_PATH = DEFAULT_CONF_DIR + File.separator + "kafkaProduce.properties"; // DEFAULT_LOG_HOME = DEFAULT_CONF_DIR + File.separator + "log"; // } // // public static Properties loadKafkaProperties() throws IOException { // String kafkaPath = System.getProperty("kafkaProduce"); // if (StringUtils.isEmpty(kafkaPath)) { // kafkaPath = DEFAULT_KAFKA_PATH; // } // // return PropertiesLoaderUtils.loadProperties(new FileSystemResource(kafkaPath)); // } // // public static Properties load(String path) throws IOException { // if (StringUtils.isEmpty(path)) { // return new Properties(); // } // // return PropertiesLoaderUtils.loadProperties(new FileSystemResource(path)); // } // }
import com.bella.cango.service.CangoManagerService; import com.bella.cango.utils.PropertiesFileLoader; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.LifecycleException; import org.apache.catalina.connector.Connector; import org.apache.catalina.core.AprLifecycleListener; import org.apache.catalina.core.JreMemoryLeakPreventionListener; import org.apache.catalina.core.StandardServer; import org.apache.catalina.startup.Tomcat; import org.apache.commons.lang3.StringUtils; import org.apache.coyote.http11.Http11NioProtocol; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.ServletContext; import javax.servlet.ServletException; import java.io.File;
package com.bella.cango.server.startUp; /** * embed tomcat * * @author kevin * @date 2016/8/22 */ public class TomcatBootstrap { private static final Logger LOGGER = LoggerFactory.getLogger(TomcatBootstrap.class); public static void main(String[] args) throws LifecycleException, ServletException { setSystemProperties(); int port = Integer.parseInt(System.getProperty("cango.port", "8080")); String contextPath = System.getProperty("cango.contextPath", "/cango"); String docBase = System.getProperty("cango.docBase", getDefaultDocBase()); LOGGER.info("server port : {}, context path : {}, docBase : {}", port, contextPath, docBase); final Tomcat tomcat = createTomcat(port, contextPath, docBase); tomcat.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { closeTomcatGracefully(tomcat); } catch (LifecycleException e) { LOGGER.error("stop tomcat error : ", e); } } }); tomcat.getServer().await(); } private static void setSystemProperties() { System.setProperty("tomcat.util.scan.StandardJarScanFilter.jarsToSkip", "*.jar"); String logHome = System.getProperty("cango.logHome"); if (StringUtils.isEmpty(logHome)) {
// Path: cango-service/src/main/java/com/bella/cango/service/CangoManagerService.java // public interface CangoManagerService { // // CangoResponseDto start(CangoRequestDto cangoRequestDto); // // CangoResponseDto add(CangoRequestDto cangoRequestDto); // // CangoResponseDto stop(CangoRequestDto cangoRequestDto); // // CangoResponseDto enable(CangoRequestDto cangoRequestDto); // // CangoResponseDto disable(CangoRequestDto cangoRequestDto); // // CangoResponseDto check(CangoRequestDto canalReqDto); // // CangoResponseDto startAll(); // // CangoResponseDto stopAll(); // // CangoResponseDto shutdown(); // // CangoResponseDto clearAll(); // } // // Path: cango-common/src/main/java/com/bella/cango/utils/PropertiesFileLoader.java // public class PropertiesFileLoader { // public static final String PROJECT_DIR; // // public static final String CLASSPATH_DIR; // // public static final String DEFAULT_CONF_DIR; // // public static final String DEFAULT_KAFKA_PATH; // // public static final String DEFAULT_LOG_HOME; // // static { // File classFile = new File(Thread.currentThread().getContextClassLoader().getResource(".").getFile()); // CLASSPATH_DIR = classFile.getAbsolutePath(); // PROJECT_DIR = classFile.getParentFile().getParentFile().getAbsolutePath(); // File confFile = new File(PROJECT_DIR, "src/conf"); // DEFAULT_CONF_DIR = confFile.getAbsolutePath(); // DEFAULT_KAFKA_PATH = DEFAULT_CONF_DIR + File.separator + "kafkaProduce.properties"; // DEFAULT_LOG_HOME = DEFAULT_CONF_DIR + File.separator + "log"; // } // // public static Properties loadKafkaProperties() throws IOException { // String kafkaPath = System.getProperty("kafkaProduce"); // if (StringUtils.isEmpty(kafkaPath)) { // kafkaPath = DEFAULT_KAFKA_PATH; // } // // return PropertiesLoaderUtils.loadProperties(new FileSystemResource(kafkaPath)); // } // // public static Properties load(String path) throws IOException { // if (StringUtils.isEmpty(path)) { // return new Properties(); // } // // return PropertiesLoaderUtils.loadProperties(new FileSystemResource(path)); // } // } // Path: cango-server/src/main/java/com/bella/cango/server/startUp/TomcatBootstrap.java import com.bella.cango.service.CangoManagerService; import com.bella.cango.utils.PropertiesFileLoader; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.LifecycleException; import org.apache.catalina.connector.Connector; import org.apache.catalina.core.AprLifecycleListener; import org.apache.catalina.core.JreMemoryLeakPreventionListener; import org.apache.catalina.core.StandardServer; import org.apache.catalina.startup.Tomcat; import org.apache.commons.lang3.StringUtils; import org.apache.coyote.http11.Http11NioProtocol; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.ServletContext; import javax.servlet.ServletException; import java.io.File; package com.bella.cango.server.startUp; /** * embed tomcat * * @author kevin * @date 2016/8/22 */ public class TomcatBootstrap { private static final Logger LOGGER = LoggerFactory.getLogger(TomcatBootstrap.class); public static void main(String[] args) throws LifecycleException, ServletException { setSystemProperties(); int port = Integer.parseInt(System.getProperty("cango.port", "8080")); String contextPath = System.getProperty("cango.contextPath", "/cango"); String docBase = System.getProperty("cango.docBase", getDefaultDocBase()); LOGGER.info("server port : {}, context path : {}, docBase : {}", port, contextPath, docBase); final Tomcat tomcat = createTomcat(port, contextPath, docBase); tomcat.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { closeTomcatGracefully(tomcat); } catch (LifecycleException e) { LOGGER.error("stop tomcat error : ", e); } } }); tomcat.getServer().await(); } private static void setSystemProperties() { System.setProperty("tomcat.util.scan.StandardJarScanFilter.jarsToSkip", "*.jar"); String logHome = System.getProperty("cango.logHome"); if (StringUtils.isEmpty(logHome)) {
System.setProperty("cango.logHome", PropertiesFileLoader.DEFAULT_LOG_HOME);
kevinKaiF/cango
cango-server/src/main/java/com/bella/cango/server/startUp/TomcatBootstrap.java
// Path: cango-service/src/main/java/com/bella/cango/service/CangoManagerService.java // public interface CangoManagerService { // // CangoResponseDto start(CangoRequestDto cangoRequestDto); // // CangoResponseDto add(CangoRequestDto cangoRequestDto); // // CangoResponseDto stop(CangoRequestDto cangoRequestDto); // // CangoResponseDto enable(CangoRequestDto cangoRequestDto); // // CangoResponseDto disable(CangoRequestDto cangoRequestDto); // // CangoResponseDto check(CangoRequestDto canalReqDto); // // CangoResponseDto startAll(); // // CangoResponseDto stopAll(); // // CangoResponseDto shutdown(); // // CangoResponseDto clearAll(); // } // // Path: cango-common/src/main/java/com/bella/cango/utils/PropertiesFileLoader.java // public class PropertiesFileLoader { // public static final String PROJECT_DIR; // // public static final String CLASSPATH_DIR; // // public static final String DEFAULT_CONF_DIR; // // public static final String DEFAULT_KAFKA_PATH; // // public static final String DEFAULT_LOG_HOME; // // static { // File classFile = new File(Thread.currentThread().getContextClassLoader().getResource(".").getFile()); // CLASSPATH_DIR = classFile.getAbsolutePath(); // PROJECT_DIR = classFile.getParentFile().getParentFile().getAbsolutePath(); // File confFile = new File(PROJECT_DIR, "src/conf"); // DEFAULT_CONF_DIR = confFile.getAbsolutePath(); // DEFAULT_KAFKA_PATH = DEFAULT_CONF_DIR + File.separator + "kafkaProduce.properties"; // DEFAULT_LOG_HOME = DEFAULT_CONF_DIR + File.separator + "log"; // } // // public static Properties loadKafkaProperties() throws IOException { // String kafkaPath = System.getProperty("kafkaProduce"); // if (StringUtils.isEmpty(kafkaPath)) { // kafkaPath = DEFAULT_KAFKA_PATH; // } // // return PropertiesLoaderUtils.loadProperties(new FileSystemResource(kafkaPath)); // } // // public static Properties load(String path) throws IOException { // if (StringUtils.isEmpty(path)) { // return new Properties(); // } // // return PropertiesLoaderUtils.loadProperties(new FileSystemResource(path)); // } // }
import com.bella.cango.service.CangoManagerService; import com.bella.cango.utils.PropertiesFileLoader; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.LifecycleException; import org.apache.catalina.connector.Connector; import org.apache.catalina.core.AprLifecycleListener; import org.apache.catalina.core.JreMemoryLeakPreventionListener; import org.apache.catalina.core.StandardServer; import org.apache.catalina.startup.Tomcat; import org.apache.commons.lang3.StringUtils; import org.apache.coyote.http11.Http11NioProtocol; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.ServletContext; import javax.servlet.ServletException; import java.io.File;
} catch (LifecycleException e) { LOGGER.error("stop tomcat error : ", e); } } }); tomcat.getServer().await(); } private static void setSystemProperties() { System.setProperty("tomcat.util.scan.StandardJarScanFilter.jarsToSkip", "*.jar"); String logHome = System.getProperty("cango.logHome"); if (StringUtils.isEmpty(logHome)) { System.setProperty("cango.logHome", PropertiesFileLoader.DEFAULT_LOG_HOME); } } /** * Close tomcat gracefully. * * @param tomcat the tomcat * @throws LifecycleException the lifecycle exception */ private static void closeTomcatGracefully(Tomcat tomcat) throws LifecycleException { // 平滑/优雅地关闭tomcat,防止kafka消息丢失 Container[] containers = tomcat.getHost().findChildren(); if (containers != null && containers.length > 0) { Container container = containers[0]; if (container instanceof Context) { ServletContext servletContext = ((Context) container).getServletContext(); WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
// Path: cango-service/src/main/java/com/bella/cango/service/CangoManagerService.java // public interface CangoManagerService { // // CangoResponseDto start(CangoRequestDto cangoRequestDto); // // CangoResponseDto add(CangoRequestDto cangoRequestDto); // // CangoResponseDto stop(CangoRequestDto cangoRequestDto); // // CangoResponseDto enable(CangoRequestDto cangoRequestDto); // // CangoResponseDto disable(CangoRequestDto cangoRequestDto); // // CangoResponseDto check(CangoRequestDto canalReqDto); // // CangoResponseDto startAll(); // // CangoResponseDto stopAll(); // // CangoResponseDto shutdown(); // // CangoResponseDto clearAll(); // } // // Path: cango-common/src/main/java/com/bella/cango/utils/PropertiesFileLoader.java // public class PropertiesFileLoader { // public static final String PROJECT_DIR; // // public static final String CLASSPATH_DIR; // // public static final String DEFAULT_CONF_DIR; // // public static final String DEFAULT_KAFKA_PATH; // // public static final String DEFAULT_LOG_HOME; // // static { // File classFile = new File(Thread.currentThread().getContextClassLoader().getResource(".").getFile()); // CLASSPATH_DIR = classFile.getAbsolutePath(); // PROJECT_DIR = classFile.getParentFile().getParentFile().getAbsolutePath(); // File confFile = new File(PROJECT_DIR, "src/conf"); // DEFAULT_CONF_DIR = confFile.getAbsolutePath(); // DEFAULT_KAFKA_PATH = DEFAULT_CONF_DIR + File.separator + "kafkaProduce.properties"; // DEFAULT_LOG_HOME = DEFAULT_CONF_DIR + File.separator + "log"; // } // // public static Properties loadKafkaProperties() throws IOException { // String kafkaPath = System.getProperty("kafkaProduce"); // if (StringUtils.isEmpty(kafkaPath)) { // kafkaPath = DEFAULT_KAFKA_PATH; // } // // return PropertiesLoaderUtils.loadProperties(new FileSystemResource(kafkaPath)); // } // // public static Properties load(String path) throws IOException { // if (StringUtils.isEmpty(path)) { // return new Properties(); // } // // return PropertiesLoaderUtils.loadProperties(new FileSystemResource(path)); // } // } // Path: cango-server/src/main/java/com/bella/cango/server/startUp/TomcatBootstrap.java import com.bella.cango.service.CangoManagerService; import com.bella.cango.utils.PropertiesFileLoader; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.LifecycleException; import org.apache.catalina.connector.Connector; import org.apache.catalina.core.AprLifecycleListener; import org.apache.catalina.core.JreMemoryLeakPreventionListener; import org.apache.catalina.core.StandardServer; import org.apache.catalina.startup.Tomcat; import org.apache.commons.lang3.StringUtils; import org.apache.coyote.http11.Http11NioProtocol; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.ServletContext; import javax.servlet.ServletException; import java.io.File; } catch (LifecycleException e) { LOGGER.error("stop tomcat error : ", e); } } }); tomcat.getServer().await(); } private static void setSystemProperties() { System.setProperty("tomcat.util.scan.StandardJarScanFilter.jarsToSkip", "*.jar"); String logHome = System.getProperty("cango.logHome"); if (StringUtils.isEmpty(logHome)) { System.setProperty("cango.logHome", PropertiesFileLoader.DEFAULT_LOG_HOME); } } /** * Close tomcat gracefully. * * @param tomcat the tomcat * @throws LifecycleException the lifecycle exception */ private static void closeTomcatGracefully(Tomcat tomcat) throws LifecycleException { // 平滑/优雅地关闭tomcat,防止kafka消息丢失 Container[] containers = tomcat.getHost().findChildren(); if (containers != null && containers.length > 0) { Container container = containers[0]; if (container instanceof Context) { ServletContext servletContext = ((Context) container).getServletContext(); WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
webApplicationContext.getBean(CangoManagerService.class).shutdown();
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/LikeUtil.java
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // } // // Path: cango-instance/src/main/java/com/google/common/collect/MigrateMap.java // public class MigrateMap { // // @SuppressWarnings("deprecation") // public static <K, V> ConcurrentMap<K, V> makeComputingMap(MapMaker maker, // Function<? super K, ? extends V> computingFunction) { // return maker.makeComputingMap(computingFunction); // } // // @SuppressWarnings("deprecation") // public static <K, V> ConcurrentMap<K, V> makeComputingMap(Function<? super K, ? extends V> computingFunction) { // return new MapMaker().makeComputingMap(computingFunction); // } // // public static <K, V> ConcurrentMap<K, V> makeMap() { // return new MapMaker().makeMap(); // } // }
import com.bella.cango.instance.oracle.exception.YuGongException; import com.google.common.base.Function; import com.google.common.collect.MapMaker; import com.google.common.collect.MigrateMap; import org.apache.commons.lang.StringUtils; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;
package com.bella.cango.instance.oracle.common.utils; public class LikeUtil { public static String[] regexSpecialChars = {"<", ">", "^", "$", "\\", "/", ";", "(", ")", "?", ".", "*", "[", "]", "+", "|"}; public static String escapse = "\\";
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // } // // Path: cango-instance/src/main/java/com/google/common/collect/MigrateMap.java // public class MigrateMap { // // @SuppressWarnings("deprecation") // public static <K, V> ConcurrentMap<K, V> makeComputingMap(MapMaker maker, // Function<? super K, ? extends V> computingFunction) { // return maker.makeComputingMap(computingFunction); // } // // @SuppressWarnings("deprecation") // public static <K, V> ConcurrentMap<K, V> makeComputingMap(Function<? super K, ? extends V> computingFunction) { // return new MapMaker().makeComputingMap(computingFunction); // } // // public static <K, V> ConcurrentMap<K, V> makeMap() { // return new MapMaker().makeMap(); // } // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/LikeUtil.java import com.bella.cango.instance.oracle.exception.YuGongException; import com.google.common.base.Function; import com.google.common.collect.MapMaker; import com.google.common.collect.MigrateMap; import org.apache.commons.lang.StringUtils; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; package com.bella.cango.instance.oracle.common.utils; public class LikeUtil { public static String[] regexSpecialChars = {"<", ">", "^", "$", "\\", "/", ";", "(", ")", "?", ".", "*", "[", "]", "+", "|"}; public static String escapse = "\\";
private static Map<String, Pattern> patterns = MigrateMap.makeComputingMap(new MapMaker(),
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/LikeUtil.java
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // } // // Path: cango-instance/src/main/java/com/google/common/collect/MigrateMap.java // public class MigrateMap { // // @SuppressWarnings("deprecation") // public static <K, V> ConcurrentMap<K, V> makeComputingMap(MapMaker maker, // Function<? super K, ? extends V> computingFunction) { // return maker.makeComputingMap(computingFunction); // } // // @SuppressWarnings("deprecation") // public static <K, V> ConcurrentMap<K, V> makeComputingMap(Function<? super K, ? extends V> computingFunction) { // return new MapMaker().makeComputingMap(computingFunction); // } // // public static <K, V> ConcurrentMap<K, V> makeMap() { // return new MapMaker().makeMap(); // } // }
import com.bella.cango.instance.oracle.exception.YuGongException; import com.google.common.base.Function; import com.google.common.collect.MapMaker; import com.google.common.collect.MigrateMap; import org.apache.commons.lang.StringUtils; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;
package com.bella.cango.instance.oracle.common.utils; public class LikeUtil { public static String[] regexSpecialChars = {"<", ">", "^", "$", "\\", "/", ";", "(", ")", "?", ".", "*", "[", "]", "+", "|"}; public static String escapse = "\\"; private static Map<String, Pattern> patterns = MigrateMap.makeComputingMap(new MapMaker(), new Function<String, Pattern>() { public Pattern apply(String pattern) { try { return Pattern.compile(buildPattern(pattern, escapse), Pattern.CASE_INSENSITIVE); } catch (Throwable e) {
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // } // // Path: cango-instance/src/main/java/com/google/common/collect/MigrateMap.java // public class MigrateMap { // // @SuppressWarnings("deprecation") // public static <K, V> ConcurrentMap<K, V> makeComputingMap(MapMaker maker, // Function<? super K, ? extends V> computingFunction) { // return maker.makeComputingMap(computingFunction); // } // // @SuppressWarnings("deprecation") // public static <K, V> ConcurrentMap<K, V> makeComputingMap(Function<? super K, ? extends V> computingFunction) { // return new MapMaker().makeComputingMap(computingFunction); // } // // public static <K, V> ConcurrentMap<K, V> makeMap() { // return new MapMaker().makeMap(); // } // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/LikeUtil.java import com.bella.cango.instance.oracle.exception.YuGongException; import com.google.common.base.Function; import com.google.common.collect.MapMaker; import com.google.common.collect.MigrateMap; import org.apache.commons.lang.StringUtils; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; package com.bella.cango.instance.oracle.common.utils; public class LikeUtil { public static String[] regexSpecialChars = {"<", ">", "^", "$", "\\", "/", ";", "(", ")", "?", ".", "*", "[", "]", "+", "|"}; public static String escapse = "\\"; private static Map<String, Pattern> patterns = MigrateMap.makeComputingMap(new MapMaker(), new Function<String, Pattern>() { public Pattern apply(String pattern) { try { return Pattern.compile(buildPattern(pattern, escapse), Pattern.CASE_INSENSITIVE); } catch (Throwable e) {
throw new YuGongException(e);
kevinKaiF/cango
cango-dto/src/main/java/com/bella/cango/dto/CangoResponseDto.java
// Path: cango-common/src/main/java/com/bella/cango/enums/CangoRspStatus.java // public enum CangoRspStatus { // SUCCESS, // FAILURE; // }
import com.bella.cango.enums.CangoRspStatus; import java.io.Serializable;
package com.bella.cango.dto; /** * The type Cango response dto. */ public class CangoResponseDto implements Serializable { @Override public String toString() { return "CanalRspDto [ failMsg=" + failMsg + ", msg=" + msg + "]"; } private static final long serialVersionUID = -5348804938984020686L; /** * 失败信息. */ private String failMsg; /** * 成功的响应信息. */ private String msg;
// Path: cango-common/src/main/java/com/bella/cango/enums/CangoRspStatus.java // public enum CangoRspStatus { // SUCCESS, // FAILURE; // } // Path: cango-dto/src/main/java/com/bella/cango/dto/CangoResponseDto.java import com.bella.cango.enums.CangoRspStatus; import java.io.Serializable; package com.bella.cango.dto; /** * The type Cango response dto. */ public class CangoResponseDto implements Serializable { @Override public String toString() { return "CanalRspDto [ failMsg=" + failMsg + ", msg=" + msg + "]"; } private static final long serialVersionUID = -5348804938984020686L; /** * 失败信息. */ private String failMsg; /** * 成功的响应信息. */ private String msg;
private CangoRspStatus status;
kevinKaiF/cango
cango-dto/src/main/java/com/bella/cango/dto/CangoMsgDto.java
// Path: cango-common/src/main/java/com/bella/cango/enums/EventType.java // public enum EventType { // // /** // * Insert event type. // */ // INSERT(1, "insert record"), // /** // * Update event type. // */ // UPDATE(2, "update record"), // /** // * Delete event type. // */ // DELETE(3, "delete record"), // /** // * Create event type. // */ // CREATE(4, "create table"), // /** // * Alter event type. // */ // ALTER(5, "alter table"), // /** // * Erase event type. // */ // ERASE(6, "erase table"); // // /** // * The Code. // */ // private Integer code; // // /** // * The Desc. // */ // private String desc; // // /** // * Instantiates a new Event type. // * // * @param code the code // * @param desc the desc // */ // private EventType(Integer code, String desc) { // this.code = code; // this.desc = desc; // } // // /** // * Value of event type. // * // * @param code the code // * @return the event type // */ // public static EventType valueOf(Integer code) { // if (code != null) { // EventType[] values = values(); // for (EventType value : values) { // if (code.equals(value.code)) { // return value; // } // } // // } // return null; // } // // /** // * Gets code. // * // * @return the code // */ // public Integer getCode() { // return code; // } // // /** // * Sets code. // * // * @param code the code // */ // public void setCode(Integer code) { // this.code = code; // } // // /** // * Gets desc. // * // * @return the desc // */ // public String getDesc() { // return desc; // } // // /** // * Sets desc. // * // * @param desc the desc // */ // public void setDesc(String desc) { // this.desc = desc; // } // // }
import com.bella.cango.enums.EventType; import java.util.List;
package com.bella.cango.dto; /** * TODO * * @author kevin * @date 2016/8/7 */ public class CangoMsgDto { /** * 序列化ID,要保证兼容性时不要修改此值 */ private static final long serialVersionUID = -1655844036921106774L; /** * Cango实例名称. */ protected String name; /** * 变更的数据库地址 */ protected String dbHost; /** * 变更的数据库端口 */ protected Integer dbPort; /** * 变更的数据库名称 */ protected String dbName; /** * 变更的表名 */ protected String tableName; /** * 变更类型 */
// Path: cango-common/src/main/java/com/bella/cango/enums/EventType.java // public enum EventType { // // /** // * Insert event type. // */ // INSERT(1, "insert record"), // /** // * Update event type. // */ // UPDATE(2, "update record"), // /** // * Delete event type. // */ // DELETE(3, "delete record"), // /** // * Create event type. // */ // CREATE(4, "create table"), // /** // * Alter event type. // */ // ALTER(5, "alter table"), // /** // * Erase event type. // */ // ERASE(6, "erase table"); // // /** // * The Code. // */ // private Integer code; // // /** // * The Desc. // */ // private String desc; // // /** // * Instantiates a new Event type. // * // * @param code the code // * @param desc the desc // */ // private EventType(Integer code, String desc) { // this.code = code; // this.desc = desc; // } // // /** // * Value of event type. // * // * @param code the code // * @return the event type // */ // public static EventType valueOf(Integer code) { // if (code != null) { // EventType[] values = values(); // for (EventType value : values) { // if (code.equals(value.code)) { // return value; // } // } // // } // return null; // } // // /** // * Gets code. // * // * @return the code // */ // public Integer getCode() { // return code; // } // // /** // * Sets code. // * // * @param code the code // */ // public void setCode(Integer code) { // this.code = code; // } // // /** // * Gets desc. // * // * @return the desc // */ // public String getDesc() { // return desc; // } // // /** // * Sets desc. // * // * @param desc the desc // */ // public void setDesc(String desc) { // this.desc = desc; // } // // } // Path: cango-dto/src/main/java/com/bella/cango/dto/CangoMsgDto.java import com.bella.cango.enums.EventType; import java.util.List; package com.bella.cango.dto; /** * TODO * * @author kevin * @date 2016/8/7 */ public class CangoMsgDto { /** * 序列化ID,要保证兼容性时不要修改此值 */ private static final long serialVersionUID = -1655844036921106774L; /** * Cango实例名称. */ protected String name; /** * 变更的数据库地址 */ protected String dbHost; /** * 变更的数据库端口 */ protected Integer dbPort; /** * 变更的数据库名称 */ protected String dbName; /** * 变更的表名 */ protected String tableName; /** * 变更类型 */
protected EventType eventType;
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/TableMetaGenerator.java
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/LikeUtil.java // public class LikeUtil { // // public static String[] regexSpecialChars = {"<", ">", "^", "$", "\\", "/", ";", "(", ")", "?", ".", // "*", "[", "]", "+", "|"}; // public static String escapse = "\\"; // // private static Map<String, Pattern> patterns = MigrateMap.makeComputingMap(new MapMaker(), // new Function<String, Pattern>() { // // public Pattern apply(String pattern) { // try { // return Pattern.compile(buildPattern(pattern, // escapse), // Pattern.CASE_INSENSITIVE); // } catch (Throwable e) { // throw new YuGongException(e); // } // } // }); // // public static boolean isMatch(String pattern, String value) { // if (StringUtils.equalsIgnoreCase(pattern, value)) { // return true; // } else if (StringUtils.isEmpty(value)) { // return false; // } else if (StringUtils.isEmpty(pattern)) { // return false; // } // // Pattern pat = patterns.get(pattern); // Matcher m = pat.matcher(value); // return m.matches(); // } // // private static String buildPattern(String pattern, String escape) { // char esc = escape.charAt(0); // pattern = StringUtils.trim(pattern); // StringBuilder builder = new StringBuilder("^"); // int index = 0, last = 0; // while (true) { // // 查找esc // index = pattern.indexOf(esc, last); // if (index == -1 || index >= pattern.length()) { // if (last < pattern.length()) { // builder.append(convertWildcard(ripRegex(pattern.substring(last)))); // } // break; // } // if (index > 0) { // String toRipRegex = StringUtils.substring(pattern, last, index); // builder.append(convertWildcard(ripRegex(toRipRegex))); // last = index; // } // if (index + 1 < pattern.length()) { // builder.append(ripRegex(pattern.charAt(index + 1))); // last = index + 2; // } else { // builder.append(pattern.charAt(index)); // last = index + 1; // } // if (last >= pattern.length()) { // break; // } // } // builder.append('$'); // return builder.toString(); // } // // private static String ripRegex(char toRip) { // char[] chars = new char[1]; // chars[0] = toRip; // return ripRegex(new String(chars)); // } // // private static String ripRegex(String toRip) { // for (String c : regexSpecialChars) { // toRip = StringUtils.replace(toRip, c, "\\" + c); // } // // return toRip; // } // // private static String convertWildcard(String toConvert) { // toConvert = StringUtils.replace(toConvert, "_", "(.)"); // toConvert = StringUtils.replace(toConvert, "%", "(.*)"); // return toConvert; // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // }
import com.bella.cango.instance.oracle.common.utils.LikeUtil; import com.bella.cango.instance.oracle.exception.YuGongException; import com.google.common.collect.Lists; import org.apache.commons.lang.StringUtils; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCallback; import org.springframework.jdbc.support.JdbcUtils; import javax.sql.DataSource; import java.sql.*; import java.util.*;
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return (Table) jdbcTemplate.execute(new ConnectionCallback() { public Object doInConnection(Connection conn) throws SQLException, DataAccessException { DatabaseMetaData metaData = conn.getMetaData(); String sName = getIdentifierName(schemaName, metaData); String tName = getIdentifierName(tableName, metaData); ResultSet rs = null; Table table; try { rs = metaData.getTables(sName, sName, tName, new String[]{"TABLE"}); table = null; while (rs.next()) { String catlog = rs.getString(1); String schema = rs.getString(2); String name = rs.getString(3); String type = rs.getString(4); if ((sName == null || LikeUtil.isMatch(sName, catlog) || LikeUtil.isMatch(sName, schema)) && LikeUtil.isMatch(tName, name)) { table = new Table(type, StringUtils.isEmpty(catlog) ? schema : catlog, name); break; } } } finally { JdbcUtils.closeResultSet(rs); } if (table == null) {
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/LikeUtil.java // public class LikeUtil { // // public static String[] regexSpecialChars = {"<", ">", "^", "$", "\\", "/", ";", "(", ")", "?", ".", // "*", "[", "]", "+", "|"}; // public static String escapse = "\\"; // // private static Map<String, Pattern> patterns = MigrateMap.makeComputingMap(new MapMaker(), // new Function<String, Pattern>() { // // public Pattern apply(String pattern) { // try { // return Pattern.compile(buildPattern(pattern, // escapse), // Pattern.CASE_INSENSITIVE); // } catch (Throwable e) { // throw new YuGongException(e); // } // } // }); // // public static boolean isMatch(String pattern, String value) { // if (StringUtils.equalsIgnoreCase(pattern, value)) { // return true; // } else if (StringUtils.isEmpty(value)) { // return false; // } else if (StringUtils.isEmpty(pattern)) { // return false; // } // // Pattern pat = patterns.get(pattern); // Matcher m = pat.matcher(value); // return m.matches(); // } // // private static String buildPattern(String pattern, String escape) { // char esc = escape.charAt(0); // pattern = StringUtils.trim(pattern); // StringBuilder builder = new StringBuilder("^"); // int index = 0, last = 0; // while (true) { // // 查找esc // index = pattern.indexOf(esc, last); // if (index == -1 || index >= pattern.length()) { // if (last < pattern.length()) { // builder.append(convertWildcard(ripRegex(pattern.substring(last)))); // } // break; // } // if (index > 0) { // String toRipRegex = StringUtils.substring(pattern, last, index); // builder.append(convertWildcard(ripRegex(toRipRegex))); // last = index; // } // if (index + 1 < pattern.length()) { // builder.append(ripRegex(pattern.charAt(index + 1))); // last = index + 2; // } else { // builder.append(pattern.charAt(index)); // last = index + 1; // } // if (last >= pattern.length()) { // break; // } // } // builder.append('$'); // return builder.toString(); // } // // private static String ripRegex(char toRip) { // char[] chars = new char[1]; // chars[0] = toRip; // return ripRegex(new String(chars)); // } // // private static String ripRegex(String toRip) { // for (String c : regexSpecialChars) { // toRip = StringUtils.replace(toRip, c, "\\" + c); // } // // return toRip; // } // // private static String convertWildcard(String toConvert) { // toConvert = StringUtils.replace(toConvert, "_", "(.)"); // toConvert = StringUtils.replace(toConvert, "%", "(.*)"); // return toConvert; // } // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/exception/YuGongException.java // public class YuGongException extends NestableRuntimeException { // // private static final long serialVersionUID = -654893533794556357L; // // public YuGongException(String errorCode) { // super(errorCode); // } // // public YuGongException(String errorCode, Throwable cause) { // super(errorCode, cause); // } // // public YuGongException(String errorCode, String errorDesc) { // super(errorCode + ":" + errorDesc); // } // // public YuGongException(String errorCode, String errorDesc, Throwable cause) { // super(errorCode + ":" + errorDesc, cause); // } // // public YuGongException(Throwable cause) { // super(cause); // } // // // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/TableMetaGenerator.java import com.bella.cango.instance.oracle.common.utils.LikeUtil; import com.bella.cango.instance.oracle.exception.YuGongException; import com.google.common.collect.Lists; import org.apache.commons.lang.StringUtils; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCallback; import org.springframework.jdbc.support.JdbcUtils; import javax.sql.DataSource; import java.sql.*; import java.util.*; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return (Table) jdbcTemplate.execute(new ConnectionCallback() { public Object doInConnection(Connection conn) throws SQLException, DataAccessException { DatabaseMetaData metaData = conn.getMetaData(); String sName = getIdentifierName(schemaName, metaData); String tName = getIdentifierName(tableName, metaData); ResultSet rs = null; Table table; try { rs = metaData.getTables(sName, sName, tName, new String[]{"TABLE"}); table = null; while (rs.next()) { String catlog = rs.getString(1); String schema = rs.getString(2); String name = rs.getString(3); String type = rs.getString(4); if ((sName == null || LikeUtil.isMatch(sName, catlog) || LikeUtil.isMatch(sName, schema)) && LikeUtil.isMatch(tName, name)) { table = new Table(type, StringUtils.isEmpty(catlog) ? schema : catlog, name); break; } } } finally { JdbcUtils.closeResultSet(rs); } if (table == null) {
throw new YuGongException("table[" + schemaName + "." + tableName + "] is not found");
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/record/IncrementRecord.java
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnValue.java // public class ColumnValue { // // private ColumnMeta column; // private Object value; // private boolean check = true; // 是否需要做数据对比 // // public ColumnValue() { // } // // public ColumnValue(ColumnMeta column, Object value) { // this(column, value, true); // } // // public ColumnValue(ColumnMeta column, Object value, boolean check) { // this.value = value; // this.column = column; // this.check = check; // } // // public ColumnMeta getColumn() { // return column; // } // // public void setColumn(ColumnMeta column) { // this.column = column; // } // // public Object getValue() { // return value; // } // // public void setValue(Object value) { // this.value = value; // } // // public boolean isCheck() { // return check; // } // // public void setCheck(boolean check) { // this.check = check; // } // // public ColumnValue clone() { // ColumnValue column = new ColumnValue(); // column.setValue(this.value); // column.setColumn(this.column.clone()); // return column; // } // // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((column == null) ? 0 : column.hashCode()); // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnValue other = (ColumnValue) obj; // if (column == null) { // if (other.column != null) return false; // } else if (!column.equals(other.column)) return false; // if (value == null) { // if (other.value != null) return false; // } else if (!value.equals(other.value)) return false; // return true; // } // // @Override // public String toString() { // return "ColumnValue [column=" + column + ", value=" + value + "]"; // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // }
import com.bella.cango.instance.oracle.common.db.meta.ColumnValue; import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import org.apache.commons.lang.builder.ToStringBuilder; import java.util.List;
package com.bella.cango.instance.oracle.common.model.record; /** * 增量的record对象 * * @author agapple 2013-9-16 下午4:20:25 */ public class IncrementRecord extends Record { private IncrementOpType opType; public IncrementRecord() { super(); }
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnValue.java // public class ColumnValue { // // private ColumnMeta column; // private Object value; // private boolean check = true; // 是否需要做数据对比 // // public ColumnValue() { // } // // public ColumnValue(ColumnMeta column, Object value) { // this(column, value, true); // } // // public ColumnValue(ColumnMeta column, Object value, boolean check) { // this.value = value; // this.column = column; // this.check = check; // } // // public ColumnMeta getColumn() { // return column; // } // // public void setColumn(ColumnMeta column) { // this.column = column; // } // // public Object getValue() { // return value; // } // // public void setValue(Object value) { // this.value = value; // } // // public boolean isCheck() { // return check; // } // // public void setCheck(boolean check) { // this.check = check; // } // // public ColumnValue clone() { // ColumnValue column = new ColumnValue(); // column.setValue(this.value); // column.setColumn(this.column.clone()); // return column; // } // // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((column == null) ? 0 : column.hashCode()); // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnValue other = (ColumnValue) obj; // if (column == null) { // if (other.column != null) return false; // } else if (!column.equals(other.column)) return false; // if (value == null) { // if (other.value != null) return false; // } else if (!value.equals(other.value)) return false; // return true; // } // // @Override // public String toString() { // return "ColumnValue [column=" + column + ", value=" + value + "]"; // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/record/IncrementRecord.java import com.bella.cango.instance.oracle.common.db.meta.ColumnValue; import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import org.apache.commons.lang.builder.ToStringBuilder; import java.util.List; package com.bella.cango.instance.oracle.common.model.record; /** * 增量的record对象 * * @author agapple 2013-9-16 下午4:20:25 */ public class IncrementRecord extends Record { private IncrementOpType opType; public IncrementRecord() { super(); }
public IncrementRecord(String schemaName, String tableName, List<ColumnValue> primaryKeys, List<ColumnValue> columns) {
kevinKaiF/cango
cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/record/IncrementRecord.java
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnValue.java // public class ColumnValue { // // private ColumnMeta column; // private Object value; // private boolean check = true; // 是否需要做数据对比 // // public ColumnValue() { // } // // public ColumnValue(ColumnMeta column, Object value) { // this(column, value, true); // } // // public ColumnValue(ColumnMeta column, Object value, boolean check) { // this.value = value; // this.column = column; // this.check = check; // } // // public ColumnMeta getColumn() { // return column; // } // // public void setColumn(ColumnMeta column) { // this.column = column; // } // // public Object getValue() { // return value; // } // // public void setValue(Object value) { // this.value = value; // } // // public boolean isCheck() { // return check; // } // // public void setCheck(boolean check) { // this.check = check; // } // // public ColumnValue clone() { // ColumnValue column = new ColumnValue(); // column.setValue(this.value); // column.setColumn(this.column.clone()); // return column; // } // // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((column == null) ? 0 : column.hashCode()); // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnValue other = (ColumnValue) obj; // if (column == null) { // if (other.column != null) return false; // } else if (!column.equals(other.column)) return false; // if (value == null) { // if (other.value != null) return false; // } else if (!value.equals(other.value)) return false; // return true; // } // // @Override // public String toString() { // return "ColumnValue [column=" + column + ", value=" + value + "]"; // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // }
import com.bella.cango.instance.oracle.common.db.meta.ColumnValue; import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import org.apache.commons.lang.builder.ToStringBuilder; import java.util.List;
if (opType == IncrementOpType.D) { return super.getColumnByName(columnName, true); // delete的时候可能缺少列,返回null值 } else { return super.getColumnByName(columnName); } } @Override public ColumnValue removeColumnByName(String columnName) { if (opType == IncrementOpType.D) { return super.removeColumnByName(columnName, true); // delete的时候可能缺少列,返回null值 } else { return super.removeColumnByName(columnName); } } @Override public IncrementRecord clone() { IncrementRecord record = new IncrementRecord(); super.clone(record); record.setOpType(this.opType); return record; } public void clone(IncrementRecord record) { super.clone(record); record.setOpType(this.opType); } public String toString() {
// Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/db/meta/ColumnValue.java // public class ColumnValue { // // private ColumnMeta column; // private Object value; // private boolean check = true; // 是否需要做数据对比 // // public ColumnValue() { // } // // public ColumnValue(ColumnMeta column, Object value) { // this(column, value, true); // } // // public ColumnValue(ColumnMeta column, Object value, boolean check) { // this.value = value; // this.column = column; // this.check = check; // } // // public ColumnMeta getColumn() { // return column; // } // // public void setColumn(ColumnMeta column) { // this.column = column; // } // // public Object getValue() { // return value; // } // // public void setValue(Object value) { // this.value = value; // } // // public boolean isCheck() { // return check; // } // // public void setCheck(boolean check) { // this.check = check; // } // // public ColumnValue clone() { // ColumnValue column = new ColumnValue(); // column.setValue(this.value); // column.setColumn(this.column.clone()); // return column; // } // // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((column == null) ? 0 : column.hashCode()); // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // public boolean equals(Object obj) { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // ColumnValue other = (ColumnValue) obj; // if (column == null) { // if (other.column != null) return false; // } else if (!column.equals(other.column)) return false; // if (value == null) { // if (other.value != null) return false; // } else if (!value.equals(other.value)) return false; // return true; // } // // @Override // public String toString() { // return "ColumnValue [column=" + column + ", value=" + value + "]"; // } // // } // // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/utils/YuGongToStringStyle.java // public class YuGongToStringStyle extends ToStringStyle { // // private static final long serialVersionUID = -6568177374288222145L; // // public static final ToStringStyle DEFAULT_STYLE = new DateStyle("yyyy-MM-dd HH:mm:ss"); // // private static class DateStyle extends ToStringStyle { // // private static final long serialVersionUID = 5208917932254652886L; // // private String datePattern; // // public DateStyle(String datePattern) { // super(); // this.setUseIdentityHashCode(false); // this.setUseShortClassName(true); // this.datePattern = datePattern; // } // // protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { // if (value instanceof Date) { // value = new SimpleDateFormat(datePattern).format(value); // } else { // buffer.append(value); // } // } // } // } // Path: cango-instance/src/main/java/com/bella/cango/instance/oracle/common/model/record/IncrementRecord.java import com.bella.cango.instance.oracle.common.db.meta.ColumnValue; import com.bella.cango.instance.oracle.common.utils.YuGongToStringStyle; import org.apache.commons.lang.builder.ToStringBuilder; import java.util.List; if (opType == IncrementOpType.D) { return super.getColumnByName(columnName, true); // delete的时候可能缺少列,返回null值 } else { return super.getColumnByName(columnName); } } @Override public ColumnValue removeColumnByName(String columnName) { if (opType == IncrementOpType.D) { return super.removeColumnByName(columnName, true); // delete的时候可能缺少列,返回null值 } else { return super.removeColumnByName(columnName); } } @Override public IncrementRecord clone() { IncrementRecord record = new IncrementRecord(); super.clone(record); record.setOpType(this.opType); return record; } public void clone(IncrementRecord record) { super.clone(record); record.setOpType(this.opType); } public String toString() {
return ToStringBuilder.reflectionToString(this, YuGongToStringStyle.DEFAULT_STYLE);
bgandon/killbill-simple-tax-plugin
src/main/java/org/killbill/billing/plugin/simpletax/internal/VATINValidator.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ConcurrentLazyValue.java // public abstract class ConcurrentLazyValue<T> extends LazyValue<T> { // // /** Whether the value is initialized. */ // private boolean initialized = false; // // /** Stores the managed object. */ // private T value; // // /** // * Returns the value wrapped by this instance, initializing it on first // * access. Subsequent access return the cached value. // * // * @return The object initialized by this {@code LazyValue}. // */ // @Override // public T get() { // if (!initialized) { // synchronized (this) { // if (!initialized) { // value = initialize(); // initialized = true; // } // } // } // return value; // } // // }
import com.google.common.collect.Multimap; import static com.google.common.primitives.Ints.tryParse; import static java.util.regex.Pattern.compile; import static org.apache.commons.lang3.StringUtils.substring; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.killbill.billing.plugin.simpletax.util.ConcurrentLazyValue; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableMultimap;
/* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.internal; /** * A validator for VAT Identification Numbers (VATIN), based on the <a * href="http://www.braemoor.co.uk/software/vat.shtml">JavaScript EU VAT Number * Validation</a>. * * @author Benjamin Gandon */ public class VATINValidator implements Predicate<String> { private static final int COUNTRY_PREFIX_LENGTH = 2; private static final int VATIN_TAIL_GROUP = 2; private static Pair<Pattern, Predicate<String>> pair(Pattern pattern, Predicate<String> validator) { return ImmutablePair.of(pattern, validator); }
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ConcurrentLazyValue.java // public abstract class ConcurrentLazyValue<T> extends LazyValue<T> { // // /** Whether the value is initialized. */ // private boolean initialized = false; // // /** Stores the managed object. */ // private T value; // // /** // * Returns the value wrapped by this instance, initializing it on first // * access. Subsequent access return the cached value. // * // * @return The object initialized by this {@code LazyValue}. // */ // @Override // public T get() { // if (!initialized) { // synchronized (this) { // if (!initialized) { // value = initialize(); // initialized = true; // } // } // } // return value; // } // // } // Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/VATINValidator.java import com.google.common.collect.Multimap; import static com.google.common.primitives.Ints.tryParse; import static java.util.regex.Pattern.compile; import static org.apache.commons.lang3.StringUtils.substring; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.killbill.billing.plugin.simpletax.util.ConcurrentLazyValue; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableMultimap; /* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.internal; /** * A validator for VAT Identification Numbers (VATIN), based on the <a * href="http://www.braemoor.co.uk/software/vat.shtml">JavaScript EU VAT Number * Validation</a>. * * @author Benjamin Gandon */ public class VATINValidator implements Predicate<String> { private static final int COUNTRY_PREFIX_LENGTH = 2; private static final int VATIN_TAIL_GROUP = 2; private static Pair<Pattern, Predicate<String>> pair(Pattern pattern, Predicate<String> validator) { return ImmutablePair.of(pattern, validator); }
private static final Supplier<Multimap<String, Pair<Pattern, Predicate<String>>>> PATTERNS = new ConcurrentLazyValue<Multimap<String, Pair<Pattern, Predicate<String>>>>() {
bgandon/killbill-simple-tax-plugin
src/main/java/org/killbill/billing/plugin/simpletax/internal/VATIN.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ShortToStringStyle.java // public static final ToStringStyle SHORT_STYLE = new ShortToStringStyle();
import static com.google.common.base.Preconditions.checkArgument; import static org.killbill.billing.plugin.simpletax.util.ShortToStringStyle.SHORT_STYLE; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue;
/** * @return The VAT Identificaiton Number. */ @JsonValue public String getNumber() { return number; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } VATIN rhs = (VATIN) obj; return new EqualsBuilder().append(number, rhs.number).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder().append(number).toHashCode(); } @Override public String toString() {
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ShortToStringStyle.java // public static final ToStringStyle SHORT_STYLE = new ShortToStringStyle(); // Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/VATIN.java import static com.google.common.base.Preconditions.checkArgument; import static org.killbill.billing.plugin.simpletax.util.ShortToStringStyle.SHORT_STYLE; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** * @return The VAT Identificaiton Number. */ @JsonValue public String getNumber() { return number; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } VATIN rhs = (VATIN) obj; return new EqualsBuilder().append(number, rhs.number).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder().append(number).toHashCode(); } @Override public String toString() {
return new ToStringBuilder(this, SHORT_STYLE)//
bgandon/killbill-simple-tax-plugin
src/test/java/org/killbill/billing/plugin/simpletax/internal/TestVATIN.java
// Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public static String shortIdentityToString(Object obj) { // if (obj == null) { // return null; // } // return obj.getClass().getSimpleName() + '@' + toHexString(identityHashCode(obj)); // }
import static org.killbill.billing.test.helpers.TestUtil.shortIdentityToString; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import org.testng.annotations.DataProvider; import org.testng.annotations.Test;
@Test(groups = "fast") public void shouldEnforceEquality() { // Expect assertFalse(FR_TEST0.equals(null)); assertFalse(FR_TEST1.equals(null)); assertTrue(FR_TEST0.equals(FR_TEST0)); assertTrue(FR_TEST1.equals(FR_TEST1)); assertFalse(FR_TEST0.equals(new Object())); assertFalse(FR_TEST1.equals(FR_TEST1_NUM)); assertTrue(FR_TEST0.equals(new VATIN(FR_TEST0_NUM))); assertTrue(FR_TEST1.equals(new VATIN(FR_TEST1_NUM))); assertFalse(FR_TEST0.equals(new VATIN(FR_TEST8_NUM))); assertFalse(FR_TEST1.equals(new VATIN(FR_TEST9_NUM))); } @Test(groups = "fast") public void shouldComputeHashCode() { // Expect assertEquals(FR_TEST0.hashCode(), 1807022424); assertEquals(FR_TEST1.hashCode(), 666000569); assertEquals(FR_TEST2.hashCode(), -475021286); assertEquals(FR_TEST8.hashCode(), 1637069758L); assertEquals(FR_TEST9.hashCode(), (17 * 37) + FR_TEST9_NUM.hashCode()); } @Test(groups = "fast") public void shouldOutputVATIN() { // Expect
// Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public static String shortIdentityToString(Object obj) { // if (obj == null) { // return null; // } // return obj.getClass().getSimpleName() + '@' + toHexString(identityHashCode(obj)); // } // Path: src/test/java/org/killbill/billing/plugin/simpletax/internal/TestVATIN.java import static org.killbill.billing.test.helpers.TestUtil.shortIdentityToString; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @Test(groups = "fast") public void shouldEnforceEquality() { // Expect assertFalse(FR_TEST0.equals(null)); assertFalse(FR_TEST1.equals(null)); assertTrue(FR_TEST0.equals(FR_TEST0)); assertTrue(FR_TEST1.equals(FR_TEST1)); assertFalse(FR_TEST0.equals(new Object())); assertFalse(FR_TEST1.equals(FR_TEST1_NUM)); assertTrue(FR_TEST0.equals(new VATIN(FR_TEST0_NUM))); assertTrue(FR_TEST1.equals(new VATIN(FR_TEST1_NUM))); assertFalse(FR_TEST0.equals(new VATIN(FR_TEST8_NUM))); assertFalse(FR_TEST1.equals(new VATIN(FR_TEST9_NUM))); } @Test(groups = "fast") public void shouldComputeHashCode() { // Expect assertEquals(FR_TEST0.hashCode(), 1807022424); assertEquals(FR_TEST1.hashCode(), 666000569); assertEquals(FR_TEST2.hashCode(), -475021286); assertEquals(FR_TEST8.hashCode(), 1637069758L); assertEquals(FR_TEST9.hashCode(), (17 * 37) + FR_TEST9_NUM.hashCode()); } @Test(groups = "fast") public void shouldOutputVATIN() { // Expect
assertEquals(FR_TEST0.toString(), shortIdentityToString(FR_TEST0) + "[number=" + FR_TEST0_NUM + "]");
bgandon/killbill-simple-tax-plugin
src/main/java/org/killbill/billing/plugin/simpletax/resolving/TaxResolver.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/TaxCode.java // public class TaxCode { // // private String name; // private String taxItemDescription; // private BigDecimal rate; // private LocalDate startingOn; // private LocalDate stoppingOn; // private Country country; // // /** // * constructs a new tax code definition. // * // * @param name // * The unique name for the tax code. // * @param taxItemDescription // * The description for tax items that will be generated by the // * tax code. // * @param rate // * The tax rate to apply when computing tax amounts. // * @param startingOn // * The first day on which the tax code will <em>start</em> being // * applicable, or {@code null} if the tax code has no sunrise // * date. // * @param stoppingOn // * The first day on which this tax code will <em>cease</em> to be // * applicable, or {@code null} if the tax code has no sunset // * date. // * @param country // * The country on which this tax code applies. // */ // public TaxCode(String name, String taxItemDescription, BigDecimal rate, LocalDate startingOn, LocalDate stoppingOn, // Country country) { // super(); // this.name = name; // this.taxItemDescription = taxItemDescription; // this.rate = rate; // this.startingOn = startingOn; // this.stoppingOn = stoppingOn; // this.country = country; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // TaxCode rhs = (TaxCode) obj; // if (!new EqualsBuilder()// // .append(name, rhs.name)// // .append(taxItemDescription, rhs.taxItemDescription)// // .append(startingOn, rhs.startingOn)// // .append(stoppingOn, rhs.stoppingOn)// // .append(country, rhs.country)// // .isEquals()) { // return false; // } // // Custom processing BigDecimal equality ignoring scale // if (rate == null) { // return rhs.rate == null; // } // return rate.compareTo(rhs.rate) == 0; // } // // @Override // public int hashCode() { // return new HashCodeBuilder()// // .append(name)// // .append(taxItemDescription)// // // Custom processing BigDecimal hash ignoring scale // .append(rate == null ? 0 : rate.toString())// // .append(startingOn)// // .append(stoppingOn)// // .append(country)// // .toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this, SHORT_STYLE)// // .append("name", name)// // .append("taxItemDescription", taxItemDescription)// // .append("rate", rate)// // .append("startingOn", startingOn)// // .append("stoppingOn", stoppingOn)// // .append("country", country)// // .toString(); // } // // /** // * @return The unique name of this tax code. // */ // public String getName() { // return name; // } // // /** // * @return The description for tax items that are generated by this tax // * code. // */ // public String getTaxItemDescription() { // return taxItemDescription; // } // // /** // * @return The tax rate to apply when computing tax amounts. // */ // public BigDecimal getRate() { // return rate; // } // // /** // * @return The first day on which this tax code <em>starts</em> being // * applicable. // */ // public LocalDate getStartingOn() { // return startingOn; // } // // /** // * @return The first day on which this tax code <em>ceases</em> to be // * applicable. // */ // public LocalDate getStoppingOn() { // return stoppingOn; // } // // /** // * @return The country on which this tax code applies. // */ // public Country getCountry() { // return country; // } // }
import javax.annotation.Nullable; import org.killbill.billing.invoice.api.InvoiceItem; import org.killbill.billing.plugin.simpletax.internal.TaxCode;
/* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.resolving; /** * Tax resolvers are meant to apply regulation specific rules when determining * which tax code actually applies, in a set of potential candidates. * <p> * Constructors of implementing classes must accept one single argument of type * {@link org.killbill.billing.plugin.simpletax.TaxComputationContext}. * * @author Benjamin Gandon */ public interface TaxResolver { /** * Retain only one applicable tax code, so that taxation of invoice item can * be done, based on the returned tax code. * * @param taxCodes * The candidate tax codes for this invoice item. * @param item * The invoice item to tax. * @return The tax code to apply to this item, or {@code null} if none * applies. */ @Nullable
// Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/TaxCode.java // public class TaxCode { // // private String name; // private String taxItemDescription; // private BigDecimal rate; // private LocalDate startingOn; // private LocalDate stoppingOn; // private Country country; // // /** // * constructs a new tax code definition. // * // * @param name // * The unique name for the tax code. // * @param taxItemDescription // * The description for tax items that will be generated by the // * tax code. // * @param rate // * The tax rate to apply when computing tax amounts. // * @param startingOn // * The first day on which the tax code will <em>start</em> being // * applicable, or {@code null} if the tax code has no sunrise // * date. // * @param stoppingOn // * The first day on which this tax code will <em>cease</em> to be // * applicable, or {@code null} if the tax code has no sunset // * date. // * @param country // * The country on which this tax code applies. // */ // public TaxCode(String name, String taxItemDescription, BigDecimal rate, LocalDate startingOn, LocalDate stoppingOn, // Country country) { // super(); // this.name = name; // this.taxItemDescription = taxItemDescription; // this.rate = rate; // this.startingOn = startingOn; // this.stoppingOn = stoppingOn; // this.country = country; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // TaxCode rhs = (TaxCode) obj; // if (!new EqualsBuilder()// // .append(name, rhs.name)// // .append(taxItemDescription, rhs.taxItemDescription)// // .append(startingOn, rhs.startingOn)// // .append(stoppingOn, rhs.stoppingOn)// // .append(country, rhs.country)// // .isEquals()) { // return false; // } // // Custom processing BigDecimal equality ignoring scale // if (rate == null) { // return rhs.rate == null; // } // return rate.compareTo(rhs.rate) == 0; // } // // @Override // public int hashCode() { // return new HashCodeBuilder()// // .append(name)// // .append(taxItemDescription)// // // Custom processing BigDecimal hash ignoring scale // .append(rate == null ? 0 : rate.toString())// // .append(startingOn)// // .append(stoppingOn)// // .append(country)// // .toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this, SHORT_STYLE)// // .append("name", name)// // .append("taxItemDescription", taxItemDescription)// // .append("rate", rate)// // .append("startingOn", startingOn)// // .append("stoppingOn", stoppingOn)// // .append("country", country)// // .toString(); // } // // /** // * @return The unique name of this tax code. // */ // public String getName() { // return name; // } // // /** // * @return The description for tax items that are generated by this tax // * code. // */ // public String getTaxItemDescription() { // return taxItemDescription; // } // // /** // * @return The tax rate to apply when computing tax amounts. // */ // public BigDecimal getRate() { // return rate; // } // // /** // * @return The first day on which this tax code <em>starts</em> being // * applicable. // */ // public LocalDate getStartingOn() { // return startingOn; // } // // /** // * @return The first day on which this tax code <em>ceases</em> to be // * applicable. // */ // public LocalDate getStoppingOn() { // return stoppingOn; // } // // /** // * @return The country on which this tax code applies. // */ // public Country getCountry() { // return country; // } // } // Path: src/main/java/org/killbill/billing/plugin/simpletax/resolving/TaxResolver.java import javax.annotation.Nullable; import org.killbill.billing.invoice.api.InvoiceItem; import org.killbill.billing.plugin.simpletax.internal.TaxCode; /* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.resolving; /** * Tax resolvers are meant to apply regulation specific rules when determining * which tax code actually applies, in a set of potential candidates. * <p> * Constructors of implementing classes must accept one single argument of type * {@link org.killbill.billing.plugin.simpletax.TaxComputationContext}. * * @author Benjamin Gandon */ public interface TaxResolver { /** * Retain only one applicable tax code, so that taxation of invoice item can * be done, based on the returned tax code. * * @param taxCodes * The candidate tax codes for this invoice item. * @param item * The invoice item to tax. * @return The tax code to apply to this item, or {@code null} if none * applies. */ @Nullable
public abstract TaxCode applicableCodeForItem(Iterable<TaxCode> taxCodes, InvoiceItem item);
bgandon/killbill-simple-tax-plugin
src/test/java/org/killbill/billing/plugin/simpletax/internal/TestCountry.java
// Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public static String shortIdentityToString(Object obj) { // if (obj == null) { // return null; // } // return obj.getClass().getSimpleName() + '@' + toHexString(identityHashCode(obj)); // }
import static java.util.Locale.ENGLISH; import static java.util.Locale.FRENCH; import static org.killbill.billing.test.helpers.TestUtil.shortIdentityToString; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import org.testng.annotations.DataProvider; import org.testng.annotations.Test;
assertEquals(new Country(legalCountryCode).getCode(), legalCountryCode); } @Test(groups = "fast") public void shouldReturnLocalizedName() { // Expect assertEquals(US.computeName(FRENCH), "Etats-Unis"); assertEquals(FR.computeName(ENGLISH), "France"); } @Test(groups = "fast") public void shouldEnforceEquality() { // Expect assertFalse(FR.equals(null)); assertTrue(FR.equals(FR)); assertFalse(FR.equals(new Object())); assertTrue(FR.equals(FR)); assertFalse(FR.equals(US)); } @Test(groups = "fast") public void shouldComputeHashCode() { // Expect assertEquals(FR.hashCode(), 2881); assertEquals(US.hashCode(), 3347); } @Test(groups = "fast") public void shouldOutputCountryCode() { // Expect
// Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public static String shortIdentityToString(Object obj) { // if (obj == null) { // return null; // } // return obj.getClass().getSimpleName() + '@' + toHexString(identityHashCode(obj)); // } // Path: src/test/java/org/killbill/billing/plugin/simpletax/internal/TestCountry.java import static java.util.Locale.ENGLISH; import static java.util.Locale.FRENCH; import static org.killbill.billing.test.helpers.TestUtil.shortIdentityToString; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; assertEquals(new Country(legalCountryCode).getCode(), legalCountryCode); } @Test(groups = "fast") public void shouldReturnLocalizedName() { // Expect assertEquals(US.computeName(FRENCH), "Etats-Unis"); assertEquals(FR.computeName(ENGLISH), "France"); } @Test(groups = "fast") public void shouldEnforceEquality() { // Expect assertFalse(FR.equals(null)); assertTrue(FR.equals(FR)); assertFalse(FR.equals(new Object())); assertTrue(FR.equals(FR)); assertFalse(FR.equals(US)); } @Test(groups = "fast") public void shouldComputeHashCode() { // Expect assertEquals(FR.hashCode(), 2881); assertEquals(US.hashCode(), 3347); } @Test(groups = "fast") public void shouldOutputCountryCode() { // Expect
assertEquals(FR.toString(), shortIdentityToString(FR) + "[code=FR]");
bgandon/killbill-simple-tax-plugin
src/test/java/org/killbill/billing/plugin/simpletax/util/TestImmutableCustomField.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ImmutableCustomField.java // public static Builder builder() { // return new Builder(); // } // // Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ImmutableCustomField.java // public static class Builder { // // private UUID id; // private DateTime createdDate, updatedDate; // private UUID objectId; // private ObjectType objectType; // private String fieldName, fieldValue; // // private Builder() { // super(); // id = randomUUID(); // createdDate = now(); // updatedDate = now(); // } // // private Builder(CustomField src) { // this(); // id = src.getId(); // createdDate = src.getCreatedDate(); // updatedDate = src.getUpdatedDate(); // objectId = src.getObjectId(); // objectType = src.getObjectType(); // fieldName = src.getFieldName(); // fieldValue = src.getFieldValue(); // } // // /** // * @return A new {@link ImmutableCustomField}, with the properties set // * in this builder. // */ // public CustomField build() { // ImmutableCustomField taxField = new ImmutableCustomField(); // taxField.id = id; // taxField.createdDate = createdDate; // taxField.updatedDate = updatedDate; // taxField.objectId = objectId; // taxField.objectType = objectType; // taxField.fieldName = fieldName; // taxField.fieldValue = fieldValue; // return taxField; // } // // /** // * @param objectId // * The object identifier to use. // * @return this builder // */ // public Builder withObjectId(UUID objectId) { // this.objectId = objectId; // updatedDate = now(); // return this; // } // // /** // * @param objectType // * The object type to use. // * @return this builder // */ // public Builder withObjectType(ObjectType objectType) { // this.objectType = objectType; // updatedDate = now(); // return this; // } // // /** // * @param fieldName // * The field name to use. // * @return this builder // */ // public Builder withFieldName(String fieldName) { // this.fieldName = fieldName; // updatedDate = now(); // return this; // } // // /** // * @param fieldValue // * The field value to use. // * @return this builder // */ // public Builder withFieldValue(String fieldValue) { // this.fieldValue = fieldValue; // updatedDate = now(); // return this; // } // }
import static java.lang.Thread.sleep; import static org.killbill.billing.ObjectType.INVOICE_ITEM; import static org.killbill.billing.plugin.simpletax.util.ImmutableCustomField.builder; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotSame; import java.util.UUID; import org.killbill.billing.plugin.simpletax.util.ImmutableCustomField.Builder; import org.killbill.billing.util.customfield.CustomField; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
/* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.util; /** * Tests for {@link ImmutableCustomField}. * * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class TestImmutableCustomField { private UUID someUUID;
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ImmutableCustomField.java // public static Builder builder() { // return new Builder(); // } // // Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ImmutableCustomField.java // public static class Builder { // // private UUID id; // private DateTime createdDate, updatedDate; // private UUID objectId; // private ObjectType objectType; // private String fieldName, fieldValue; // // private Builder() { // super(); // id = randomUUID(); // createdDate = now(); // updatedDate = now(); // } // // private Builder(CustomField src) { // this(); // id = src.getId(); // createdDate = src.getCreatedDate(); // updatedDate = src.getUpdatedDate(); // objectId = src.getObjectId(); // objectType = src.getObjectType(); // fieldName = src.getFieldName(); // fieldValue = src.getFieldValue(); // } // // /** // * @return A new {@link ImmutableCustomField}, with the properties set // * in this builder. // */ // public CustomField build() { // ImmutableCustomField taxField = new ImmutableCustomField(); // taxField.id = id; // taxField.createdDate = createdDate; // taxField.updatedDate = updatedDate; // taxField.objectId = objectId; // taxField.objectType = objectType; // taxField.fieldName = fieldName; // taxField.fieldValue = fieldValue; // return taxField; // } // // /** // * @param objectId // * The object identifier to use. // * @return this builder // */ // public Builder withObjectId(UUID objectId) { // this.objectId = objectId; // updatedDate = now(); // return this; // } // // /** // * @param objectType // * The object type to use. // * @return this builder // */ // public Builder withObjectType(ObjectType objectType) { // this.objectType = objectType; // updatedDate = now(); // return this; // } // // /** // * @param fieldName // * The field name to use. // * @return this builder // */ // public Builder withFieldName(String fieldName) { // this.fieldName = fieldName; // updatedDate = now(); // return this; // } // // /** // * @param fieldValue // * The field value to use. // * @return this builder // */ // public Builder withFieldValue(String fieldValue) { // this.fieldValue = fieldValue; // updatedDate = now(); // return this; // } // } // Path: src/test/java/org/killbill/billing/plugin/simpletax/util/TestImmutableCustomField.java import static java.lang.Thread.sleep; import static org.killbill.billing.ObjectType.INVOICE_ITEM; import static org.killbill.billing.plugin.simpletax.util.ImmutableCustomField.builder; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotSame; import java.util.UUID; import org.killbill.billing.plugin.simpletax.util.ImmutableCustomField.Builder; import org.killbill.billing.util.customfield.CustomField; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.util; /** * Tests for {@link ImmutableCustomField}. * * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class TestImmutableCustomField { private UUID someUUID;
private Builder builderA;
bgandon/killbill-simple-tax-plugin
src/test/java/org/killbill/billing/plugin/simpletax/util/TestImmutableCustomField.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ImmutableCustomField.java // public static Builder builder() { // return new Builder(); // } // // Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ImmutableCustomField.java // public static class Builder { // // private UUID id; // private DateTime createdDate, updatedDate; // private UUID objectId; // private ObjectType objectType; // private String fieldName, fieldValue; // // private Builder() { // super(); // id = randomUUID(); // createdDate = now(); // updatedDate = now(); // } // // private Builder(CustomField src) { // this(); // id = src.getId(); // createdDate = src.getCreatedDate(); // updatedDate = src.getUpdatedDate(); // objectId = src.getObjectId(); // objectType = src.getObjectType(); // fieldName = src.getFieldName(); // fieldValue = src.getFieldValue(); // } // // /** // * @return A new {@link ImmutableCustomField}, with the properties set // * in this builder. // */ // public CustomField build() { // ImmutableCustomField taxField = new ImmutableCustomField(); // taxField.id = id; // taxField.createdDate = createdDate; // taxField.updatedDate = updatedDate; // taxField.objectId = objectId; // taxField.objectType = objectType; // taxField.fieldName = fieldName; // taxField.fieldValue = fieldValue; // return taxField; // } // // /** // * @param objectId // * The object identifier to use. // * @return this builder // */ // public Builder withObjectId(UUID objectId) { // this.objectId = objectId; // updatedDate = now(); // return this; // } // // /** // * @param objectType // * The object type to use. // * @return this builder // */ // public Builder withObjectType(ObjectType objectType) { // this.objectType = objectType; // updatedDate = now(); // return this; // } // // /** // * @param fieldName // * The field name to use. // * @return this builder // */ // public Builder withFieldName(String fieldName) { // this.fieldName = fieldName; // updatedDate = now(); // return this; // } // // /** // * @param fieldValue // * The field value to use. // * @return this builder // */ // public Builder withFieldValue(String fieldValue) { // this.fieldValue = fieldValue; // updatedDate = now(); // return this; // } // }
import static java.lang.Thread.sleep; import static org.killbill.billing.ObjectType.INVOICE_ITEM; import static org.killbill.billing.plugin.simpletax.util.ImmutableCustomField.builder; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotSame; import java.util.UUID; import org.killbill.billing.plugin.simpletax.util.ImmutableCustomField.Builder; import org.killbill.billing.util.customfield.CustomField; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
/* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.util; /** * Tests for {@link ImmutableCustomField}. * * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class TestImmutableCustomField { private UUID someUUID; private Builder builderA; @BeforeMethod public void setup() { someUUID = UUID.randomUUID();
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ImmutableCustomField.java // public static Builder builder() { // return new Builder(); // } // // Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ImmutableCustomField.java // public static class Builder { // // private UUID id; // private DateTime createdDate, updatedDate; // private UUID objectId; // private ObjectType objectType; // private String fieldName, fieldValue; // // private Builder() { // super(); // id = randomUUID(); // createdDate = now(); // updatedDate = now(); // } // // private Builder(CustomField src) { // this(); // id = src.getId(); // createdDate = src.getCreatedDate(); // updatedDate = src.getUpdatedDate(); // objectId = src.getObjectId(); // objectType = src.getObjectType(); // fieldName = src.getFieldName(); // fieldValue = src.getFieldValue(); // } // // /** // * @return A new {@link ImmutableCustomField}, with the properties set // * in this builder. // */ // public CustomField build() { // ImmutableCustomField taxField = new ImmutableCustomField(); // taxField.id = id; // taxField.createdDate = createdDate; // taxField.updatedDate = updatedDate; // taxField.objectId = objectId; // taxField.objectType = objectType; // taxField.fieldName = fieldName; // taxField.fieldValue = fieldValue; // return taxField; // } // // /** // * @param objectId // * The object identifier to use. // * @return this builder // */ // public Builder withObjectId(UUID objectId) { // this.objectId = objectId; // updatedDate = now(); // return this; // } // // /** // * @param objectType // * The object type to use. // * @return this builder // */ // public Builder withObjectType(ObjectType objectType) { // this.objectType = objectType; // updatedDate = now(); // return this; // } // // /** // * @param fieldName // * The field name to use. // * @return this builder // */ // public Builder withFieldName(String fieldName) { // this.fieldName = fieldName; // updatedDate = now(); // return this; // } // // /** // * @param fieldValue // * The field value to use. // * @return this builder // */ // public Builder withFieldValue(String fieldValue) { // this.fieldValue = fieldValue; // updatedDate = now(); // return this; // } // } // Path: src/test/java/org/killbill/billing/plugin/simpletax/util/TestImmutableCustomField.java import static java.lang.Thread.sleep; import static org.killbill.billing.ObjectType.INVOICE_ITEM; import static org.killbill.billing.plugin.simpletax.util.ImmutableCustomField.builder; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotSame; import java.util.UUID; import org.killbill.billing.plugin.simpletax.util.ImmutableCustomField.Builder; import org.killbill.billing.util.customfield.CustomField; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.util; /** * Tests for {@link ImmutableCustomField}. * * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class TestImmutableCustomField { private UUID someUUID; private Builder builderA; @BeforeMethod public void setup() { someUUID = UUID.randomUUID();
builderA = builder()//
bgandon/killbill-simple-tax-plugin
src/main/java/org/killbill/billing/plugin/simpletax/config/http/TaxCountryController.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/config/http/CustomFieldService.java // public static final String TAX_COUNTRY_CUSTOM_FIELD_NAME = "taxCountry"; // // Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/Country.java // public class Country { // // private static final Supplier<Set<String>> COUNTRIES = new ConcurrentLazyValue<Set<String>>() { // @Override // protected Set<String> initialize() { // return ImmutableSet.copyOf(getISOCountries()); // } // }; // // private String code; // // /** // * Constructs a new country. The country code must be an element of // * {@link Locale#getISOCountries()}. // * // * @param code // * The ISO 3166-1 alpha-2 country code. // * @throws IllegalArgumentException // * when the country code is not an element of // * {@link Locale#getISOCountries()}. // */ // @JsonCreator // public Country(String code) throws IllegalArgumentException { // super(); // checkArgument(COUNTRIES.get().contains(code), "Illegal country code: [%s]", code); // this.code = code; // } // // /** // * Returns the ISO 3166-1 alpha-2 code for this country. // * // * @return The code of this country. Never {@code null}. // */ // @JsonValue // public String getCode() { // return code; // } // // /** // * Computes the name of this country, in the specified language, or in // * English if the language is not {@linkplain Locale#getAvailableLocales() // * supported}. // * // * @param language // * The preferred language in which the country name should be // * expressed. // * @return The name of the country in the specified language, or in English. // */ // public String computeName(Locale language) { // return new Locale("", code).getDisplayCountry(language); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Country rhs = (Country) obj; // return new EqualsBuilder().append(code, rhs.code).isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(code).toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this, SHORT_STYLE)// // .append("code", code)// // .toString(); // } // }
import org.killbill.billing.util.customfield.CustomField; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import static com.google.common.collect.Lists.newArrayList; import static org.killbill.billing.plugin.simpletax.config.http.CustomFieldService.TAX_COUNTRY_CUSTOM_FIELD_NAME; import static org.osgi.service.log.LogService.LOG_ERROR; import java.util.List; import java.util.UUID; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.killbill.billing.plugin.api.PluginTenantContext; import org.killbill.billing.plugin.simpletax.internal.Country; import org.killbill.billing.tenant.api.Tenant; import org.killbill.billing.util.callcontext.TenantContext;
/* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.config.http; /** * A controller that serves the end points related to Tax Countries. * * @author Benjamin Gandon */ public class TaxCountryController { private OSGIKillbillLogService logService; private CustomFieldService customFieldService; /** * Constructs a new controller for tax country end points. * * @param customFieldService * The service to use when accessing custom fields. * @param logService * The Kill Bill log service to use. */ public TaxCountryController(CustomFieldService customFieldService, OSGIKillbillLogService logService) { super(); this.logService = logService; this.customFieldService = customFieldService; } /** * Lists JSON resources for tax countries taking any restrictions into * account. * * @param accountId * Any account on which the tax countries should be restricted. * Might be {@code null}. * @param tenant * The tenant on which to operate. * @return A list of {@linkplain TaxCountryRsc account tax countries * resources}. Never {@code null}. */ // TODO: return a List<TaxCountryRsc> public Object listTaxCountries(@Nullable UUID accountId, Tenant tenant) { TenantContext tenantContext = new PluginTenantContext(tenant.getId()); List<CustomField> fields; if (accountId == null) {
// Path: src/main/java/org/killbill/billing/plugin/simpletax/config/http/CustomFieldService.java // public static final String TAX_COUNTRY_CUSTOM_FIELD_NAME = "taxCountry"; // // Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/Country.java // public class Country { // // private static final Supplier<Set<String>> COUNTRIES = new ConcurrentLazyValue<Set<String>>() { // @Override // protected Set<String> initialize() { // return ImmutableSet.copyOf(getISOCountries()); // } // }; // // private String code; // // /** // * Constructs a new country. The country code must be an element of // * {@link Locale#getISOCountries()}. // * // * @param code // * The ISO 3166-1 alpha-2 country code. // * @throws IllegalArgumentException // * when the country code is not an element of // * {@link Locale#getISOCountries()}. // */ // @JsonCreator // public Country(String code) throws IllegalArgumentException { // super(); // checkArgument(COUNTRIES.get().contains(code), "Illegal country code: [%s]", code); // this.code = code; // } // // /** // * Returns the ISO 3166-1 alpha-2 code for this country. // * // * @return The code of this country. Never {@code null}. // */ // @JsonValue // public String getCode() { // return code; // } // // /** // * Computes the name of this country, in the specified language, or in // * English if the language is not {@linkplain Locale#getAvailableLocales() // * supported}. // * // * @param language // * The preferred language in which the country name should be // * expressed. // * @return The name of the country in the specified language, or in English. // */ // public String computeName(Locale language) { // return new Locale("", code).getDisplayCountry(language); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Country rhs = (Country) obj; // return new EqualsBuilder().append(code, rhs.code).isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(code).toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this, SHORT_STYLE)// // .append("code", code)// // .toString(); // } // } // Path: src/main/java/org/killbill/billing/plugin/simpletax/config/http/TaxCountryController.java import org.killbill.billing.util.customfield.CustomField; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import static com.google.common.collect.Lists.newArrayList; import static org.killbill.billing.plugin.simpletax.config.http.CustomFieldService.TAX_COUNTRY_CUSTOM_FIELD_NAME; import static org.osgi.service.log.LogService.LOG_ERROR; import java.util.List; import java.util.UUID; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.killbill.billing.plugin.api.PluginTenantContext; import org.killbill.billing.plugin.simpletax.internal.Country; import org.killbill.billing.tenant.api.Tenant; import org.killbill.billing.util.callcontext.TenantContext; /* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.config.http; /** * A controller that serves the end points related to Tax Countries. * * @author Benjamin Gandon */ public class TaxCountryController { private OSGIKillbillLogService logService; private CustomFieldService customFieldService; /** * Constructs a new controller for tax country end points. * * @param customFieldService * The service to use when accessing custom fields. * @param logService * The Kill Bill log service to use. */ public TaxCountryController(CustomFieldService customFieldService, OSGIKillbillLogService logService) { super(); this.logService = logService; this.customFieldService = customFieldService; } /** * Lists JSON resources for tax countries taking any restrictions into * account. * * @param accountId * Any account on which the tax countries should be restricted. * Might be {@code null}. * @param tenant * The tenant on which to operate. * @return A list of {@linkplain TaxCountryRsc account tax countries * resources}. Never {@code null}. */ // TODO: return a List<TaxCountryRsc> public Object listTaxCountries(@Nullable UUID accountId, Tenant tenant) { TenantContext tenantContext = new PluginTenantContext(tenant.getId()); List<CustomField> fields; if (accountId == null) {
fields = customFieldService.findAllAccountFieldsByFieldNameAndTenant(TAX_COUNTRY_CUSTOM_FIELD_NAME,
bgandon/killbill-simple-tax-plugin
src/main/java/org/killbill/billing/plugin/simpletax/config/http/TaxCountryController.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/config/http/CustomFieldService.java // public static final String TAX_COUNTRY_CUSTOM_FIELD_NAME = "taxCountry"; // // Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/Country.java // public class Country { // // private static final Supplier<Set<String>> COUNTRIES = new ConcurrentLazyValue<Set<String>>() { // @Override // protected Set<String> initialize() { // return ImmutableSet.copyOf(getISOCountries()); // } // }; // // private String code; // // /** // * Constructs a new country. The country code must be an element of // * {@link Locale#getISOCountries()}. // * // * @param code // * The ISO 3166-1 alpha-2 country code. // * @throws IllegalArgumentException // * when the country code is not an element of // * {@link Locale#getISOCountries()}. // */ // @JsonCreator // public Country(String code) throws IllegalArgumentException { // super(); // checkArgument(COUNTRIES.get().contains(code), "Illegal country code: [%s]", code); // this.code = code; // } // // /** // * Returns the ISO 3166-1 alpha-2 code for this country. // * // * @return The code of this country. Never {@code null}. // */ // @JsonValue // public String getCode() { // return code; // } // // /** // * Computes the name of this country, in the specified language, or in // * English if the language is not {@linkplain Locale#getAvailableLocales() // * supported}. // * // * @param language // * The preferred language in which the country name should be // * expressed. // * @return The name of the country in the specified language, or in English. // */ // public String computeName(Locale language) { // return new Locale("", code).getDisplayCountry(language); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Country rhs = (Country) obj; // return new EqualsBuilder().append(code, rhs.code).isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(code).toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this, SHORT_STYLE)// // .append("code", code)// // .toString(); // } // }
import org.killbill.billing.util.customfield.CustomField; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import static com.google.common.collect.Lists.newArrayList; import static org.killbill.billing.plugin.simpletax.config.http.CustomFieldService.TAX_COUNTRY_CUSTOM_FIELD_NAME; import static org.osgi.service.log.LogService.LOG_ERROR; import java.util.List; import java.util.UUID; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.killbill.billing.plugin.api.PluginTenantContext; import org.killbill.billing.plugin.simpletax.internal.Country; import org.killbill.billing.tenant.api.Tenant; import org.killbill.billing.util.callcontext.TenantContext;
if (field == null) { return null; } return toTaxCountryJsonOrNull(accountId, field.getFieldValue()); } /** * Persists a new tax country value for a given account. * * @param accountId * An account the tax country of which should be modified. Must * not be {@code null}. * @param taxCountryRsc * A new tax country resource to persist. Must not be * {@code null}. * @param tenant * The tenant on which to operate. * @return {@code true} if the tax country is properly saved, or * {@code false} otherwise. * @throws NullPointerException * When {@code vatinRsc} is {@code null}. */ public boolean saveAccountTaxCountry(@Nonnull UUID accountId, @Nonnull TaxCountryRsc taxCountryRsc, Tenant tenant) { TenantContext tenantContext = new PluginTenantContext(tenant.getId()); String newValue = taxCountryRsc.taxCountry.getCode(); return customFieldService.saveAccountField(newValue, TAX_COUNTRY_CUSTOM_FIELD_NAME, accountId, tenantContext); } // TODO: rename to toTaxCountryRscOrNull private TaxCountryRsc toTaxCountryJsonOrNull(@Nonnull UUID accountId, @Nullable String country) {
// Path: src/main/java/org/killbill/billing/plugin/simpletax/config/http/CustomFieldService.java // public static final String TAX_COUNTRY_CUSTOM_FIELD_NAME = "taxCountry"; // // Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/Country.java // public class Country { // // private static final Supplier<Set<String>> COUNTRIES = new ConcurrentLazyValue<Set<String>>() { // @Override // protected Set<String> initialize() { // return ImmutableSet.copyOf(getISOCountries()); // } // }; // // private String code; // // /** // * Constructs a new country. The country code must be an element of // * {@link Locale#getISOCountries()}. // * // * @param code // * The ISO 3166-1 alpha-2 country code. // * @throws IllegalArgumentException // * when the country code is not an element of // * {@link Locale#getISOCountries()}. // */ // @JsonCreator // public Country(String code) throws IllegalArgumentException { // super(); // checkArgument(COUNTRIES.get().contains(code), "Illegal country code: [%s]", code); // this.code = code; // } // // /** // * Returns the ISO 3166-1 alpha-2 code for this country. // * // * @return The code of this country. Never {@code null}. // */ // @JsonValue // public String getCode() { // return code; // } // // /** // * Computes the name of this country, in the specified language, or in // * English if the language is not {@linkplain Locale#getAvailableLocales() // * supported}. // * // * @param language // * The preferred language in which the country name should be // * expressed. // * @return The name of the country in the specified language, or in English. // */ // public String computeName(Locale language) { // return new Locale("", code).getDisplayCountry(language); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // Country rhs = (Country) obj; // return new EqualsBuilder().append(code, rhs.code).isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(code).toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this, SHORT_STYLE)// // .append("code", code)// // .toString(); // } // } // Path: src/main/java/org/killbill/billing/plugin/simpletax/config/http/TaxCountryController.java import org.killbill.billing.util.customfield.CustomField; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import static com.google.common.collect.Lists.newArrayList; import static org.killbill.billing.plugin.simpletax.config.http.CustomFieldService.TAX_COUNTRY_CUSTOM_FIELD_NAME; import static org.osgi.service.log.LogService.LOG_ERROR; import java.util.List; import java.util.UUID; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.killbill.billing.plugin.api.PluginTenantContext; import org.killbill.billing.plugin.simpletax.internal.Country; import org.killbill.billing.tenant.api.Tenant; import org.killbill.billing.util.callcontext.TenantContext; if (field == null) { return null; } return toTaxCountryJsonOrNull(accountId, field.getFieldValue()); } /** * Persists a new tax country value for a given account. * * @param accountId * An account the tax country of which should be modified. Must * not be {@code null}. * @param taxCountryRsc * A new tax country resource to persist. Must not be * {@code null}. * @param tenant * The tenant on which to operate. * @return {@code true} if the tax country is properly saved, or * {@code false} otherwise. * @throws NullPointerException * When {@code vatinRsc} is {@code null}. */ public boolean saveAccountTaxCountry(@Nonnull UUID accountId, @Nonnull TaxCountryRsc taxCountryRsc, Tenant tenant) { TenantContext tenantContext = new PluginTenantContext(tenant.getId()); String newValue = taxCountryRsc.taxCountry.getCode(); return customFieldService.saveAccountField(newValue, TAX_COUNTRY_CUSTOM_FIELD_NAME, accountId, tenantContext); } // TODO: rename to toTaxCountryRscOrNull private TaxCountryRsc toTaxCountryJsonOrNull(@Nonnull UUID accountId, @Nullable String country) {
Country taxCountry;
bgandon/killbill-simple-tax-plugin
src/test/java/org/killbill/billing/plugin/simpletax/internal/TestTaxCode.java
// Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public static String shortIdentityToString(Object obj) { // if (obj == null) { // return null; // } // return obj.getClass().getSimpleName() + '@' + toHexString(identityHashCode(obj)); // } // // Path: src/test/java/org/killbill/billing/test/helpers/TaxCodeBuilder.java // @SuppressWarnings("javadoc") // public class TaxCodeBuilder implements Builder<TaxCode> { // // private String name; // private String taxItemDescription; // private BigDecimal rate; // private LocalDate startingOn; // private LocalDate stoppingOn; // private Country country; // // @Override // public TaxCode build() { // return new TaxCode(name, taxItemDescription, rate, startingOn, stoppingOn, country); // } // // public TaxCodeBuilder withName(String name) { // this.name = name; // return this; // } // // public TaxCodeBuilder withTaxItemDescription(String taxItemDescription) { // this.taxItemDescription = taxItemDescription; // return this; // } // // public TaxCodeBuilder withRate(BigDecimal rate) { // this.rate = rate; // return this; // } // // public TaxCodeBuilder withStartingOn(LocalDate startingOn) { // this.startingOn = startingOn; // return this; // } // // public TaxCodeBuilder withStoppingOn(LocalDate stoppingOn) { // this.stoppingOn = stoppingOn; // return this; // } // // public TaxCodeBuilder withCountry(Country country) { // this.country = country; // return this; // } // // } // // Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public final class TestUtil { // private TestUtil() { // } // // /** // * Helper assert that ignores {@linkplain BigDecimal#scale() scales}. // * // * @param actual // * the actual value // * @param expected // * the expected value // */ // public static void assertEqualsIgnoreScale(BigDecimal actual, BigDecimal expected) { // assertTrue(expected.compareTo(actual) == 0); // } // // /** // * An {@link org.apache.commons.lang3.ObjectUtils#identityToString(Object) // * identityToString()} variant with short class name. // * // * @param obj // * The object to create a toString for, may be {@code null}. // * @return The default toString text, or {@code null} if {@code null} passed // * in. // * @see org.apache.commons.lang3.ObjectUtils#identityToString(Object) // */ // public static String shortIdentityToString(Object obj) { // if (obj == null) { // return null; // } // return obj.getClass().getSimpleName() + '@' + toHexString(identityHashCode(obj)); // } // }
import static java.math.BigDecimal.ZERO; import static org.killbill.billing.test.helpers.TestUtil.shortIdentityToString; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.math.BigDecimal; import org.joda.time.LocalDate; import org.killbill.billing.test.helpers.TaxCodeBuilder; import org.killbill.billing.test.helpers.TestUtil; import org.testng.annotations.Test;
/* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.internal; /** * Tests for {@link TaxCode}. * * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class TestTaxCode { private final LocalDate today = new LocalDate("2015-10-26"); private final LocalDate yesterday = today.minusDays(1);
// Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public static String shortIdentityToString(Object obj) { // if (obj == null) { // return null; // } // return obj.getClass().getSimpleName() + '@' + toHexString(identityHashCode(obj)); // } // // Path: src/test/java/org/killbill/billing/test/helpers/TaxCodeBuilder.java // @SuppressWarnings("javadoc") // public class TaxCodeBuilder implements Builder<TaxCode> { // // private String name; // private String taxItemDescription; // private BigDecimal rate; // private LocalDate startingOn; // private LocalDate stoppingOn; // private Country country; // // @Override // public TaxCode build() { // return new TaxCode(name, taxItemDescription, rate, startingOn, stoppingOn, country); // } // // public TaxCodeBuilder withName(String name) { // this.name = name; // return this; // } // // public TaxCodeBuilder withTaxItemDescription(String taxItemDescription) { // this.taxItemDescription = taxItemDescription; // return this; // } // // public TaxCodeBuilder withRate(BigDecimal rate) { // this.rate = rate; // return this; // } // // public TaxCodeBuilder withStartingOn(LocalDate startingOn) { // this.startingOn = startingOn; // return this; // } // // public TaxCodeBuilder withStoppingOn(LocalDate stoppingOn) { // this.stoppingOn = stoppingOn; // return this; // } // // public TaxCodeBuilder withCountry(Country country) { // this.country = country; // return this; // } // // } // // Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public final class TestUtil { // private TestUtil() { // } // // /** // * Helper assert that ignores {@linkplain BigDecimal#scale() scales}. // * // * @param actual // * the actual value // * @param expected // * the expected value // */ // public static void assertEqualsIgnoreScale(BigDecimal actual, BigDecimal expected) { // assertTrue(expected.compareTo(actual) == 0); // } // // /** // * An {@link org.apache.commons.lang3.ObjectUtils#identityToString(Object) // * identityToString()} variant with short class name. // * // * @param obj // * The object to create a toString for, may be {@code null}. // * @return The default toString text, or {@code null} if {@code null} passed // * in. // * @see org.apache.commons.lang3.ObjectUtils#identityToString(Object) // */ // public static String shortIdentityToString(Object obj) { // if (obj == null) { // return null; // } // return obj.getClass().getSimpleName() + '@' + toHexString(identityHashCode(obj)); // } // } // Path: src/test/java/org/killbill/billing/plugin/simpletax/internal/TestTaxCode.java import static java.math.BigDecimal.ZERO; import static org.killbill.billing.test.helpers.TestUtil.shortIdentityToString; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.math.BigDecimal; import org.joda.time.LocalDate; import org.killbill.billing.test.helpers.TaxCodeBuilder; import org.killbill.billing.test.helpers.TestUtil; import org.testng.annotations.Test; /* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.internal; /** * Tests for {@link TaxCode}. * * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class TestTaxCode { private final LocalDate today = new LocalDate("2015-10-26"); private final LocalDate yesterday = today.minusDays(1);
private TaxCode taxTT = new TaxCodeBuilder()//
bgandon/killbill-simple-tax-plugin
src/test/java/org/killbill/billing/plugin/simpletax/internal/TestTaxCode.java
// Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public static String shortIdentityToString(Object obj) { // if (obj == null) { // return null; // } // return obj.getClass().getSimpleName() + '@' + toHexString(identityHashCode(obj)); // } // // Path: src/test/java/org/killbill/billing/test/helpers/TaxCodeBuilder.java // @SuppressWarnings("javadoc") // public class TaxCodeBuilder implements Builder<TaxCode> { // // private String name; // private String taxItemDescription; // private BigDecimal rate; // private LocalDate startingOn; // private LocalDate stoppingOn; // private Country country; // // @Override // public TaxCode build() { // return new TaxCode(name, taxItemDescription, rate, startingOn, stoppingOn, country); // } // // public TaxCodeBuilder withName(String name) { // this.name = name; // return this; // } // // public TaxCodeBuilder withTaxItemDescription(String taxItemDescription) { // this.taxItemDescription = taxItemDescription; // return this; // } // // public TaxCodeBuilder withRate(BigDecimal rate) { // this.rate = rate; // return this; // } // // public TaxCodeBuilder withStartingOn(LocalDate startingOn) { // this.startingOn = startingOn; // return this; // } // // public TaxCodeBuilder withStoppingOn(LocalDate stoppingOn) { // this.stoppingOn = stoppingOn; // return this; // } // // public TaxCodeBuilder withCountry(Country country) { // this.country = country; // return this; // } // // } // // Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public final class TestUtil { // private TestUtil() { // } // // /** // * Helper assert that ignores {@linkplain BigDecimal#scale() scales}. // * // * @param actual // * the actual value // * @param expected // * the expected value // */ // public static void assertEqualsIgnoreScale(BigDecimal actual, BigDecimal expected) { // assertTrue(expected.compareTo(actual) == 0); // } // // /** // * An {@link org.apache.commons.lang3.ObjectUtils#identityToString(Object) // * identityToString()} variant with short class name. // * // * @param obj // * The object to create a toString for, may be {@code null}. // * @return The default toString text, or {@code null} if {@code null} passed // * in. // * @see org.apache.commons.lang3.ObjectUtils#identityToString(Object) // */ // public static String shortIdentityToString(Object obj) { // if (obj == null) { // return null; // } // return obj.getClass().getSimpleName() + '@' + toHexString(identityHashCode(obj)); // } // }
import static java.math.BigDecimal.ZERO; import static org.killbill.billing.test.helpers.TestUtil.shortIdentityToString; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.math.BigDecimal; import org.joda.time.LocalDate; import org.killbill.billing.test.helpers.TaxCodeBuilder; import org.killbill.billing.test.helpers.TestUtil; import org.testng.annotations.Test;
assertFalse(taxA.equals(taxCdesc)); assertFalse(taxA.equals(taxCstart)); assertFalse(taxA.equals(taxCstop)); } @Test(groups = "fast") public void shouldBeEqualIgnoringScale() { // Given TaxCode taxD1 = new TaxCodeBuilder().withRate(new BigDecimal("0.1")).build(); TaxCode taxD2 = new TaxCodeBuilder().withRate(new BigDecimal("0.100")).build(); TaxCode taxE = new TaxCodeBuilder().withRate(new BigDecimal("0.2")).build(); // Expect assertTrue(taxD1.equals(taxD2)); assertTrue(taxD2.equals(taxD1)); assertFalse(taxD1.equals(taxE)); assertFalse(taxD2.equals(taxE)); assertFalse(taxE.equals(taxD1)); assertFalse(taxE.equals(taxD2)); } @Test(groups = "fast") public void shouldComputeHashCode() { // Expect assertEquals(taxTT.hashCode(), -1190345958); } @Test(groups = "fast") public void shouldPrintFields() { // Expect
// Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public static String shortIdentityToString(Object obj) { // if (obj == null) { // return null; // } // return obj.getClass().getSimpleName() + '@' + toHexString(identityHashCode(obj)); // } // // Path: src/test/java/org/killbill/billing/test/helpers/TaxCodeBuilder.java // @SuppressWarnings("javadoc") // public class TaxCodeBuilder implements Builder<TaxCode> { // // private String name; // private String taxItemDescription; // private BigDecimal rate; // private LocalDate startingOn; // private LocalDate stoppingOn; // private Country country; // // @Override // public TaxCode build() { // return new TaxCode(name, taxItemDescription, rate, startingOn, stoppingOn, country); // } // // public TaxCodeBuilder withName(String name) { // this.name = name; // return this; // } // // public TaxCodeBuilder withTaxItemDescription(String taxItemDescription) { // this.taxItemDescription = taxItemDescription; // return this; // } // // public TaxCodeBuilder withRate(BigDecimal rate) { // this.rate = rate; // return this; // } // // public TaxCodeBuilder withStartingOn(LocalDate startingOn) { // this.startingOn = startingOn; // return this; // } // // public TaxCodeBuilder withStoppingOn(LocalDate stoppingOn) { // this.stoppingOn = stoppingOn; // return this; // } // // public TaxCodeBuilder withCountry(Country country) { // this.country = country; // return this; // } // // } // // Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public final class TestUtil { // private TestUtil() { // } // // /** // * Helper assert that ignores {@linkplain BigDecimal#scale() scales}. // * // * @param actual // * the actual value // * @param expected // * the expected value // */ // public static void assertEqualsIgnoreScale(BigDecimal actual, BigDecimal expected) { // assertTrue(expected.compareTo(actual) == 0); // } // // /** // * An {@link org.apache.commons.lang3.ObjectUtils#identityToString(Object) // * identityToString()} variant with short class name. // * // * @param obj // * The object to create a toString for, may be {@code null}. // * @return The default toString text, or {@code null} if {@code null} passed // * in. // * @see org.apache.commons.lang3.ObjectUtils#identityToString(Object) // */ // public static String shortIdentityToString(Object obj) { // if (obj == null) { // return null; // } // return obj.getClass().getSimpleName() + '@' + toHexString(identityHashCode(obj)); // } // } // Path: src/test/java/org/killbill/billing/plugin/simpletax/internal/TestTaxCode.java import static java.math.BigDecimal.ZERO; import static org.killbill.billing.test.helpers.TestUtil.shortIdentityToString; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.math.BigDecimal; import org.joda.time.LocalDate; import org.killbill.billing.test.helpers.TaxCodeBuilder; import org.killbill.billing.test.helpers.TestUtil; import org.testng.annotations.Test; assertFalse(taxA.equals(taxCdesc)); assertFalse(taxA.equals(taxCstart)); assertFalse(taxA.equals(taxCstop)); } @Test(groups = "fast") public void shouldBeEqualIgnoringScale() { // Given TaxCode taxD1 = new TaxCodeBuilder().withRate(new BigDecimal("0.1")).build(); TaxCode taxD2 = new TaxCodeBuilder().withRate(new BigDecimal("0.100")).build(); TaxCode taxE = new TaxCodeBuilder().withRate(new BigDecimal("0.2")).build(); // Expect assertTrue(taxD1.equals(taxD2)); assertTrue(taxD2.equals(taxD1)); assertFalse(taxD1.equals(taxE)); assertFalse(taxD2.equals(taxE)); assertFalse(taxE.equals(taxD1)); assertFalse(taxE.equals(taxD2)); } @Test(groups = "fast") public void shouldComputeHashCode() { // Expect assertEquals(taxTT.hashCode(), -1190345958); } @Test(groups = "fast") public void shouldPrintFields() { // Expect
String shortIdentityToString = shortIdentityToString(taxTT);
bgandon/killbill-simple-tax-plugin
src/test/java/org/killbill/billing/plugin/simpletax/internal/TestTaxCode.java
// Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public static String shortIdentityToString(Object obj) { // if (obj == null) { // return null; // } // return obj.getClass().getSimpleName() + '@' + toHexString(identityHashCode(obj)); // } // // Path: src/test/java/org/killbill/billing/test/helpers/TaxCodeBuilder.java // @SuppressWarnings("javadoc") // public class TaxCodeBuilder implements Builder<TaxCode> { // // private String name; // private String taxItemDescription; // private BigDecimal rate; // private LocalDate startingOn; // private LocalDate stoppingOn; // private Country country; // // @Override // public TaxCode build() { // return new TaxCode(name, taxItemDescription, rate, startingOn, stoppingOn, country); // } // // public TaxCodeBuilder withName(String name) { // this.name = name; // return this; // } // // public TaxCodeBuilder withTaxItemDescription(String taxItemDescription) { // this.taxItemDescription = taxItemDescription; // return this; // } // // public TaxCodeBuilder withRate(BigDecimal rate) { // this.rate = rate; // return this; // } // // public TaxCodeBuilder withStartingOn(LocalDate startingOn) { // this.startingOn = startingOn; // return this; // } // // public TaxCodeBuilder withStoppingOn(LocalDate stoppingOn) { // this.stoppingOn = stoppingOn; // return this; // } // // public TaxCodeBuilder withCountry(Country country) { // this.country = country; // return this; // } // // } // // Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public final class TestUtil { // private TestUtil() { // } // // /** // * Helper assert that ignores {@linkplain BigDecimal#scale() scales}. // * // * @param actual // * the actual value // * @param expected // * the expected value // */ // public static void assertEqualsIgnoreScale(BigDecimal actual, BigDecimal expected) { // assertTrue(expected.compareTo(actual) == 0); // } // // /** // * An {@link org.apache.commons.lang3.ObjectUtils#identityToString(Object) // * identityToString()} variant with short class name. // * // * @param obj // * The object to create a toString for, may be {@code null}. // * @return The default toString text, or {@code null} if {@code null} passed // * in. // * @see org.apache.commons.lang3.ObjectUtils#identityToString(Object) // */ // public static String shortIdentityToString(Object obj) { // if (obj == null) { // return null; // } // return obj.getClass().getSimpleName() + '@' + toHexString(identityHashCode(obj)); // } // }
import static java.math.BigDecimal.ZERO; import static org.killbill.billing.test.helpers.TestUtil.shortIdentityToString; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.math.BigDecimal; import org.joda.time.LocalDate; import org.killbill.billing.test.helpers.TaxCodeBuilder; import org.killbill.billing.test.helpers.TestUtil; import org.testng.annotations.Test;
public void shouldBeEqualIgnoringScale() { // Given TaxCode taxD1 = new TaxCodeBuilder().withRate(new BigDecimal("0.1")).build(); TaxCode taxD2 = new TaxCodeBuilder().withRate(new BigDecimal("0.100")).build(); TaxCode taxE = new TaxCodeBuilder().withRate(new BigDecimal("0.2")).build(); // Expect assertTrue(taxD1.equals(taxD2)); assertTrue(taxD2.equals(taxD1)); assertFalse(taxD1.equals(taxE)); assertFalse(taxD2.equals(taxE)); assertFalse(taxE.equals(taxD1)); assertFalse(taxE.equals(taxD2)); } @Test(groups = "fast") public void shouldComputeHashCode() { // Expect assertEquals(taxTT.hashCode(), -1190345958); } @Test(groups = "fast") public void shouldPrintFields() { // Expect String shortIdentityToString = shortIdentityToString(taxTT); assertEquals(taxTT.toString(), shortIdentityToString + "[name=toto,"// + "taxItemDescription=titi,"// + "rate=0.06713,"// + "startingOn=2015-10-25,"// + "stoppingOn=2015-10-26,"//
// Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public static String shortIdentityToString(Object obj) { // if (obj == null) { // return null; // } // return obj.getClass().getSimpleName() + '@' + toHexString(identityHashCode(obj)); // } // // Path: src/test/java/org/killbill/billing/test/helpers/TaxCodeBuilder.java // @SuppressWarnings("javadoc") // public class TaxCodeBuilder implements Builder<TaxCode> { // // private String name; // private String taxItemDescription; // private BigDecimal rate; // private LocalDate startingOn; // private LocalDate stoppingOn; // private Country country; // // @Override // public TaxCode build() { // return new TaxCode(name, taxItemDescription, rate, startingOn, stoppingOn, country); // } // // public TaxCodeBuilder withName(String name) { // this.name = name; // return this; // } // // public TaxCodeBuilder withTaxItemDescription(String taxItemDescription) { // this.taxItemDescription = taxItemDescription; // return this; // } // // public TaxCodeBuilder withRate(BigDecimal rate) { // this.rate = rate; // return this; // } // // public TaxCodeBuilder withStartingOn(LocalDate startingOn) { // this.startingOn = startingOn; // return this; // } // // public TaxCodeBuilder withStoppingOn(LocalDate stoppingOn) { // this.stoppingOn = stoppingOn; // return this; // } // // public TaxCodeBuilder withCountry(Country country) { // this.country = country; // return this; // } // // } // // Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public final class TestUtil { // private TestUtil() { // } // // /** // * Helper assert that ignores {@linkplain BigDecimal#scale() scales}. // * // * @param actual // * the actual value // * @param expected // * the expected value // */ // public static void assertEqualsIgnoreScale(BigDecimal actual, BigDecimal expected) { // assertTrue(expected.compareTo(actual) == 0); // } // // /** // * An {@link org.apache.commons.lang3.ObjectUtils#identityToString(Object) // * identityToString()} variant with short class name. // * // * @param obj // * The object to create a toString for, may be {@code null}. // * @return The default toString text, or {@code null} if {@code null} passed // * in. // * @see org.apache.commons.lang3.ObjectUtils#identityToString(Object) // */ // public static String shortIdentityToString(Object obj) { // if (obj == null) { // return null; // } // return obj.getClass().getSimpleName() + '@' + toHexString(identityHashCode(obj)); // } // } // Path: src/test/java/org/killbill/billing/plugin/simpletax/internal/TestTaxCode.java import static java.math.BigDecimal.ZERO; import static org.killbill.billing.test.helpers.TestUtil.shortIdentityToString; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.math.BigDecimal; import org.joda.time.LocalDate; import org.killbill.billing.test.helpers.TaxCodeBuilder; import org.killbill.billing.test.helpers.TestUtil; import org.testng.annotations.Test; public void shouldBeEqualIgnoringScale() { // Given TaxCode taxD1 = new TaxCodeBuilder().withRate(new BigDecimal("0.1")).build(); TaxCode taxD2 = new TaxCodeBuilder().withRate(new BigDecimal("0.100")).build(); TaxCode taxE = new TaxCodeBuilder().withRate(new BigDecimal("0.2")).build(); // Expect assertTrue(taxD1.equals(taxD2)); assertTrue(taxD2.equals(taxD1)); assertFalse(taxD1.equals(taxE)); assertFalse(taxD2.equals(taxE)); assertFalse(taxE.equals(taxD1)); assertFalse(taxE.equals(taxD2)); } @Test(groups = "fast") public void shouldComputeHashCode() { // Expect assertEquals(taxTT.hashCode(), -1190345958); } @Test(groups = "fast") public void shouldPrintFields() { // Expect String shortIdentityToString = shortIdentityToString(taxTT); assertEquals(taxTT.toString(), shortIdentityToString + "[name=toto,"// + "taxItemDescription=titi,"// + "rate=0.06713,"// + "startingOn=2015-10-25,"// + "stoppingOn=2015-10-26,"//
+ "country=" + TestUtil.shortIdentityToString(taxTT.getCountry()) + "[code=FR]]");
bgandon/killbill-simple-tax-plugin
src/test/java/org/killbill/billing/plugin/simpletax/resolving/fixtures/ThrowingTaxResolver.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/TaxComputationContext.java // public class TaxComputationContext { // // private SimpleTaxConfig config; // // private Account account; // private Country accountTaxCountry; // // private Set<Invoice> allInvoices; // // private Function<InvoiceItem, BigDecimal> toAdjustedAmount; // // private Ordering<InvoiceItem> byAdjustedAmount; // // private TaxCodeService taxCodeService; // // /** // * Constructs an immutable holder for pre-comuted data. // * // * @param config // * The plugin configuration. // * @param account // * The account that the newly created invoice relates to. // * @param accountTaxCountry // * The tax country for the given account. // * @param allInvoices // * The set of all invoices for the given account. // * @param toAdjustedAmount // * A function that computes adjusted amounts for the listed // * invoices of the given account. // * @param byAdjustedAmount // * An ordering that orders {@link InvoiceItem}s by adjusted // * amount. // * @param taxCodeService // * The tax code service to use. // */ // public TaxComputationContext(SimpleTaxConfig config, Account account, Country accountTaxCountry, // Set<Invoice> allInvoices, Function<InvoiceItem, BigDecimal> toAdjustedAmount, // Ordering<InvoiceItem> byAdjustedAmount, TaxCodeService taxCodeService) { // super(); // this.config = config; // this.account = account; // this.accountTaxCountry = accountTaxCountry; // this.allInvoices = allInvoices; // this.toAdjustedAmount = toAdjustedAmount; // this.byAdjustedAmount = byAdjustedAmount; // this.taxCodeService = taxCodeService; // } // // /** // * @return The plugin configuration. // */ // public SimpleTaxConfig getConfig() { // return config; // } // // /** // * @return The account that the newly created invoice relates to. // */ // public Account getAccount() { // return account; // } // // /** // * @return The tax country for the {@linkplain #getAccount() given account}. // */ // public Country getAccountTaxCountry() { // return accountTaxCountry; // } // // /** // * @return The set of all invoices for the {@linkplain #getAccount() given // * account}. // */ // public Set<Invoice> getAllInvoices() { // return allInvoices; // } // // /** // * @return A function that computes adjusted amounts for the // * {@linkplain #getAllInvoices() set of invoices} of the // * {@linkplain #getAccount() given account}. // */ // public Function<InvoiceItem, BigDecimal> toAdjustedAmount() { // return toAdjustedAmount; // } // // /** // * @return An ordering that orders {@link InvoiceItem}s by adjusted amount. // */ // public Ordering<InvoiceItem> byAdjustedAmount() { // return byAdjustedAmount; // } // // /** // * @return The applicable resolver for tax codes. // */ // public TaxCodeService getTaxCodeService() { // return taxCodeService; // } // }
import org.killbill.billing.plugin.simpletax.TaxComputationContext;
/* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.resolving.fixtures; /** * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class ThrowingTaxResolver extends AbstractTaxResolver {
// Path: src/main/java/org/killbill/billing/plugin/simpletax/TaxComputationContext.java // public class TaxComputationContext { // // private SimpleTaxConfig config; // // private Account account; // private Country accountTaxCountry; // // private Set<Invoice> allInvoices; // // private Function<InvoiceItem, BigDecimal> toAdjustedAmount; // // private Ordering<InvoiceItem> byAdjustedAmount; // // private TaxCodeService taxCodeService; // // /** // * Constructs an immutable holder for pre-comuted data. // * // * @param config // * The plugin configuration. // * @param account // * The account that the newly created invoice relates to. // * @param accountTaxCountry // * The tax country for the given account. // * @param allInvoices // * The set of all invoices for the given account. // * @param toAdjustedAmount // * A function that computes adjusted amounts for the listed // * invoices of the given account. // * @param byAdjustedAmount // * An ordering that orders {@link InvoiceItem}s by adjusted // * amount. // * @param taxCodeService // * The tax code service to use. // */ // public TaxComputationContext(SimpleTaxConfig config, Account account, Country accountTaxCountry, // Set<Invoice> allInvoices, Function<InvoiceItem, BigDecimal> toAdjustedAmount, // Ordering<InvoiceItem> byAdjustedAmount, TaxCodeService taxCodeService) { // super(); // this.config = config; // this.account = account; // this.accountTaxCountry = accountTaxCountry; // this.allInvoices = allInvoices; // this.toAdjustedAmount = toAdjustedAmount; // this.byAdjustedAmount = byAdjustedAmount; // this.taxCodeService = taxCodeService; // } // // /** // * @return The plugin configuration. // */ // public SimpleTaxConfig getConfig() { // return config; // } // // /** // * @return The account that the newly created invoice relates to. // */ // public Account getAccount() { // return account; // } // // /** // * @return The tax country for the {@linkplain #getAccount() given account}. // */ // public Country getAccountTaxCountry() { // return accountTaxCountry; // } // // /** // * @return The set of all invoices for the {@linkplain #getAccount() given // * account}. // */ // public Set<Invoice> getAllInvoices() { // return allInvoices; // } // // /** // * @return A function that computes adjusted amounts for the // * {@linkplain #getAllInvoices() set of invoices} of the // * {@linkplain #getAccount() given account}. // */ // public Function<InvoiceItem, BigDecimal> toAdjustedAmount() { // return toAdjustedAmount; // } // // /** // * @return An ordering that orders {@link InvoiceItem}s by adjusted amount. // */ // public Ordering<InvoiceItem> byAdjustedAmount() { // return byAdjustedAmount; // } // // /** // * @return The applicable resolver for tax codes. // */ // public TaxCodeService getTaxCodeService() { // return taxCodeService; // } // } // Path: src/test/java/org/killbill/billing/plugin/simpletax/resolving/fixtures/ThrowingTaxResolver.java import org.killbill.billing.plugin.simpletax.TaxComputationContext; /* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.resolving.fixtures; /** * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class ThrowingTaxResolver extends AbstractTaxResolver {
public ThrowingTaxResolver(TaxComputationContext ctx) {
bgandon/killbill-simple-tax-plugin
src/test/java/org/killbill/billing/plugin/simpletax/config/http/TestCustomFieldService.java
// Path: src/test/java/org/killbill/billing/test/helpers/CustomFieldBuilder.java // public static CustomFieldBuilder copy(CustomFieldBuilder that) { // return new CustomFieldBuilder()// // .withObjectType(that.objectType)// // .withObjectId(that.objectId)// // .withFieldName(that.fieldName)// // .withFieldValue(that.fieldValue); // } // // Path: src/test/java/org/killbill/billing/test/helpers/CustomFieldBuilder.java // @SuppressWarnings("javadoc") // public class CustomFieldBuilder implements Builder<CustomField> { // // private UUID objectId; // private ObjectType objectType; // private String fieldName, fieldValue; // // @Override // public CustomField build() { // return ImmutableCustomField.builder()// // .withObjectId(objectId)// // .withObjectType(objectType)// // .withFieldName(fieldName)// // .withFieldValue(fieldValue)// // .build(); // } // // public static CustomFieldBuilder copy(CustomFieldBuilder that) { // return new CustomFieldBuilder()// // .withObjectType(that.objectType)// // .withObjectId(that.objectId)// // .withFieldName(that.fieldName)// // .withFieldValue(that.fieldValue); // } // // public CustomFieldBuilder withObjectId(UUID objectId) { // this.objectId = objectId; // return this; // } // // public CustomFieldBuilder withObjectType(ObjectType objectType) { // this.objectType = objectType; // return this; // } // // public CustomFieldBuilder withFieldName(String fieldName) { // this.fieldName = fieldName; // return this; // } // // public CustomFieldBuilder withFieldValue(String fieldValue) { // this.fieldValue = fieldValue; // return this; // } // }
import static com.google.common.collect.Iterators.forArray; import static com.google.common.collect.Lists.newArrayList; import static java.util.UUID.randomUUID; import static org.apache.commons.lang3.StringUtils.contains; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; import static org.killbill.billing.ErrorCode.UNEXPECTED_ERROR; import static org.killbill.billing.ObjectType.ACCOUNT; import static org.killbill.billing.ObjectType.INVOICE; import static org.killbill.billing.test.helpers.CustomFieldBuilder.copy; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyListOf; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.osgi.service.log.LogService.LOG_ERROR; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.UUID; import org.killbill.billing.ObjectType; import org.killbill.billing.test.helpers.CustomFieldBuilder; import org.killbill.billing.util.api.CustomFieldApiException; import org.killbill.billing.util.api.CustomFieldUserApi; import org.killbill.billing.util.callcontext.CallContext; import org.killbill.billing.util.callcontext.TenantContext; import org.killbill.billing.util.customfield.CustomField; import org.killbill.billing.util.entity.Pagination; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.Lists;
private ArgumentCaptor<List<CustomField>> addedFields; @Captor private ArgumentCaptor<List<CustomField>> removedFields; @Mock private TenantContext defaultTenant; @Mock private Pagination<CustomField> pageStart; @Mock private Pagination<CustomField> pageMiddle; @Mock private Pagination<CustomField> pageEnd; @BeforeClass public void init() { initMocks(this); } private void withThreePagesOfSearchResults(TenantContext tenantContext) { when(customFieldApi.searchCustomFields(anyString(), eq(0L), eq(PAGE_SIZE), eq(tenantContext)))// .thenReturn(pageStart); when(customFieldApi.searchCustomFields(anyString(), eq(PAGE_SIZE), eq(PAGE_SIZE), eq(tenantContext)))// .thenReturn(pageMiddle); when(customFieldApi.searchCustomFields(anyString(), eq(2 * PAGE_SIZE), eq(PAGE_SIZE), eq(tenantContext)))// .thenReturn(pageEnd); when(pageStart.getNextOffset()).thenReturn(PAGE_SIZE); when(pageMiddle.getNextOffset()).thenReturn(2 * PAGE_SIZE); when(pageEnd.getNextOffset()).thenReturn(null);
// Path: src/test/java/org/killbill/billing/test/helpers/CustomFieldBuilder.java // public static CustomFieldBuilder copy(CustomFieldBuilder that) { // return new CustomFieldBuilder()// // .withObjectType(that.objectType)// // .withObjectId(that.objectId)// // .withFieldName(that.fieldName)// // .withFieldValue(that.fieldValue); // } // // Path: src/test/java/org/killbill/billing/test/helpers/CustomFieldBuilder.java // @SuppressWarnings("javadoc") // public class CustomFieldBuilder implements Builder<CustomField> { // // private UUID objectId; // private ObjectType objectType; // private String fieldName, fieldValue; // // @Override // public CustomField build() { // return ImmutableCustomField.builder()// // .withObjectId(objectId)// // .withObjectType(objectType)// // .withFieldName(fieldName)// // .withFieldValue(fieldValue)// // .build(); // } // // public static CustomFieldBuilder copy(CustomFieldBuilder that) { // return new CustomFieldBuilder()// // .withObjectType(that.objectType)// // .withObjectId(that.objectId)// // .withFieldName(that.fieldName)// // .withFieldValue(that.fieldValue); // } // // public CustomFieldBuilder withObjectId(UUID objectId) { // this.objectId = objectId; // return this; // } // // public CustomFieldBuilder withObjectType(ObjectType objectType) { // this.objectType = objectType; // return this; // } // // public CustomFieldBuilder withFieldName(String fieldName) { // this.fieldName = fieldName; // return this; // } // // public CustomFieldBuilder withFieldValue(String fieldValue) { // this.fieldValue = fieldValue; // return this; // } // } // Path: src/test/java/org/killbill/billing/plugin/simpletax/config/http/TestCustomFieldService.java import static com.google.common.collect.Iterators.forArray; import static com.google.common.collect.Lists.newArrayList; import static java.util.UUID.randomUUID; import static org.apache.commons.lang3.StringUtils.contains; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; import static org.killbill.billing.ErrorCode.UNEXPECTED_ERROR; import static org.killbill.billing.ObjectType.ACCOUNT; import static org.killbill.billing.ObjectType.INVOICE; import static org.killbill.billing.test.helpers.CustomFieldBuilder.copy; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyListOf; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.osgi.service.log.LogService.LOG_ERROR; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.UUID; import org.killbill.billing.ObjectType; import org.killbill.billing.test.helpers.CustomFieldBuilder; import org.killbill.billing.util.api.CustomFieldApiException; import org.killbill.billing.util.api.CustomFieldUserApi; import org.killbill.billing.util.callcontext.CallContext; import org.killbill.billing.util.callcontext.TenantContext; import org.killbill.billing.util.customfield.CustomField; import org.killbill.billing.util.entity.Pagination; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.Lists; private ArgumentCaptor<List<CustomField>> addedFields; @Captor private ArgumentCaptor<List<CustomField>> removedFields; @Mock private TenantContext defaultTenant; @Mock private Pagination<CustomField> pageStart; @Mock private Pagination<CustomField> pageMiddle; @Mock private Pagination<CustomField> pageEnd; @BeforeClass public void init() { initMocks(this); } private void withThreePagesOfSearchResults(TenantContext tenantContext) { when(customFieldApi.searchCustomFields(anyString(), eq(0L), eq(PAGE_SIZE), eq(tenantContext)))// .thenReturn(pageStart); when(customFieldApi.searchCustomFields(anyString(), eq(PAGE_SIZE), eq(PAGE_SIZE), eq(tenantContext)))// .thenReturn(pageMiddle); when(customFieldApi.searchCustomFields(anyString(), eq(2 * PAGE_SIZE), eq(PAGE_SIZE), eq(tenantContext)))// .thenReturn(pageEnd); when(pageStart.getNextOffset()).thenReturn(PAGE_SIZE); when(pageMiddle.getNextOffset()).thenReturn(2 * PAGE_SIZE); when(pageEnd.getNextOffset()).thenReturn(null);
CustomFieldBuilder builder = new CustomFieldBuilder().withObjectType(ACCOUNT).withFieldName("toto");
bgandon/killbill-simple-tax-plugin
src/test/java/org/killbill/billing/plugin/simpletax/config/http/TestCustomFieldService.java
// Path: src/test/java/org/killbill/billing/test/helpers/CustomFieldBuilder.java // public static CustomFieldBuilder copy(CustomFieldBuilder that) { // return new CustomFieldBuilder()// // .withObjectType(that.objectType)// // .withObjectId(that.objectId)// // .withFieldName(that.fieldName)// // .withFieldValue(that.fieldValue); // } // // Path: src/test/java/org/killbill/billing/test/helpers/CustomFieldBuilder.java // @SuppressWarnings("javadoc") // public class CustomFieldBuilder implements Builder<CustomField> { // // private UUID objectId; // private ObjectType objectType; // private String fieldName, fieldValue; // // @Override // public CustomField build() { // return ImmutableCustomField.builder()// // .withObjectId(objectId)// // .withObjectType(objectType)// // .withFieldName(fieldName)// // .withFieldValue(fieldValue)// // .build(); // } // // public static CustomFieldBuilder copy(CustomFieldBuilder that) { // return new CustomFieldBuilder()// // .withObjectType(that.objectType)// // .withObjectId(that.objectId)// // .withFieldName(that.fieldName)// // .withFieldValue(that.fieldValue); // } // // public CustomFieldBuilder withObjectId(UUID objectId) { // this.objectId = objectId; // return this; // } // // public CustomFieldBuilder withObjectType(ObjectType objectType) { // this.objectType = objectType; // return this; // } // // public CustomFieldBuilder withFieldName(String fieldName) { // this.fieldName = fieldName; // return this; // } // // public CustomFieldBuilder withFieldValue(String fieldValue) { // this.fieldValue = fieldValue; // return this; // } // }
import static com.google.common.collect.Iterators.forArray; import static com.google.common.collect.Lists.newArrayList; import static java.util.UUID.randomUUID; import static org.apache.commons.lang3.StringUtils.contains; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; import static org.killbill.billing.ErrorCode.UNEXPECTED_ERROR; import static org.killbill.billing.ObjectType.ACCOUNT; import static org.killbill.billing.ObjectType.INVOICE; import static org.killbill.billing.test.helpers.CustomFieldBuilder.copy; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyListOf; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.osgi.service.log.LogService.LOG_ERROR; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.UUID; import org.killbill.billing.ObjectType; import org.killbill.billing.test.helpers.CustomFieldBuilder; import org.killbill.billing.util.api.CustomFieldApiException; import org.killbill.billing.util.api.CustomFieldUserApi; import org.killbill.billing.util.callcontext.CallContext; import org.killbill.billing.util.callcontext.TenantContext; import org.killbill.billing.util.customfield.CustomField; import org.killbill.billing.util.entity.Pagination; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.Lists;
private ArgumentCaptor<List<CustomField>> removedFields; @Mock private TenantContext defaultTenant; @Mock private Pagination<CustomField> pageStart; @Mock private Pagination<CustomField> pageMiddle; @Mock private Pagination<CustomField> pageEnd; @BeforeClass public void init() { initMocks(this); } private void withThreePagesOfSearchResults(TenantContext tenantContext) { when(customFieldApi.searchCustomFields(anyString(), eq(0L), eq(PAGE_SIZE), eq(tenantContext)))// .thenReturn(pageStart); when(customFieldApi.searchCustomFields(anyString(), eq(PAGE_SIZE), eq(PAGE_SIZE), eq(tenantContext)))// .thenReturn(pageMiddle); when(customFieldApi.searchCustomFields(anyString(), eq(2 * PAGE_SIZE), eq(PAGE_SIZE), eq(tenantContext)))// .thenReturn(pageEnd); when(pageStart.getNextOffset()).thenReturn(PAGE_SIZE); when(pageMiddle.getNextOffset()).thenReturn(2 * PAGE_SIZE); when(pageEnd.getNextOffset()).thenReturn(null); CustomFieldBuilder builder = new CustomFieldBuilder().withObjectType(ACCOUNT).withFieldName("toto"); when(pageStart.iterator()).thenReturn(forArray(//
// Path: src/test/java/org/killbill/billing/test/helpers/CustomFieldBuilder.java // public static CustomFieldBuilder copy(CustomFieldBuilder that) { // return new CustomFieldBuilder()// // .withObjectType(that.objectType)// // .withObjectId(that.objectId)// // .withFieldName(that.fieldName)// // .withFieldValue(that.fieldValue); // } // // Path: src/test/java/org/killbill/billing/test/helpers/CustomFieldBuilder.java // @SuppressWarnings("javadoc") // public class CustomFieldBuilder implements Builder<CustomField> { // // private UUID objectId; // private ObjectType objectType; // private String fieldName, fieldValue; // // @Override // public CustomField build() { // return ImmutableCustomField.builder()// // .withObjectId(objectId)// // .withObjectType(objectType)// // .withFieldName(fieldName)// // .withFieldValue(fieldValue)// // .build(); // } // // public static CustomFieldBuilder copy(CustomFieldBuilder that) { // return new CustomFieldBuilder()// // .withObjectType(that.objectType)// // .withObjectId(that.objectId)// // .withFieldName(that.fieldName)// // .withFieldValue(that.fieldValue); // } // // public CustomFieldBuilder withObjectId(UUID objectId) { // this.objectId = objectId; // return this; // } // // public CustomFieldBuilder withObjectType(ObjectType objectType) { // this.objectType = objectType; // return this; // } // // public CustomFieldBuilder withFieldName(String fieldName) { // this.fieldName = fieldName; // return this; // } // // public CustomFieldBuilder withFieldValue(String fieldValue) { // this.fieldValue = fieldValue; // return this; // } // } // Path: src/test/java/org/killbill/billing/plugin/simpletax/config/http/TestCustomFieldService.java import static com.google.common.collect.Iterators.forArray; import static com.google.common.collect.Lists.newArrayList; import static java.util.UUID.randomUUID; import static org.apache.commons.lang3.StringUtils.contains; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; import static org.killbill.billing.ErrorCode.UNEXPECTED_ERROR; import static org.killbill.billing.ObjectType.ACCOUNT; import static org.killbill.billing.ObjectType.INVOICE; import static org.killbill.billing.test.helpers.CustomFieldBuilder.copy; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyListOf; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.osgi.service.log.LogService.LOG_ERROR; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.UUID; import org.killbill.billing.ObjectType; import org.killbill.billing.test.helpers.CustomFieldBuilder; import org.killbill.billing.util.api.CustomFieldApiException; import org.killbill.billing.util.api.CustomFieldUserApi; import org.killbill.billing.util.callcontext.CallContext; import org.killbill.billing.util.callcontext.TenantContext; import org.killbill.billing.util.customfield.CustomField; import org.killbill.billing.util.entity.Pagination; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.Lists; private ArgumentCaptor<List<CustomField>> removedFields; @Mock private TenantContext defaultTenant; @Mock private Pagination<CustomField> pageStart; @Mock private Pagination<CustomField> pageMiddle; @Mock private Pagination<CustomField> pageEnd; @BeforeClass public void init() { initMocks(this); } private void withThreePagesOfSearchResults(TenantContext tenantContext) { when(customFieldApi.searchCustomFields(anyString(), eq(0L), eq(PAGE_SIZE), eq(tenantContext)))// .thenReturn(pageStart); when(customFieldApi.searchCustomFields(anyString(), eq(PAGE_SIZE), eq(PAGE_SIZE), eq(tenantContext)))// .thenReturn(pageMiddle); when(customFieldApi.searchCustomFields(anyString(), eq(2 * PAGE_SIZE), eq(PAGE_SIZE), eq(tenantContext)))// .thenReturn(pageEnd); when(pageStart.getNextOffset()).thenReturn(PAGE_SIZE); when(pageMiddle.getNextOffset()).thenReturn(2 * PAGE_SIZE); when(pageEnd.getNextOffset()).thenReturn(null); CustomFieldBuilder builder = new CustomFieldBuilder().withObjectType(ACCOUNT).withFieldName("toto"); when(pageStart.iterator()).thenReturn(forArray(//
copy(builder).withFieldValue("page0-invoice").withObjectType(INVOICE).build(),//
bgandon/killbill-simple-tax-plugin
src/test/java/org/killbill/billing/plugin/simpletax/util/TestInvoiceHelpers.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/InvoiceHelpers.java // @Nonnull // public static BigDecimal amountWithAdjustments(@Nonnull InvoiceItem item, // @Nonnull Multimap<UUID, InvoiceItem> allAdjustments) { // Iterable<InvoiceItem> adjustments = allAdjustments.get(item.getId()); // BigDecimal amount = sumItems(adjustments); // if (item.getAmount() != null) { // amount = amount.add(item.getAmount()); // } // return amount; // } // // Path: src/main/java/org/killbill/billing/plugin/simpletax/util/InvoiceHelpers.java // public static BigDecimal sumAmounts(Iterable<BigDecimal> amounts) { // BigDecimal sum = ZERO; // for (BigDecimal amount : amounts) { // sum = sum.add(amount); // } // return sum; // } // // Path: src/main/java/org/killbill/billing/plugin/simpletax/util/InvoiceHelpers.java // @Nonnull // public static BigDecimal sumItems(@Nullable Iterable<InvoiceItem> invoiceItems) { // if (invoiceItems == null) { // return ZERO; // } // BigDecimal sum = ZERO; // for (InvoiceItem item : invoiceItems) { // if (item.getAmount() != null) { // sum = sum.add(item.getAmount()); // } // } // return sum; // } // // Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public static void assertEqualsIgnoreScale(BigDecimal actual, BigDecimal expected) { // assertTrue(expected.compareTo(actual) == 0); // } // // Path: src/test/java/org/killbill/billing/test/helpers/InvoiceItemBuilder.java // @SuppressWarnings("javadoc") // public class InvoiceItemBuilder implements Builder<InvoiceItem> { // private Invoice invoice; // private InvoiceItemType type; // private LocalDate startDate, endDate; // private BigDecimal amount; // private String planName; // private Promise<InvoiceItem> linkedItem; // // private Promise<InvoiceItem> builtItemHolder; // // public static InvoiceItemBuilder item() { // return new InvoiceItemBuilder(); // } // // @Override // public InvoiceItem build() { // UUID id = randomUUID(); // UUID invoiceId = invoice == null ? null : invoice.getId(); // UUID accountId = invoice == null ? null : invoice.getAccountId(); // String description = type == null ? null : "Test " + type.name(); // UUID linkedItemId = linkedItem == null ? null : linkedItem.get().getId(); // PluginInvoiceItem item = new PluginInvoiceItem(id, type, invoiceId, accountId, startDate, endDate, amount, EUR, // description, null, null, planName, null, null, linkedItemId, null, null, null); // if (builtItemHolder != null) { // builtItemHolder.resolve(item); // } // return item; // } // // public InvoiceItemBuilder withInvoice(Invoice invoice) { // this.invoice = invoice; // return this; // } // // public InvoiceItemBuilder withType(InvoiceItemType type) { // this.type = type; // return this; // } // // public InvoiceItemBuilder withStartDate(LocalDate startDate) { // this.startDate = startDate; // return this; // } // // public InvoiceItemBuilder withEndDate(LocalDate endDate) { // this.endDate = endDate; // return this; // } // // public InvoiceItemBuilder withAmount(BigDecimal amount) { // this.amount = amount; // return this; // } // // public InvoiceItemBuilder withPlanName(String planName) { // this.planName = planName; // return this; // } // // public InvoiceItemBuilder withLinkedItem(Promise<InvoiceItem> linkedItem) { // this.linkedItem = linkedItem; // return this; // } // // public InvoiceItemBuilder thenSaveTo(Promise<InvoiceItem> itemHolder) { // builtItemHolder = itemHolder; // return this; // } // }
import static com.google.common.collect.Lists.newArrayList; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static java.math.BigDecimal.ZERO; import static java.math.BigDecimal.valueOf; import static java.util.Arrays.asList; import static org.killbill.billing.plugin.simpletax.util.InvoiceHelpers.amountWithAdjustments; import static org.killbill.billing.plugin.simpletax.util.InvoiceHelpers.sumAmounts; import static org.killbill.billing.plugin.simpletax.util.InvoiceHelpers.sumItems; import static org.killbill.billing.test.helpers.TestUtil.assertEqualsIgnoreScale; import java.math.BigDecimal; import java.util.UUID; import org.killbill.billing.invoice.api.InvoiceItem; import org.killbill.billing.test.helpers.InvoiceItemBuilder; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap;
/* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.util; /** * Tests for {@link InvoiceHelpers}. * * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class TestInvoiceHelpers { private static final BigDecimal NINE = valueOf(9L); private static final BigDecimal ELEVEN = valueOf(11L); private static final BigDecimal EIGHTTEEN = valueOf(18L); private InvoiceItem itemA, itemB, itemC, itemD; @BeforeClass public void init() {
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/InvoiceHelpers.java // @Nonnull // public static BigDecimal amountWithAdjustments(@Nonnull InvoiceItem item, // @Nonnull Multimap<UUID, InvoiceItem> allAdjustments) { // Iterable<InvoiceItem> adjustments = allAdjustments.get(item.getId()); // BigDecimal amount = sumItems(adjustments); // if (item.getAmount() != null) { // amount = amount.add(item.getAmount()); // } // return amount; // } // // Path: src/main/java/org/killbill/billing/plugin/simpletax/util/InvoiceHelpers.java // public static BigDecimal sumAmounts(Iterable<BigDecimal> amounts) { // BigDecimal sum = ZERO; // for (BigDecimal amount : amounts) { // sum = sum.add(amount); // } // return sum; // } // // Path: src/main/java/org/killbill/billing/plugin/simpletax/util/InvoiceHelpers.java // @Nonnull // public static BigDecimal sumItems(@Nullable Iterable<InvoiceItem> invoiceItems) { // if (invoiceItems == null) { // return ZERO; // } // BigDecimal sum = ZERO; // for (InvoiceItem item : invoiceItems) { // if (item.getAmount() != null) { // sum = sum.add(item.getAmount()); // } // } // return sum; // } // // Path: src/test/java/org/killbill/billing/test/helpers/TestUtil.java // public static void assertEqualsIgnoreScale(BigDecimal actual, BigDecimal expected) { // assertTrue(expected.compareTo(actual) == 0); // } // // Path: src/test/java/org/killbill/billing/test/helpers/InvoiceItemBuilder.java // @SuppressWarnings("javadoc") // public class InvoiceItemBuilder implements Builder<InvoiceItem> { // private Invoice invoice; // private InvoiceItemType type; // private LocalDate startDate, endDate; // private BigDecimal amount; // private String planName; // private Promise<InvoiceItem> linkedItem; // // private Promise<InvoiceItem> builtItemHolder; // // public static InvoiceItemBuilder item() { // return new InvoiceItemBuilder(); // } // // @Override // public InvoiceItem build() { // UUID id = randomUUID(); // UUID invoiceId = invoice == null ? null : invoice.getId(); // UUID accountId = invoice == null ? null : invoice.getAccountId(); // String description = type == null ? null : "Test " + type.name(); // UUID linkedItemId = linkedItem == null ? null : linkedItem.get().getId(); // PluginInvoiceItem item = new PluginInvoiceItem(id, type, invoiceId, accountId, startDate, endDate, amount, EUR, // description, null, null, planName, null, null, linkedItemId, null, null, null); // if (builtItemHolder != null) { // builtItemHolder.resolve(item); // } // return item; // } // // public InvoiceItemBuilder withInvoice(Invoice invoice) { // this.invoice = invoice; // return this; // } // // public InvoiceItemBuilder withType(InvoiceItemType type) { // this.type = type; // return this; // } // // public InvoiceItemBuilder withStartDate(LocalDate startDate) { // this.startDate = startDate; // return this; // } // // public InvoiceItemBuilder withEndDate(LocalDate endDate) { // this.endDate = endDate; // return this; // } // // public InvoiceItemBuilder withAmount(BigDecimal amount) { // this.amount = amount; // return this; // } // // public InvoiceItemBuilder withPlanName(String planName) { // this.planName = planName; // return this; // } // // public InvoiceItemBuilder withLinkedItem(Promise<InvoiceItem> linkedItem) { // this.linkedItem = linkedItem; // return this; // } // // public InvoiceItemBuilder thenSaveTo(Promise<InvoiceItem> itemHolder) { // builtItemHolder = itemHolder; // return this; // } // } // Path: src/test/java/org/killbill/billing/plugin/simpletax/util/TestInvoiceHelpers.java import static com.google.common.collect.Lists.newArrayList; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static java.math.BigDecimal.ZERO; import static java.math.BigDecimal.valueOf; import static java.util.Arrays.asList; import static org.killbill.billing.plugin.simpletax.util.InvoiceHelpers.amountWithAdjustments; import static org.killbill.billing.plugin.simpletax.util.InvoiceHelpers.sumAmounts; import static org.killbill.billing.plugin.simpletax.util.InvoiceHelpers.sumItems; import static org.killbill.billing.test.helpers.TestUtil.assertEqualsIgnoreScale; import java.math.BigDecimal; import java.util.UUID; import org.killbill.billing.invoice.api.InvoiceItem; import org.killbill.billing.test.helpers.InvoiceItemBuilder; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; /* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.util; /** * Tests for {@link InvoiceHelpers}. * * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class TestInvoiceHelpers { private static final BigDecimal NINE = valueOf(9L); private static final BigDecimal ELEVEN = valueOf(11L); private static final BigDecimal EIGHTTEEN = valueOf(18L); private InvoiceItem itemA, itemB, itemC, itemD; @BeforeClass public void init() {
itemA = new InvoiceItemBuilder()//
bgandon/killbill-simple-tax-plugin
src/test/java/org/killbill/billing/test/helpers/CustomFieldBuilder.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ImmutableCustomField.java // public class ImmutableCustomField implements CustomField { // // private UUID id; // private DateTime createdDate, updatedDate; // private UUID objectId; // private ObjectType objectType; // private String fieldName, fieldValue; // // private ImmutableCustomField() { // super(); // } // // @Override // public UUID getId() { // return id; // } // // @Override // public DateTime getCreatedDate() { // return createdDate; // } // // @Override // public DateTime getUpdatedDate() { // return updatedDate; // } // // @Override // public UUID getObjectId() { // return objectId; // } // // @Override // public ObjectType getObjectType() { // return objectType; // } // // @Override // public String getFieldName() { // return fieldName; // } // // @Override // public String getFieldValue() { // return fieldValue; // } // // /** // * @return A new {@link ImmutableCustomField} builder. // */ // public static Builder builder() { // return new Builder(); // } // // /** // * @param field // * A template custom field, the data of which should be copied. // * @return A new {@link ImmutableCustomField} builder. // */ // public static Builder builder(CustomField field) { // return new Builder(field); // } // // /** // * A builder class for {@link ImmutableCustomField}s. // * // * @author Benjamin Gandon // */ // public static class Builder { // // private UUID id; // private DateTime createdDate, updatedDate; // private UUID objectId; // private ObjectType objectType; // private String fieldName, fieldValue; // // private Builder() { // super(); // id = randomUUID(); // createdDate = now(); // updatedDate = now(); // } // // private Builder(CustomField src) { // this(); // id = src.getId(); // createdDate = src.getCreatedDate(); // updatedDate = src.getUpdatedDate(); // objectId = src.getObjectId(); // objectType = src.getObjectType(); // fieldName = src.getFieldName(); // fieldValue = src.getFieldValue(); // } // // /** // * @return A new {@link ImmutableCustomField}, with the properties set // * in this builder. // */ // public CustomField build() { // ImmutableCustomField taxField = new ImmutableCustomField(); // taxField.id = id; // taxField.createdDate = createdDate; // taxField.updatedDate = updatedDate; // taxField.objectId = objectId; // taxField.objectType = objectType; // taxField.fieldName = fieldName; // taxField.fieldValue = fieldValue; // return taxField; // } // // /** // * @param objectId // * The object identifier to use. // * @return this builder // */ // public Builder withObjectId(UUID objectId) { // this.objectId = objectId; // updatedDate = now(); // return this; // } // // /** // * @param objectType // * The object type to use. // * @return this builder // */ // public Builder withObjectType(ObjectType objectType) { // this.objectType = objectType; // updatedDate = now(); // return this; // } // // /** // * @param fieldName // * The field name to use. // * @return this builder // */ // public Builder withFieldName(String fieldName) { // this.fieldName = fieldName; // updatedDate = now(); // return this; // } // // /** // * @param fieldValue // * The field value to use. // * @return this builder // */ // public Builder withFieldValue(String fieldValue) { // this.fieldValue = fieldValue; // updatedDate = now(); // return this; // } // } // }
import java.util.UUID; import org.killbill.billing.ObjectType; import org.killbill.billing.plugin.simpletax.util.ImmutableCustomField; import org.killbill.billing.util.customfield.CustomField;
/* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.test.helpers; /** * A {@link Builder} to create {@link ImmutableCustomField} instances. This one * is a little bit different from * {@link org.killbill.billing.plugin.simpletax.util.ImmutableCustomField.Builder} * in that it is tailored for being used in tests. * <p> * Indeed, it implements the {@link Builder} interface, and provides helper * methods like {@link #copy(CustomFieldBuilder)} that are useful in the context * of unit tests and would not make sense in real code. * * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class CustomFieldBuilder implements Builder<CustomField> { private UUID objectId; private ObjectType objectType; private String fieldName, fieldValue; @Override public CustomField build() {
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ImmutableCustomField.java // public class ImmutableCustomField implements CustomField { // // private UUID id; // private DateTime createdDate, updatedDate; // private UUID objectId; // private ObjectType objectType; // private String fieldName, fieldValue; // // private ImmutableCustomField() { // super(); // } // // @Override // public UUID getId() { // return id; // } // // @Override // public DateTime getCreatedDate() { // return createdDate; // } // // @Override // public DateTime getUpdatedDate() { // return updatedDate; // } // // @Override // public UUID getObjectId() { // return objectId; // } // // @Override // public ObjectType getObjectType() { // return objectType; // } // // @Override // public String getFieldName() { // return fieldName; // } // // @Override // public String getFieldValue() { // return fieldValue; // } // // /** // * @return A new {@link ImmutableCustomField} builder. // */ // public static Builder builder() { // return new Builder(); // } // // /** // * @param field // * A template custom field, the data of which should be copied. // * @return A new {@link ImmutableCustomField} builder. // */ // public static Builder builder(CustomField field) { // return new Builder(field); // } // // /** // * A builder class for {@link ImmutableCustomField}s. // * // * @author Benjamin Gandon // */ // public static class Builder { // // private UUID id; // private DateTime createdDate, updatedDate; // private UUID objectId; // private ObjectType objectType; // private String fieldName, fieldValue; // // private Builder() { // super(); // id = randomUUID(); // createdDate = now(); // updatedDate = now(); // } // // private Builder(CustomField src) { // this(); // id = src.getId(); // createdDate = src.getCreatedDate(); // updatedDate = src.getUpdatedDate(); // objectId = src.getObjectId(); // objectType = src.getObjectType(); // fieldName = src.getFieldName(); // fieldValue = src.getFieldValue(); // } // // /** // * @return A new {@link ImmutableCustomField}, with the properties set // * in this builder. // */ // public CustomField build() { // ImmutableCustomField taxField = new ImmutableCustomField(); // taxField.id = id; // taxField.createdDate = createdDate; // taxField.updatedDate = updatedDate; // taxField.objectId = objectId; // taxField.objectType = objectType; // taxField.fieldName = fieldName; // taxField.fieldValue = fieldValue; // return taxField; // } // // /** // * @param objectId // * The object identifier to use. // * @return this builder // */ // public Builder withObjectId(UUID objectId) { // this.objectId = objectId; // updatedDate = now(); // return this; // } // // /** // * @param objectType // * The object type to use. // * @return this builder // */ // public Builder withObjectType(ObjectType objectType) { // this.objectType = objectType; // updatedDate = now(); // return this; // } // // /** // * @param fieldName // * The field name to use. // * @return this builder // */ // public Builder withFieldName(String fieldName) { // this.fieldName = fieldName; // updatedDate = now(); // return this; // } // // /** // * @param fieldValue // * The field value to use. // * @return this builder // */ // public Builder withFieldValue(String fieldValue) { // this.fieldValue = fieldValue; // updatedDate = now(); // return this; // } // } // } // Path: src/test/java/org/killbill/billing/test/helpers/CustomFieldBuilder.java import java.util.UUID; import org.killbill.billing.ObjectType; import org.killbill.billing.plugin.simpletax.util.ImmutableCustomField; import org.killbill.billing.util.customfield.CustomField; /* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.test.helpers; /** * A {@link Builder} to create {@link ImmutableCustomField} instances. This one * is a little bit different from * {@link org.killbill.billing.plugin.simpletax.util.ImmutableCustomField.Builder} * in that it is tailored for being used in tests. * <p> * Indeed, it implements the {@link Builder} interface, and provides helper * methods like {@link #copy(CustomFieldBuilder)} that are useful in the context * of unit tests and would not make sense in real code. * * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class CustomFieldBuilder implements Builder<CustomField> { private UUID objectId; private ObjectType objectType; private String fieldName, fieldValue; @Override public CustomField build() {
return ImmutableCustomField.builder()//
bgandon/killbill-simple-tax-plugin
src/test/java/org/killbill/billing/plugin/simpletax/resolving/fixtures/InitFailingTaxResolver.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/TaxComputationContext.java // public class TaxComputationContext { // // private SimpleTaxConfig config; // // private Account account; // private Country accountTaxCountry; // // private Set<Invoice> allInvoices; // // private Function<InvoiceItem, BigDecimal> toAdjustedAmount; // // private Ordering<InvoiceItem> byAdjustedAmount; // // private TaxCodeService taxCodeService; // // /** // * Constructs an immutable holder for pre-comuted data. // * // * @param config // * The plugin configuration. // * @param account // * The account that the newly created invoice relates to. // * @param accountTaxCountry // * The tax country for the given account. // * @param allInvoices // * The set of all invoices for the given account. // * @param toAdjustedAmount // * A function that computes adjusted amounts for the listed // * invoices of the given account. // * @param byAdjustedAmount // * An ordering that orders {@link InvoiceItem}s by adjusted // * amount. // * @param taxCodeService // * The tax code service to use. // */ // public TaxComputationContext(SimpleTaxConfig config, Account account, Country accountTaxCountry, // Set<Invoice> allInvoices, Function<InvoiceItem, BigDecimal> toAdjustedAmount, // Ordering<InvoiceItem> byAdjustedAmount, TaxCodeService taxCodeService) { // super(); // this.config = config; // this.account = account; // this.accountTaxCountry = accountTaxCountry; // this.allInvoices = allInvoices; // this.toAdjustedAmount = toAdjustedAmount; // this.byAdjustedAmount = byAdjustedAmount; // this.taxCodeService = taxCodeService; // } // // /** // * @return The plugin configuration. // */ // public SimpleTaxConfig getConfig() { // return config; // } // // /** // * @return The account that the newly created invoice relates to. // */ // public Account getAccount() { // return account; // } // // /** // * @return The tax country for the {@linkplain #getAccount() given account}. // */ // public Country getAccountTaxCountry() { // return accountTaxCountry; // } // // /** // * @return The set of all invoices for the {@linkplain #getAccount() given // * account}. // */ // public Set<Invoice> getAllInvoices() { // return allInvoices; // } // // /** // * @return A function that computes adjusted amounts for the // * {@linkplain #getAllInvoices() set of invoices} of the // * {@linkplain #getAccount() given account}. // */ // public Function<InvoiceItem, BigDecimal> toAdjustedAmount() { // return toAdjustedAmount; // } // // /** // * @return An ordering that orders {@link InvoiceItem}s by adjusted amount. // */ // public Ordering<InvoiceItem> byAdjustedAmount() { // return byAdjustedAmount; // } // // /** // * @return The applicable resolver for tax codes. // */ // public TaxCodeService getTaxCodeService() { // return taxCodeService; // } // }
import org.killbill.billing.plugin.simpletax.TaxComputationContext;
/* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.resolving.fixtures; /** * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class InitFailingTaxResolver extends AbstractTaxResolver { static { boom(); } private static void boom() { throw new RuntimeException(); }
// Path: src/main/java/org/killbill/billing/plugin/simpletax/TaxComputationContext.java // public class TaxComputationContext { // // private SimpleTaxConfig config; // // private Account account; // private Country accountTaxCountry; // // private Set<Invoice> allInvoices; // // private Function<InvoiceItem, BigDecimal> toAdjustedAmount; // // private Ordering<InvoiceItem> byAdjustedAmount; // // private TaxCodeService taxCodeService; // // /** // * Constructs an immutable holder for pre-comuted data. // * // * @param config // * The plugin configuration. // * @param account // * The account that the newly created invoice relates to. // * @param accountTaxCountry // * The tax country for the given account. // * @param allInvoices // * The set of all invoices for the given account. // * @param toAdjustedAmount // * A function that computes adjusted amounts for the listed // * invoices of the given account. // * @param byAdjustedAmount // * An ordering that orders {@link InvoiceItem}s by adjusted // * amount. // * @param taxCodeService // * The tax code service to use. // */ // public TaxComputationContext(SimpleTaxConfig config, Account account, Country accountTaxCountry, // Set<Invoice> allInvoices, Function<InvoiceItem, BigDecimal> toAdjustedAmount, // Ordering<InvoiceItem> byAdjustedAmount, TaxCodeService taxCodeService) { // super(); // this.config = config; // this.account = account; // this.accountTaxCountry = accountTaxCountry; // this.allInvoices = allInvoices; // this.toAdjustedAmount = toAdjustedAmount; // this.byAdjustedAmount = byAdjustedAmount; // this.taxCodeService = taxCodeService; // } // // /** // * @return The plugin configuration. // */ // public SimpleTaxConfig getConfig() { // return config; // } // // /** // * @return The account that the newly created invoice relates to. // */ // public Account getAccount() { // return account; // } // // /** // * @return The tax country for the {@linkplain #getAccount() given account}. // */ // public Country getAccountTaxCountry() { // return accountTaxCountry; // } // // /** // * @return The set of all invoices for the {@linkplain #getAccount() given // * account}. // */ // public Set<Invoice> getAllInvoices() { // return allInvoices; // } // // /** // * @return A function that computes adjusted amounts for the // * {@linkplain #getAllInvoices() set of invoices} of the // * {@linkplain #getAccount() given account}. // */ // public Function<InvoiceItem, BigDecimal> toAdjustedAmount() { // return toAdjustedAmount; // } // // /** // * @return An ordering that orders {@link InvoiceItem}s by adjusted amount. // */ // public Ordering<InvoiceItem> byAdjustedAmount() { // return byAdjustedAmount; // } // // /** // * @return The applicable resolver for tax codes. // */ // public TaxCodeService getTaxCodeService() { // return taxCodeService; // } // } // Path: src/test/java/org/killbill/billing/plugin/simpletax/resolving/fixtures/InitFailingTaxResolver.java import org.killbill.billing.plugin.simpletax.TaxComputationContext; /* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.resolving.fixtures; /** * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class InitFailingTaxResolver extends AbstractTaxResolver { static { boom(); } private static void boom() { throw new RuntimeException(); }
public InitFailingTaxResolver(TaxComputationContext ctx) {
bgandon/killbill-simple-tax-plugin
src/main/java/org/killbill/billing/plugin/simpletax/internal/Country.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ShortToStringStyle.java // public static final ToStringStyle SHORT_STYLE = new ShortToStringStyle(); // // Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ConcurrentLazyValue.java // public abstract class ConcurrentLazyValue<T> extends LazyValue<T> { // // /** Whether the value is initialized. */ // private boolean initialized = false; // // /** Stores the managed object. */ // private T value; // // /** // * Returns the value wrapped by this instance, initializing it on first // * access. Subsequent access return the cached value. // * // * @return The object initialized by this {@code LazyValue}. // */ // @Override // public T get() { // if (!initialized) { // synchronized (this) { // if (!initialized) { // value = initialize(); // initialized = true; // } // } // } // return value; // } // // }
import com.google.common.base.Supplier; import com.google.common.collect.ImmutableSet; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Locale.getISOCountries; import static org.killbill.billing.plugin.simpletax.util.ShortToStringStyle.SHORT_STYLE; import java.util.Locale; import java.util.Set; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.killbill.billing.plugin.simpletax.util.ConcurrentLazyValue; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue;
* The preferred language in which the country name should be * expressed. * @return The name of the country in the specified language, or in English. */ public String computeName(Locale language) { return new Locale("", code).getDisplayCountry(language); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } Country rhs = (Country) obj; return new EqualsBuilder().append(code, rhs.code).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder().append(code).toHashCode(); } @Override public String toString() {
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ShortToStringStyle.java // public static final ToStringStyle SHORT_STYLE = new ShortToStringStyle(); // // Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ConcurrentLazyValue.java // public abstract class ConcurrentLazyValue<T> extends LazyValue<T> { // // /** Whether the value is initialized. */ // private boolean initialized = false; // // /** Stores the managed object. */ // private T value; // // /** // * Returns the value wrapped by this instance, initializing it on first // * access. Subsequent access return the cached value. // * // * @return The object initialized by this {@code LazyValue}. // */ // @Override // public T get() { // if (!initialized) { // synchronized (this) { // if (!initialized) { // value = initialize(); // initialized = true; // } // } // } // return value; // } // // } // Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/Country.java import com.google.common.base.Supplier; import com.google.common.collect.ImmutableSet; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Locale.getISOCountries; import static org.killbill.billing.plugin.simpletax.util.ShortToStringStyle.SHORT_STYLE; import java.util.Locale; import java.util.Set; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.killbill.billing.plugin.simpletax.util.ConcurrentLazyValue; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; * The preferred language in which the country name should be * expressed. * @return The name of the country in the specified language, or in English. */ public String computeName(Locale language) { return new Locale("", code).getDisplayCountry(language); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } Country rhs = (Country) obj; return new EqualsBuilder().append(code, rhs.code).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder().append(code).toHashCode(); } @Override public String toString() {
return new ToStringBuilder(this, SHORT_STYLE)//
bgandon/killbill-simple-tax-plugin
src/main/java/org/killbill/billing/plugin/simpletax/internal/TaxCode.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ShortToStringStyle.java // public static final ToStringStyle SHORT_STYLE = new ShortToStringStyle();
import static org.killbill.billing.plugin.simpletax.util.ShortToStringStyle.SHORT_STYLE; import java.math.BigDecimal; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.joda.time.LocalDate;
.append(name, rhs.name)// .append(taxItemDescription, rhs.taxItemDescription)// .append(startingOn, rhs.startingOn)// .append(stoppingOn, rhs.stoppingOn)// .append(country, rhs.country)// .isEquals()) { return false; } // Custom processing BigDecimal equality ignoring scale if (rate == null) { return rhs.rate == null; } return rate.compareTo(rhs.rate) == 0; } @Override public int hashCode() { return new HashCodeBuilder()// .append(name)// .append(taxItemDescription)// // Custom processing BigDecimal hash ignoring scale .append(rate == null ? 0 : rate.toString())// .append(startingOn)// .append(stoppingOn)// .append(country)// .toHashCode(); } @Override public String toString() {
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ShortToStringStyle.java // public static final ToStringStyle SHORT_STYLE = new ShortToStringStyle(); // Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/TaxCode.java import static org.killbill.billing.plugin.simpletax.util.ShortToStringStyle.SHORT_STYLE; import java.math.BigDecimal; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.joda.time.LocalDate; .append(name, rhs.name)// .append(taxItemDescription, rhs.taxItemDescription)// .append(startingOn, rhs.startingOn)// .append(stoppingOn, rhs.stoppingOn)// .append(country, rhs.country)// .isEquals()) { return false; } // Custom processing BigDecimal equality ignoring scale if (rate == null) { return rhs.rate == null; } return rate.compareTo(rhs.rate) == 0; } @Override public int hashCode() { return new HashCodeBuilder()// .append(name)// .append(taxItemDescription)// // Custom processing BigDecimal hash ignoring scale .append(rate == null ? 0 : rate.toString())// .append(startingOn)// .append(stoppingOn)// .append(country)// .toHashCode(); } @Override public String toString() {
return new ToStringBuilder(this, SHORT_STYLE)//
bgandon/killbill-simple-tax-plugin
src/test/java/org/killbill/billing/plugin/simpletax/config/http/TestVATINController.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/config/http/VatinController.java // public static final class VATINRsc { // /** // * The identifier of the account this VAT Identification Number belongs // * to. // */ // // TODO: have immutable resources. Convert to final field? // public UUID accountId; // /** The VAT Identification Number. */ // // TODO: have immutable resources. Convert to final field? // public VATIN vatin; // // /** // * Constructs a new VAT Identification Number resource. // * // * @param accountId // * An account identifier. // * @param vatin // * A VAT Identification Number. // */ // @JsonCreator // public VATINRsc(@JsonProperty("accountId") UUID accountId, @JsonProperty("vatin") VATIN vatin) { // // TODO: have more reliable resources. Add // // Precondition.checkNonNull() // this.accountId = accountId; // this.vatin = vatin; // } // } // // Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/VATIN.java // public class VATIN { // // private static final VATINValidator VALIDATOR = new VATINValidator(); // // private String number; // // /** // * @param number // * A valid VAT Identificaiton Number. // * @throws IllegalArgumentException // * When the VAT number is invalid. // */ // @JsonCreator // public VATIN(String number) throws IllegalArgumentException { // super(); // checkArgument(VALIDATOR.apply(number), "Illegal VAT Identification Number: [%s]", number); // this.number = number; // } // // /** // * @return The VAT Identificaiton Number. // */ // @JsonValue // public String getNumber() { // return number; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // VATIN rhs = (VATIN) obj; // return new EqualsBuilder().append(number, rhs.number).isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(number).toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this, SHORT_STYLE)// // .append("number", number)// // .toString(); // } // } // // Path: src/test/java/org/killbill/billing/test/helpers/CustomFieldBuilder.java // @SuppressWarnings("javadoc") // public class CustomFieldBuilder implements Builder<CustomField> { // // private UUID objectId; // private ObjectType objectType; // private String fieldName, fieldValue; // // @Override // public CustomField build() { // return ImmutableCustomField.builder()// // .withObjectId(objectId)// // .withObjectType(objectType)// // .withFieldName(fieldName)// // .withFieldValue(fieldValue)// // .build(); // } // // public static CustomFieldBuilder copy(CustomFieldBuilder that) { // return new CustomFieldBuilder()// // .withObjectType(that.objectType)// // .withObjectId(that.objectId)// // .withFieldName(that.fieldName)// // .withFieldValue(that.fieldValue); // } // // public CustomFieldBuilder withObjectId(UUID objectId) { // this.objectId = objectId; // return this; // } // // public CustomFieldBuilder withObjectType(ObjectType objectType) { // this.objectType = objectType; // return this; // } // // public CustomFieldBuilder withFieldName(String fieldName) { // this.fieldName = fieldName; // return this; // } // // public CustomFieldBuilder withFieldValue(String fieldValue) { // this.fieldValue = fieldValue; // return this; // } // }
import static com.google.common.collect.Lists.newArrayList; import static java.util.UUID.randomUUID; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.UUID; import org.killbill.billing.plugin.api.PluginTenantContext; import org.killbill.billing.plugin.simpletax.config.http.VatinController.VATINRsc; import org.killbill.billing.plugin.simpletax.internal.VATIN; import org.killbill.billing.tenant.api.Tenant; import org.killbill.billing.test.helpers.CustomFieldBuilder; import org.killbill.billing.util.callcontext.TenantContext; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import org.mockito.InjectMocks; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
/* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.config.http; /** * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class TestVATINController { private static final String FR_TEST6_NUM = "FR78666666666"; private static final String FR_TEST7_NUM = "FR89777777777";
// Path: src/main/java/org/killbill/billing/plugin/simpletax/config/http/VatinController.java // public static final class VATINRsc { // /** // * The identifier of the account this VAT Identification Number belongs // * to. // */ // // TODO: have immutable resources. Convert to final field? // public UUID accountId; // /** The VAT Identification Number. */ // // TODO: have immutable resources. Convert to final field? // public VATIN vatin; // // /** // * Constructs a new VAT Identification Number resource. // * // * @param accountId // * An account identifier. // * @param vatin // * A VAT Identification Number. // */ // @JsonCreator // public VATINRsc(@JsonProperty("accountId") UUID accountId, @JsonProperty("vatin") VATIN vatin) { // // TODO: have more reliable resources. Add // // Precondition.checkNonNull() // this.accountId = accountId; // this.vatin = vatin; // } // } // // Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/VATIN.java // public class VATIN { // // private static final VATINValidator VALIDATOR = new VATINValidator(); // // private String number; // // /** // * @param number // * A valid VAT Identificaiton Number. // * @throws IllegalArgumentException // * When the VAT number is invalid. // */ // @JsonCreator // public VATIN(String number) throws IllegalArgumentException { // super(); // checkArgument(VALIDATOR.apply(number), "Illegal VAT Identification Number: [%s]", number); // this.number = number; // } // // /** // * @return The VAT Identificaiton Number. // */ // @JsonValue // public String getNumber() { // return number; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // VATIN rhs = (VATIN) obj; // return new EqualsBuilder().append(number, rhs.number).isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(number).toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this, SHORT_STYLE)// // .append("number", number)// // .toString(); // } // } // // Path: src/test/java/org/killbill/billing/test/helpers/CustomFieldBuilder.java // @SuppressWarnings("javadoc") // public class CustomFieldBuilder implements Builder<CustomField> { // // private UUID objectId; // private ObjectType objectType; // private String fieldName, fieldValue; // // @Override // public CustomField build() { // return ImmutableCustomField.builder()// // .withObjectId(objectId)// // .withObjectType(objectType)// // .withFieldName(fieldName)// // .withFieldValue(fieldValue)// // .build(); // } // // public static CustomFieldBuilder copy(CustomFieldBuilder that) { // return new CustomFieldBuilder()// // .withObjectType(that.objectType)// // .withObjectId(that.objectId)// // .withFieldName(that.fieldName)// // .withFieldValue(that.fieldValue); // } // // public CustomFieldBuilder withObjectId(UUID objectId) { // this.objectId = objectId; // return this; // } // // public CustomFieldBuilder withObjectType(ObjectType objectType) { // this.objectType = objectType; // return this; // } // // public CustomFieldBuilder withFieldName(String fieldName) { // this.fieldName = fieldName; // return this; // } // // public CustomFieldBuilder withFieldValue(String fieldValue) { // this.fieldValue = fieldValue; // return this; // } // } // Path: src/test/java/org/killbill/billing/plugin/simpletax/config/http/TestVATINController.java import static com.google.common.collect.Lists.newArrayList; import static java.util.UUID.randomUUID; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.UUID; import org.killbill.billing.plugin.api.PluginTenantContext; import org.killbill.billing.plugin.simpletax.config.http.VatinController.VATINRsc; import org.killbill.billing.plugin.simpletax.internal.VATIN; import org.killbill.billing.tenant.api.Tenant; import org.killbill.billing.test.helpers.CustomFieldBuilder; import org.killbill.billing.util.callcontext.TenantContext; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import org.mockito.InjectMocks; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.config.http; /** * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class TestVATINController { private static final String FR_TEST6_NUM = "FR78666666666"; private static final String FR_TEST7_NUM = "FR89777777777";
private static final VATIN FR_TEST6 = new VATIN(FR_TEST6_NUM);
bgandon/killbill-simple-tax-plugin
src/test/java/org/killbill/billing/plugin/simpletax/config/http/TestVATINController.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/config/http/VatinController.java // public static final class VATINRsc { // /** // * The identifier of the account this VAT Identification Number belongs // * to. // */ // // TODO: have immutable resources. Convert to final field? // public UUID accountId; // /** The VAT Identification Number. */ // // TODO: have immutable resources. Convert to final field? // public VATIN vatin; // // /** // * Constructs a new VAT Identification Number resource. // * // * @param accountId // * An account identifier. // * @param vatin // * A VAT Identification Number. // */ // @JsonCreator // public VATINRsc(@JsonProperty("accountId") UUID accountId, @JsonProperty("vatin") VATIN vatin) { // // TODO: have more reliable resources. Add // // Precondition.checkNonNull() // this.accountId = accountId; // this.vatin = vatin; // } // } // // Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/VATIN.java // public class VATIN { // // private static final VATINValidator VALIDATOR = new VATINValidator(); // // private String number; // // /** // * @param number // * A valid VAT Identificaiton Number. // * @throws IllegalArgumentException // * When the VAT number is invalid. // */ // @JsonCreator // public VATIN(String number) throws IllegalArgumentException { // super(); // checkArgument(VALIDATOR.apply(number), "Illegal VAT Identification Number: [%s]", number); // this.number = number; // } // // /** // * @return The VAT Identificaiton Number. // */ // @JsonValue // public String getNumber() { // return number; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // VATIN rhs = (VATIN) obj; // return new EqualsBuilder().append(number, rhs.number).isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(number).toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this, SHORT_STYLE)// // .append("number", number)// // .toString(); // } // } // // Path: src/test/java/org/killbill/billing/test/helpers/CustomFieldBuilder.java // @SuppressWarnings("javadoc") // public class CustomFieldBuilder implements Builder<CustomField> { // // private UUID objectId; // private ObjectType objectType; // private String fieldName, fieldValue; // // @Override // public CustomField build() { // return ImmutableCustomField.builder()// // .withObjectId(objectId)// // .withObjectType(objectType)// // .withFieldName(fieldName)// // .withFieldValue(fieldValue)// // .build(); // } // // public static CustomFieldBuilder copy(CustomFieldBuilder that) { // return new CustomFieldBuilder()// // .withObjectType(that.objectType)// // .withObjectId(that.objectId)// // .withFieldName(that.fieldName)// // .withFieldValue(that.fieldValue); // } // // public CustomFieldBuilder withObjectId(UUID objectId) { // this.objectId = objectId; // return this; // } // // public CustomFieldBuilder withObjectType(ObjectType objectType) { // this.objectType = objectType; // return this; // } // // public CustomFieldBuilder withFieldName(String fieldName) { // this.fieldName = fieldName; // return this; // } // // public CustomFieldBuilder withFieldValue(String fieldValue) { // this.fieldValue = fieldValue; // return this; // } // }
import static com.google.common.collect.Lists.newArrayList; import static java.util.UUID.randomUUID; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.UUID; import org.killbill.billing.plugin.api.PluginTenantContext; import org.killbill.billing.plugin.simpletax.config.http.VatinController.VATINRsc; import org.killbill.billing.plugin.simpletax.internal.VATIN; import org.killbill.billing.tenant.api.Tenant; import org.killbill.billing.test.helpers.CustomFieldBuilder; import org.killbill.billing.util.callcontext.TenantContext; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import org.mockito.InjectMocks; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
// When Object resources = controller.listVatins(randomUUID(), tenant); // Then assertNotNull(resources); assertTrue(resources instanceof List); assertEquals(((List<?>) resources).size(), 0); } private static <T> List<T> check(Iterable<?> iterable, Class<T> type) { if (iterable == null) { return null; } List<T> checked = newArrayList(); int idx = 0; for (Object obj : iterable) { if (!type.isInstance(obj)) { throw new ClassCastException("cannot cast list element #" + idx + " of [" + obj + "] to " + type.getName()); } checked.add(type.cast(obj)); ++idx; } return checked; } @Test(groups = "fast") public void shouldListVATINs() throws Exception { // Given UUID accountId = randomUUID();
// Path: src/main/java/org/killbill/billing/plugin/simpletax/config/http/VatinController.java // public static final class VATINRsc { // /** // * The identifier of the account this VAT Identification Number belongs // * to. // */ // // TODO: have immutable resources. Convert to final field? // public UUID accountId; // /** The VAT Identification Number. */ // // TODO: have immutable resources. Convert to final field? // public VATIN vatin; // // /** // * Constructs a new VAT Identification Number resource. // * // * @param accountId // * An account identifier. // * @param vatin // * A VAT Identification Number. // */ // @JsonCreator // public VATINRsc(@JsonProperty("accountId") UUID accountId, @JsonProperty("vatin") VATIN vatin) { // // TODO: have more reliable resources. Add // // Precondition.checkNonNull() // this.accountId = accountId; // this.vatin = vatin; // } // } // // Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/VATIN.java // public class VATIN { // // private static final VATINValidator VALIDATOR = new VATINValidator(); // // private String number; // // /** // * @param number // * A valid VAT Identificaiton Number. // * @throws IllegalArgumentException // * When the VAT number is invalid. // */ // @JsonCreator // public VATIN(String number) throws IllegalArgumentException { // super(); // checkArgument(VALIDATOR.apply(number), "Illegal VAT Identification Number: [%s]", number); // this.number = number; // } // // /** // * @return The VAT Identificaiton Number. // */ // @JsonValue // public String getNumber() { // return number; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // VATIN rhs = (VATIN) obj; // return new EqualsBuilder().append(number, rhs.number).isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(number).toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this, SHORT_STYLE)// // .append("number", number)// // .toString(); // } // } // // Path: src/test/java/org/killbill/billing/test/helpers/CustomFieldBuilder.java // @SuppressWarnings("javadoc") // public class CustomFieldBuilder implements Builder<CustomField> { // // private UUID objectId; // private ObjectType objectType; // private String fieldName, fieldValue; // // @Override // public CustomField build() { // return ImmutableCustomField.builder()// // .withObjectId(objectId)// // .withObjectType(objectType)// // .withFieldName(fieldName)// // .withFieldValue(fieldValue)// // .build(); // } // // public static CustomFieldBuilder copy(CustomFieldBuilder that) { // return new CustomFieldBuilder()// // .withObjectType(that.objectType)// // .withObjectId(that.objectId)// // .withFieldName(that.fieldName)// // .withFieldValue(that.fieldValue); // } // // public CustomFieldBuilder withObjectId(UUID objectId) { // this.objectId = objectId; // return this; // } // // public CustomFieldBuilder withObjectType(ObjectType objectType) { // this.objectType = objectType; // return this; // } // // public CustomFieldBuilder withFieldName(String fieldName) { // this.fieldName = fieldName; // return this; // } // // public CustomFieldBuilder withFieldValue(String fieldValue) { // this.fieldValue = fieldValue; // return this; // } // } // Path: src/test/java/org/killbill/billing/plugin/simpletax/config/http/TestVATINController.java import static com.google.common.collect.Lists.newArrayList; import static java.util.UUID.randomUUID; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.UUID; import org.killbill.billing.plugin.api.PluginTenantContext; import org.killbill.billing.plugin.simpletax.config.http.VatinController.VATINRsc; import org.killbill.billing.plugin.simpletax.internal.VATIN; import org.killbill.billing.tenant.api.Tenant; import org.killbill.billing.test.helpers.CustomFieldBuilder; import org.killbill.billing.util.callcontext.TenantContext; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import org.mockito.InjectMocks; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; // When Object resources = controller.listVatins(randomUUID(), tenant); // Then assertNotNull(resources); assertTrue(resources instanceof List); assertEquals(((List<?>) resources).size(), 0); } private static <T> List<T> check(Iterable<?> iterable, Class<T> type) { if (iterable == null) { return null; } List<T> checked = newArrayList(); int idx = 0; for (Object obj : iterable) { if (!type.isInstance(obj)) { throw new ClassCastException("cannot cast list element #" + idx + " of [" + obj + "] to " + type.getName()); } checked.add(type.cast(obj)); ++idx; } return checked; } @Test(groups = "fast") public void shouldListVATINs() throws Exception { // Given UUID accountId = randomUUID();
CustomFieldBuilder builder = new CustomFieldBuilder().withObjectId(accountId);
bgandon/killbill-simple-tax-plugin
src/test/java/org/killbill/billing/plugin/simpletax/util/TestShortToStringStyle.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ShortToStringStyle.java // public static final ToStringStyle SHORT_STYLE = new ShortToStringStyle();
import static org.killbill.billing.plugin.simpletax.util.ShortToStringStyle.SHORT_STYLE; import static org.testng.Assert.assertEquals; import java.lang.reflect.Method; import org.apache.commons.lang3.builder.ToStringStyle; import org.testng.annotations.Test;
/* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.util; /** * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class TestShortToStringStyle { @Test(groups = "fast") public void shouldPreserveSingletonNature() throws Exception { // Given Method readResolve = ShortToStringStyle.class.getDeclaredMethod("readResolve"); readResolve.setAccessible(true);
// Path: src/main/java/org/killbill/billing/plugin/simpletax/util/ShortToStringStyle.java // public static final ToStringStyle SHORT_STYLE = new ShortToStringStyle(); // Path: src/test/java/org/killbill/billing/plugin/simpletax/util/TestShortToStringStyle.java import static org.killbill.billing.plugin.simpletax.util.ShortToStringStyle.SHORT_STYLE; import static org.testng.Assert.assertEquals; import java.lang.reflect.Method; import org.apache.commons.lang3.builder.ToStringStyle; import org.testng.annotations.Test; /* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.util; /** * @author Benjamin Gandon */ @SuppressWarnings("javadoc") public class TestShortToStringStyle { @Test(groups = "fast") public void shouldPreserveSingletonNature() throws Exception { // Given Method readResolve = ShortToStringStyle.class.getDeclaredMethod("readResolve"); readResolve.setAccessible(true);
ToStringStyle obj = SHORT_STYLE;
bgandon/killbill-simple-tax-plugin
src/main/java/org/killbill/billing/plugin/simpletax/config/http/VatinController.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/config/http/CustomFieldService.java // public static final String VATIN_CUSTOM_FIELD_NAME = "VATIdNum"; // // Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/VATIN.java // public class VATIN { // // private static final VATINValidator VALIDATOR = new VATINValidator(); // // private String number; // // /** // * @param number // * A valid VAT Identificaiton Number. // * @throws IllegalArgumentException // * When the VAT number is invalid. // */ // @JsonCreator // public VATIN(String number) throws IllegalArgumentException { // super(); // checkArgument(VALIDATOR.apply(number), "Illegal VAT Identification Number: [%s]", number); // this.number = number; // } // // /** // * @return The VAT Identificaiton Number. // */ // @JsonValue // public String getNumber() { // return number; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // VATIN rhs = (VATIN) obj; // return new EqualsBuilder().append(number, rhs.number).isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(number).toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this, SHORT_STYLE)// // .append("number", number)// // .toString(); // } // }
import org.killbill.billing.util.customfield.CustomField; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import static com.google.common.collect.Lists.newArrayList; import static org.killbill.billing.plugin.simpletax.config.http.CustomFieldService.VATIN_CUSTOM_FIELD_NAME; import static org.osgi.service.log.LogService.LOG_ERROR; import java.util.List; import java.util.UUID; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.killbill.billing.plugin.api.PluginTenantContext; import org.killbill.billing.plugin.simpletax.internal.VATIN; import org.killbill.billing.tenant.api.Tenant; import org.killbill.billing.util.callcontext.TenantContext;
/* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.config.http; /** * A controller that serves the end points related to VAT Identification Numbers * (VATINs). * * @author Benjamin Gandon */ public class VatinController { private OSGIKillbillLogService logService; private CustomFieldService customFieldService; /** * Constructs a new controller for the end points related to VAT * Identification Numbers (VATINs). * * @param customFieldService * The service to use when accessing custom fields. * @param logService * The Kill Bill log service to use. */ public VatinController(CustomFieldService customFieldService, OSGIKillbillLogService logService) { super(); this.logService = logService; this.customFieldService = customFieldService; } /** * Lists JSON resources for VAT Identification Numbers (VATINs) taking any * restrictions into account. * * @param accountId * Any account on which the VAT Identification Numbers (VATINs) * should be restricted. Might be {@code null}. * @param tenant * The tenant on which to operate. * @return A list of {@linkplain VATINRsc account VAT Identification Number * (VATIN) resources}. Never {@code null}. */ // TODO: return a List<VATINRsc> public Object listVatins(@Nullable UUID accountId, @Nonnull Tenant tenant) { TenantContext tenantContext = new PluginTenantContext(tenant.getId()); List<CustomField> fields; if (accountId == null) { fields = customFieldService
// Path: src/main/java/org/killbill/billing/plugin/simpletax/config/http/CustomFieldService.java // public static final String VATIN_CUSTOM_FIELD_NAME = "VATIdNum"; // // Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/VATIN.java // public class VATIN { // // private static final VATINValidator VALIDATOR = new VATINValidator(); // // private String number; // // /** // * @param number // * A valid VAT Identificaiton Number. // * @throws IllegalArgumentException // * When the VAT number is invalid. // */ // @JsonCreator // public VATIN(String number) throws IllegalArgumentException { // super(); // checkArgument(VALIDATOR.apply(number), "Illegal VAT Identification Number: [%s]", number); // this.number = number; // } // // /** // * @return The VAT Identificaiton Number. // */ // @JsonValue // public String getNumber() { // return number; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // VATIN rhs = (VATIN) obj; // return new EqualsBuilder().append(number, rhs.number).isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(number).toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this, SHORT_STYLE)// // .append("number", number)// // .toString(); // } // } // Path: src/main/java/org/killbill/billing/plugin/simpletax/config/http/VatinController.java import org.killbill.billing.util.customfield.CustomField; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import static com.google.common.collect.Lists.newArrayList; import static org.killbill.billing.plugin.simpletax.config.http.CustomFieldService.VATIN_CUSTOM_FIELD_NAME; import static org.osgi.service.log.LogService.LOG_ERROR; import java.util.List; import java.util.UUID; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.killbill.billing.plugin.api.PluginTenantContext; import org.killbill.billing.plugin.simpletax.internal.VATIN; import org.killbill.billing.tenant.api.Tenant; import org.killbill.billing.util.callcontext.TenantContext; /* * Copyright 2015 Benjamin Gandon * * 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.killbill.billing.plugin.simpletax.config.http; /** * A controller that serves the end points related to VAT Identification Numbers * (VATINs). * * @author Benjamin Gandon */ public class VatinController { private OSGIKillbillLogService logService; private CustomFieldService customFieldService; /** * Constructs a new controller for the end points related to VAT * Identification Numbers (VATINs). * * @param customFieldService * The service to use when accessing custom fields. * @param logService * The Kill Bill log service to use. */ public VatinController(CustomFieldService customFieldService, OSGIKillbillLogService logService) { super(); this.logService = logService; this.customFieldService = customFieldService; } /** * Lists JSON resources for VAT Identification Numbers (VATINs) taking any * restrictions into account. * * @param accountId * Any account on which the VAT Identification Numbers (VATINs) * should be restricted. Might be {@code null}. * @param tenant * The tenant on which to operate. * @return A list of {@linkplain VATINRsc account VAT Identification Number * (VATIN) resources}. Never {@code null}. */ // TODO: return a List<VATINRsc> public Object listVatins(@Nullable UUID accountId, @Nonnull Tenant tenant) { TenantContext tenantContext = new PluginTenantContext(tenant.getId()); List<CustomField> fields; if (accountId == null) { fields = customFieldService
.findAllAccountFieldsByFieldNameAndTenant(VATIN_CUSTOM_FIELD_NAME, tenantContext);
bgandon/killbill-simple-tax-plugin
src/main/java/org/killbill/billing/plugin/simpletax/config/http/VatinController.java
// Path: src/main/java/org/killbill/billing/plugin/simpletax/config/http/CustomFieldService.java // public static final String VATIN_CUSTOM_FIELD_NAME = "VATIdNum"; // // Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/VATIN.java // public class VATIN { // // private static final VATINValidator VALIDATOR = new VATINValidator(); // // private String number; // // /** // * @param number // * A valid VAT Identificaiton Number. // * @throws IllegalArgumentException // * When the VAT number is invalid. // */ // @JsonCreator // public VATIN(String number) throws IllegalArgumentException { // super(); // checkArgument(VALIDATOR.apply(number), "Illegal VAT Identification Number: [%s]", number); // this.number = number; // } // // /** // * @return The VAT Identificaiton Number. // */ // @JsonValue // public String getNumber() { // return number; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // VATIN rhs = (VATIN) obj; // return new EqualsBuilder().append(number, rhs.number).isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(number).toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this, SHORT_STYLE)// // .append("number", number)// // .toString(); // } // }
import org.killbill.billing.util.customfield.CustomField; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import static com.google.common.collect.Lists.newArrayList; import static org.killbill.billing.plugin.simpletax.config.http.CustomFieldService.VATIN_CUSTOM_FIELD_NAME; import static org.osgi.service.log.LogService.LOG_ERROR; import java.util.List; import java.util.UUID; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.killbill.billing.plugin.api.PluginTenantContext; import org.killbill.billing.plugin.simpletax.internal.VATIN; import org.killbill.billing.tenant.api.Tenant; import org.killbill.billing.util.callcontext.TenantContext;
accountId, tenantContext); if (field == null) { return null; } return toVATINJsonOrNull(accountId, field.getFieldValue()); } /** * Persists a new VAT Identification Number value for a given account. * * @param accountId * An account the VAT Identification Number of which should be * modified. Must not be {@code null}. * @param vatinRsc * A new VAT Identification Number resource to persist. Must not * be {@code null}. * @param tenant * The tenant on which to operate. * @return {@code true} if the VAT Identification Number is properly saved, * or {@code false} otherwise. * @throws NullPointerException * When {@code vatinRsc} is {@code null}. */ public boolean saveAccountVatin(@Nonnull UUID accountId, @Nonnull VATINRsc vatinRsc, Tenant tenant) { TenantContext tenantContext = new PluginTenantContext(tenant.getId()); String newValue = vatinRsc.vatin.getNumber(); return customFieldService.saveAccountField(newValue, VATIN_CUSTOM_FIELD_NAME, accountId, tenantContext); } private VATINRsc toVATINJsonOrNull(UUID accountId, String vatin) {
// Path: src/main/java/org/killbill/billing/plugin/simpletax/config/http/CustomFieldService.java // public static final String VATIN_CUSTOM_FIELD_NAME = "VATIdNum"; // // Path: src/main/java/org/killbill/billing/plugin/simpletax/internal/VATIN.java // public class VATIN { // // private static final VATINValidator VALIDATOR = new VATINValidator(); // // private String number; // // /** // * @param number // * A valid VAT Identificaiton Number. // * @throws IllegalArgumentException // * When the VAT number is invalid. // */ // @JsonCreator // public VATIN(String number) throws IllegalArgumentException { // super(); // checkArgument(VALIDATOR.apply(number), "Illegal VAT Identification Number: [%s]", number); // this.number = number; // } // // /** // * @return The VAT Identificaiton Number. // */ // @JsonValue // public String getNumber() { // return number; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj == this) { // return true; // } // if (obj.getClass() != getClass()) { // return false; // } // VATIN rhs = (VATIN) obj; // return new EqualsBuilder().append(number, rhs.number).isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder().append(number).toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this, SHORT_STYLE)// // .append("number", number)// // .toString(); // } // } // Path: src/main/java/org/killbill/billing/plugin/simpletax/config/http/VatinController.java import org.killbill.billing.util.customfield.CustomField; import org.killbill.killbill.osgi.libs.killbill.OSGIKillbillLogService; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import static com.google.common.collect.Lists.newArrayList; import static org.killbill.billing.plugin.simpletax.config.http.CustomFieldService.VATIN_CUSTOM_FIELD_NAME; import static org.osgi.service.log.LogService.LOG_ERROR; import java.util.List; import java.util.UUID; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.killbill.billing.plugin.api.PluginTenantContext; import org.killbill.billing.plugin.simpletax.internal.VATIN; import org.killbill.billing.tenant.api.Tenant; import org.killbill.billing.util.callcontext.TenantContext; accountId, tenantContext); if (field == null) { return null; } return toVATINJsonOrNull(accountId, field.getFieldValue()); } /** * Persists a new VAT Identification Number value for a given account. * * @param accountId * An account the VAT Identification Number of which should be * modified. Must not be {@code null}. * @param vatinRsc * A new VAT Identification Number resource to persist. Must not * be {@code null}. * @param tenant * The tenant on which to operate. * @return {@code true} if the VAT Identification Number is properly saved, * or {@code false} otherwise. * @throws NullPointerException * When {@code vatinRsc} is {@code null}. */ public boolean saveAccountVatin(@Nonnull UUID accountId, @Nonnull VATINRsc vatinRsc, Tenant tenant) { TenantContext tenantContext = new PluginTenantContext(tenant.getId()); String newValue = vatinRsc.vatin.getNumber(); return customFieldService.saveAccountField(newValue, VATIN_CUSTOM_FIELD_NAME, accountId, tenantContext); } private VATINRsc toVATINJsonOrNull(UUID accountId, String vatin) {
VATIN vatinObj;
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/ReviewTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class ReviewTest { @Test public void testDeserializeFromJson() throws IOException {
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/ReviewTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class ReviewTest { @Test public void testDeserializeFromJson() throws IOException {
JsonNode reviewNode = JsonTestUtils.getBusinessResponseJsonNode().path("reviews").get(0);
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/ReviewTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class ReviewTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode reviewNode = JsonTestUtils.getBusinessResponseJsonNode().path("reviews").get(0); Review review = JsonTestUtils.deserializeJson(reviewNode.toString(), Review.class); Assert.assertEquals(reviewNode.path("excerpt").textValue(), review.excerpt()); Assert.assertEquals(reviewNode.path("id").textValue(), review.id()); Assert.assertEquals(new Double(reviewNode.path("rating").asDouble()), review.rating()); Assert.assertEquals(reviewNode.path("rating_image_large_url").textValue(), review.ratingImageLargeUrl()); Assert.assertEquals(reviewNode.path("rating_image_small_url").textValue(), review.ratingImageSmallUrl()); Assert.assertEquals(reviewNode.path("rating_image_url").textValue(), review.ratingImageUrl()); Assert.assertEquals(new Long(reviewNode.path("time_created").asLong()), review.timeCreated()); // User is tested in it's own test. Assert.assertNotNull(review.user()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode reviewNode = JsonTestUtils.getBusinessResponseJsonNode().path("reviews").get(0); Review review = JsonTestUtils.deserializeJson(reviewNode.toString(), Review.class);
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/ReviewTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class ReviewTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode reviewNode = JsonTestUtils.getBusinessResponseJsonNode().path("reviews").get(0); Review review = JsonTestUtils.deserializeJson(reviewNode.toString(), Review.class); Assert.assertEquals(reviewNode.path("excerpt").textValue(), review.excerpt()); Assert.assertEquals(reviewNode.path("id").textValue(), review.id()); Assert.assertEquals(new Double(reviewNode.path("rating").asDouble()), review.rating()); Assert.assertEquals(reviewNode.path("rating_image_large_url").textValue(), review.ratingImageLargeUrl()); Assert.assertEquals(reviewNode.path("rating_image_small_url").textValue(), review.ratingImageSmallUrl()); Assert.assertEquals(reviewNode.path("rating_image_url").textValue(), review.ratingImageUrl()); Assert.assertEquals(new Long(reviewNode.path("time_created").asLong()), review.timeCreated()); // User is tested in it's own test. Assert.assertNotNull(review.user()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode reviewNode = JsonTestUtils.getBusinessResponseJsonNode().path("reviews").get(0); Review review = JsonTestUtils.deserializeJson(reviewNode.toString(), Review.class);
byte[] bytes = SerializationTestUtils.serialize(review);
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/CategoryTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class CategoryTest { @Test public void testDeserializeFromJson() throws IOException {
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/CategoryTest.java import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class CategoryTest { @Test public void testDeserializeFromJson() throws IOException {
JsonNode categoryNode = JsonTestUtils.getBusinessResponseJsonNode().path("categories").get(0);
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/CategoryTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class CategoryTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode categoryNode = JsonTestUtils.getBusinessResponseJsonNode().path("categories").get(0); Category category = JsonTestUtils.deserializeJson(categoryNode.toString(), Category.class); Assert.assertEquals(categoryNode.get(0).textValue(), category.name()); Assert.assertEquals(categoryNode.get(1).textValue(), category.alias()); } @Test(expected = JsonMappingException.class) public void testDeserializationFailedWithNonPairedValue() throws IOException { String categoryJsonString = "[\"Restaurant\"]"; JsonTestUtils.deserializeJson(categoryJsonString, Business.class); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode categoryNode = JsonTestUtils.getBusinessResponseJsonNode().path("categories").get(0); Category category = JsonTestUtils.deserializeJson(categoryNode.toString(), Category.class);
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/CategoryTest.java import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class CategoryTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode categoryNode = JsonTestUtils.getBusinessResponseJsonNode().path("categories").get(0); Category category = JsonTestUtils.deserializeJson(categoryNode.toString(), Category.class); Assert.assertEquals(categoryNode.get(0).textValue(), category.name()); Assert.assertEquals(categoryNode.get(1).textValue(), category.alias()); } @Test(expected = JsonMappingException.class) public void testDeserializationFailedWithNonPairedValue() throws IOException { String categoryJsonString = "[\"Restaurant\"]"; JsonTestUtils.deserializeJson(categoryJsonString, Business.class); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode categoryNode = JsonTestUtils.getBusinessResponseJsonNode().path("categories").get(0); Category category = JsonTestUtils.deserializeJson(categoryNode.toString(), Category.class);
byte[] bytes = SerializationTestUtils.serialize(category);
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/SearchResponseTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class SearchResponseTest { @Test public void testDeserializeFromJson() throws IOException {
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/SearchResponseTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class SearchResponseTest { @Test public void testDeserializeFromJson() throws IOException {
JsonNode searchNode = JsonTestUtils.getSearchResponseJsonNode();
Yelp/yelp-android
src/test/java/com/yelp/clientlib/entities/SearchResponseTest.java
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException;
package com.yelp.clientlib.entities; public class SearchResponseTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode searchNode = JsonTestUtils.getSearchResponseJsonNode(); SearchResponse searchResponse = JsonTestUtils.deserializeJson(searchNode.toString(), SearchResponse.class); Assert.assertEquals(new Integer(searchNode.path("total").asInt()), searchResponse.total()); // The following objects are tested in their own tests. Assert.assertNotNull(searchResponse.region()); Assert.assertNotNull(searchResponse.businesses()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode searchResponseNode = JsonTestUtils.getSearchResponseJsonNode(); SearchResponse searchResponse = JsonTestUtils.deserializeJson( searchResponseNode.toString(), SearchResponse.class );
// Path: src/test/java/com/yelp/clientlib/utils/JsonTestUtils.java // public class JsonTestUtils { // public static final String BUSINESS_RESPONSE_JSON_FILENAME = "businessResponse.json"; // // public static final String SEARCH_RESPONSE_JSON_FILENAME = "searchResponse.json"; // // public static JsonNode getBusinessResponseJsonNode() throws IOException { // return getJsonNodeFromFile(BUSINESS_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getSearchResponseJsonNode() throws IOException { // return getJsonNodeFromFile(SEARCH_RESPONSE_JSON_FILENAME); // } // // public static JsonNode getJsonNodeFromFile(String filename) throws IOException { // File jsonFile = new File(JsonTestUtils.class.getClassLoader().getResource(filename).getFile()); // return new ObjectMapper().readTree(jsonFile); // } // // public static <T> T deserializeJson(String content, Class<T> valueType) throws IOException { // return new ObjectMapper().readValue(content, valueType); // } // } // // Path: src/test/java/com/yelp/clientlib/utils/SerializationTestUtils.java // public class SerializationTestUtils { // // /** // * Serialize an object into a byte array. The object has to implement {@link Serializable} interface. // * // * @param object Object to be serialized. // * @return Byte array serialized from the object. // */ // public static <T extends Serializable> byte[] serialize(T object) throws IOException { // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // objectOutputStream.writeObject(object); // objectOutputStream.close(); // // return byteArrayOutputStream.toByteArray(); // } // // /** // * Deserialize a byte array into an object. The object has to implement {@link Serializable} interface. // * // * @param bytes Byte array to be deserialized. // * @param clazz Class type the object should be deserialized into. // * @return Object deserialized from the byte array. // */ // public static <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) // throws IOException, ClassNotFoundException { // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); // ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); // Object object = objectInputStream.readObject(); // // return clazz.cast(object); // } // } // Path: src/test/java/com/yelp/clientlib/entities/SearchResponseTest.java import com.fasterxml.jackson.databind.JsonNode; import com.yelp.clientlib.utils.JsonTestUtils; import com.yelp.clientlib.utils.SerializationTestUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; package com.yelp.clientlib.entities; public class SearchResponseTest { @Test public void testDeserializeFromJson() throws IOException { JsonNode searchNode = JsonTestUtils.getSearchResponseJsonNode(); SearchResponse searchResponse = JsonTestUtils.deserializeJson(searchNode.toString(), SearchResponse.class); Assert.assertEquals(new Integer(searchNode.path("total").asInt()), searchResponse.total()); // The following objects are tested in their own tests. Assert.assertNotNull(searchResponse.region()); Assert.assertNotNull(searchResponse.businesses()); } @Test public void testSerializable() throws IOException, ClassNotFoundException { JsonNode searchResponseNode = JsonTestUtils.getSearchResponseJsonNode(); SearchResponse searchResponse = JsonTestUtils.deserializeJson( searchResponseNode.toString(), SearchResponse.class );
byte[] bytes = SerializationTestUtils.serialize(searchResponse);